-- HDG_HT_W_ExpansionDonut.lua
-- Donut+Legend showing collected decor counts by expansion.

local _, privateDB = ...
privateDB.HDG_HT = privateDB.HDG_HT or {}
privateDB.HDG_HT.Widgets = privateDB.HDG_HT.Widgets or {}
local W = { id = "expansionDonut", title = "By Expansion" }
privateDB.HDG_HT.Widgets.ExpansionDonut = W

local Patterns = privateDB.HDG_HT.Patterns

local function colorForExp(exp)
    -- HDG_ExpansionData is a global; the function is GetColor (not GetExpansionColor).
    -- Returns a positional {r,g,b} table (NOT named keys) — donut wedges
    -- accept either via SetVertexColor(c[1], c[2], c[3]).
    local ED = _G.HDG_ExpansionData
    if ED and ED.GetColor then
        local c = ED.GetColor(exp)
        if c then return c end
    end
    return { 0.5, 0.5, 0.5 }
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 byExp = (snap and snap.byExp) or {}
        local ED    = _G.HDG_ExpansionData
        -- Sort segments by expansion release order (newest first → matches v2.37
        -- "By Expansion" donut). EXPANSION_ORDER is chronological release order;
        -- iterate in reverse so most-recent shows up first in the wedge sweep.
        local order = (ED and ED.EXPANSION_ORDER) or {}
        local rank  = {}
        for i, name in ipairs(order) do rank[name] = #order - i + 1 end
        local segments = {}
        local total = 0
        for exp, s in pairs(byExp) do
            local collected = s.collected or 0
            segments[#segments + 1] = {
                label = exp,
                value = collected,
                color = colorForExp(exp),
                _rank = rank[exp] or 0,
            }
            total = total + collected
        end
        table.sort(segments, function(a, b)
            if a._rank ~= b._rank then return a._rank > b._rank end
            return a.value > b.value
        end)
        self.pattern:Update({
            segments      = segments,
            centerText    = tostring(total),
            centerSubText = "collected",
        })
    end

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