-- VDS_Components_CanvasCategory
-- ============================================================================
-- categoryDropdown -- WowStyle2DropdownTemplate that picks a Housing catalog
-- category to filter the canvas decor list. Sibling to scopeDropdown
-- (VDS_Components_CanvasScope.lua) -- same template, same SetupMenu pattern,
-- different state slot + selector chain.

VDS = VDS or {}
local Types = VDS.WidgetTypes

local function buildCategoryMenu(_owner, rootDescription)
    local A = VDS.Constants.ACTIONS
    local Selectors = VDS.Selectors

    local function currentCat()
        return VDS.Store:GetState().session.ui.byView.canvas.selectedCategory
    end

    local items = Selectors:Call("canvas.categories.menuItems", VDS.Store:GetState(), {})
    for _, row in ipairs(items) do
        local id, name, count, loading = row.id, row.name, row.count, row.loading
        local label = loading and name or ("%s (%d)"):format(name, count)
        rootDescription:CreateRadio(
            label,
            function() return currentCat() == id end,
            function()
                VDS.Store:Dispatch({ type = A.CANVAS_SET_CATEGORY, payload = { value = id } })
            end
        )
    end
end

Types:Register("categoryDropdown", {
    build = function(parent, spec)
        -- WowStyle2DropdownTemplate: matches scopeDropdown visually.
        -- Selection text auto-renders from selected radio via
        -- DropdownSelectionTextMixin -- no manual SetText needed.
        local dd = CreateFrame("DropdownButton", nil, parent, "WowStyle2DropdownTemplate")
        dd.resizeToTextMinWidth = spec.width
        dd:SetDefaultText("All Categories")
        dd:SetupMenu(buildCategoryMenu)
        VDS.TooltipEngine:AttachFromSpec(dd, spec)
        -- Size set by layout engine post-build via spec.width / spec.height.
        return dd
    end,
    -- Binding fires push() when canvas.category.label changes. Style2 auto-renders
    -- text but we still call GenerateMenu so an open menu refreshes radio state.
    dispatch = {
        fields = { "text" },
        push   = function(widget, _values)
            if widget.GenerateMenu then widget:GenerateMenu() end  -- exception(boundary): GenerateMenu exists once MenuUtil attaches the mixin
        end,
    },
    specFields = { "binding", "width", "height" },
})
