-- HDG_HT_W_SourceDonut.lua
-- Donut+Legend showing collected decor counts by source type.

local _, privateDB = ...
privateDB.HDG_HT = privateDB.HDG_HT or {}
privateDB.HDG_HT.Widgets = privateDB.HDG_HT.Widgets or {}
local W = { id = "sourceDonut", title = "By Source" }
privateDB.HDG_HT.Widgets.SourceDonut = W

local Patterns = privateDB.HDG_HT.Patterns
local CONFIG   = privateDB.CONFIG

local function colorForSource(id)
    local info = CONFIG and CONFIG.SOURCE_TYPES and CONFIG.SOURCE_TYPES[id]
    return (info and info.color) or { 0.5, 0.5, 0.5 }
end

local function nameForSource(id)
    local info = CONFIG and CONFIG.SOURCE_TYPES and CONFIG.SOURCE_TYPES[id]
    return (info and info.name) or ("Source " .. tostring(id))
end

function W.Create(parent, dims)
    local self = {}
    self.pattern = Patterns.DonutLegend(parent, dims, {
        donutSize  = dims.donutSize or 120,
        holeSize   = dims.holeSize  or 60,
    })

    function self:Refresh(snap)
        local bySource = (snap and snap.bySource) or {}
        local segments = {}
        local collected = 0
        for srcID, s in pairs(bySource) do
            local c = s.collected or 0
            segments[#segments + 1] = {
                label = nameForSource(srcID),
                value = c,
                color = colorForSource(srcID),
            }
            collected = collected + c
        end
        table.sort(segments, function(a, b) return a.value > b.value end)
        local total = (snap and snap.totalAll) or collected
        local pct   = (total > 0) and math.floor(collected / total * 100 + 0.5) or 0
        self.pattern:Update({
            segments      = segments,
            centerText    = pct .. "%",
            centerSubText = string.format("%d / %d", collected, total),
        })
    end

    function self:Resize(w, h) self.pattern:Resize(w, h) end
    return self
end
