--[[--------------------------------------------------------------------
  PaladinHolyPower - ui/settings_panel/subpanels.lua
  Handles subpanel/tab logic for Settings Panel.
----------------------------------------------------------------------]]

local PHP = _G.PaladinHolyPower
if not PHP then return end

local Util = Util or PHP.Util

local subpanels     = {}
local tabs          = {}
local panelsByOrder = {}

-- Registers a subpanel (tab) with the settings panel.
function PHP.RegisterSubpanel(name, panel, tab, order)
    subpanels[name]     = panel
    tabs[order]         = tab
    panelsByOrder[order] = panel

    -- Set up tab click to show/hide subpanels
    tab:SetScript("OnClick", function()
        PHP.ShowSubpanel(order)
    end)
end

-- Shows the subpanel by numeric tab index or by panel name
function PHP.ShowSubpanel(key)
    -- Hide all subpanels
    for _, panel in pairs(subpanels) do
        if type(panel.Hide) == "function" then panel:Hide() end
    end
    -- Update all tab visuals
    for i, tab in ipairs(tabs) do
        tab.selected = false
        if tab.SetBackdropColor then
            tab:SetBackdropColor(unpack(PHP.TAB_COLOR or { 0.102, 0.102, 0.102, 1 }))
        end
    end

    local panelToShow, tabToHighlight

    if type(key) == "number" then
        -- Look up by order
        panelToShow   = panelsByOrder[key]
        tabToHighlight = tabs[key]
    elseif type(key) == "string" then
        -- Look up by name
        panelToShow = subpanels[key]
        -- Find tab index by panel mapping
        for i, panel in pairs(panelsByOrder) do
            if panel == panelToShow then
                tabToHighlight = tabs[i]
                break
            end
        end
    end

    -- Highlight the selected tab
    if tabToHighlight then
        tabToHighlight.selected = true
        if tabToHighlight.SetBackdropColor then
            tabToHighlight:SetBackdropColor(unpack(PHP.TAB_SELECTED or { 0.22, 0.20, 0.14, 1 }))
        end
    end

    -- Show the panel
    if panelToShow and type(panelToShow.Show) == "function" then
        panelToShow:Show()
    end
end

-- ADDITIVE: Sub-tab registration utility
-- Example usage: PHP.RegisterSubTabs(parent, {"A","B"}, {fnA, fnB})
function PHP.RegisterSubTabs(parent, tabNames, buildFns, opts)
    if not PHP.CreateSubTabs then
        error("PHP.CreateSubTabs not found! (Make sure components/subpanel.lua is loaded first)")
    end
    return PHP.CreateSubTabs(parent, tabNames, buildFns, opts)
end

-- Optionally expose these for debug or advanced features
PHP._subpanels     = subpanels
PHP._tabs          = tabs
PHP._panelsByOrder = panelsByOrder