-- VDS_Controller_Title
-- ============================================================================
-- Wires OnClick for title-row + config-sidebar checkboxes and buttons.
-- Wire() runs once at boot; no frame creation (cookbook 08).

VDS = VDS or {}
VDS.Controller_Title = VDS.Controller_Title or {}

local C = VDS.Controller_Title
local A = VDS.Constants.ACTIONS

-- Action-name -> dispatch(widget, newValue). Add a row when a new checkbox/button lands.
local DISPATCHERS = {
    SET_LIVE_AUTOSAVE = function(_widget, value)
        VDS.Store:Dispatch({ type = A.LIVE_AUTOSAVE_SET, payload = { value = value } })
    end,
    SET_REPLACE_BLIZZARD = function(_widget, value)
        VDS.Store:Dispatch({ type = A.SET_REPLACE_BLIZZARD, payload = { value = value } })
    end,
    SHOW_HELP = function(_widget, _value)
        if _G.StaticPopup_Show then _G.StaticPopup_Show("VDS_DYE_STUDIO_HELP") end
    end,
    TOGGLE_CONFIG = function(_widget, _value)
        VDS.Store:Dispatch({ type = A.MAIN_CONFIG_TOGGLE })
    end,
    TOGGLE_DEBUG = function(_widget, value)
        VDS.Store:Dispatch({
            type    = A.CONFIG_SET,
            payload = { key = "debug", value = value },
        })
        VDS.Log:SetDebug(value)
    end,
    TOGGLE_MINIMAP = function(_widget, value)
        -- "Show" checkbox -> hide=false for LibDBIcon.
        VDS.Store:Dispatch({
            type    = A.MINIMAP_HIDE_SET,
            payload = { hide = not value },
        })
    end,
    OPEN_DEBUG_LOG = function(_widget, _value)
        -- Mirrors /vds log. Pulls the buffered debug trace into a popup.
        -- Empty buffer if user hasn't enabled Debug Mode (checkbox above).
        VDS.Log:OpenWindow()
    end,
}

function C:Wire(rootFrame)
    if not (rootFrame and rootFrame.widgets) then return end  -- exception(false-positive): Wire-on-empty-rootFrame is a supported no-op (wire smoke contract)

    local specs = VDS.LayoutConfig.widgets
    local ids = {
        "title.configBtn", "title.helpBtn",
        "config.autoSaveCheck", "config.replaceCheck",
        "config.minimapCheck", "config.debugCheck",
        "config.openLogBtn",
    }
    for _, id in ipairs(ids) do
        local widget = rootFrame.widgets[id]
        local spec   = specs[id]
        local action = spec and spec.action  -- exception(optional): action optional in chip specs
        local fn     = action and DISPATCHERS[action]
        if widget and fn then
            -- labeled-checkbox: outer Frame + inner CheckButton at ._check.
            local target = widget._check or widget
            target:SetScript("OnClick", function(self)
                local newValue = self.GetChecked and self:GetChecked() and true or false
                if not self.GetChecked then newValue = true end
                fn(self, newValue)
            end)
        end
    end
end
