-- TOG Tools — Main Window
-- Root AceGUI frame containing a TabGroup.
-- Tabs are dynamically built from addon.modules, sorted alphabetically.
-- Each module registers itself in addon.modules with:
--   { tabKey, label, Draw(container), WINDOW_SIZE }

local _, addon = ...
local AceGUI = LibStub("AceGUI-3.0")

-- ---------------------------------------------------------------------------
-- Module
-- ---------------------------------------------------------------------------
local MainWindow = {}
addon.MainWindow = MainWindow

MainWindow.frame     = nil
MainWindow.tabs      = nil
MainWindow.activeTab = nil

-- ---------------------------------------------------------------------------
-- ESC proxy — intercepts ESC before the AceGUI frame sees it
-- ---------------------------------------------------------------------------
local _escProxy = CreateFrame("Frame", "TOGToolsEscProxy", UIParent)
_escProxy:SetSize(1, 1)
_escProxy:SetAlpha(0)
_escProxy:SetPoint("CENTER")
_escProxy:Hide()
tinsert(UISpecialFrames, "TOGToolsEscProxy")

_escProxy:SetScript("OnHide", function()
    if MainWindow.frame then
        MainWindow:Close()
    end
end)

-- ---------------------------------------------------------------------------
-- Build the ordered tab list from registered modules
-- ---------------------------------------------------------------------------
local function BuildTabDefs()
    local defs = {}
    for _, mod in pairs(addon.modules) do
        tinsert(defs, { value = mod.tabKey, text = mod.label })
    end
    table.sort(defs, function(a, b) return a.text < b.text end)
    return defs
end

-- ---------------------------------------------------------------------------
-- Per-tab window sizing
-- Each module may expose WINDOW_SIZE = { width, height, locked=true }
-- or WINDOW_SIZE = { minWidth, minHeight } for resizable tabs.
-- ---------------------------------------------------------------------------
function MainWindow:ApplyTabSize(tabKey)
    if not (self.frame and self.frame.frame) then return end
    local mod = addon.modules[tabKey]
    local spec = mod and mod.WINDOW_SIZE
    if not spec then return end

    local f = self.frame
    if spec.locked then
        f:EnableResize(false)
        if f.frame.SetResizeBounds then
            f.frame:SetResizeBounds(spec.width, spec.height, spec.width, spec.height)
        else
            if f.frame.SetMinResize then f.frame:SetMinResize(spec.width, spec.height) end
            if f.frame.SetMaxResize then f.frame:SetMaxResize(spec.width, spec.height) end
        end
        f.frame:SetWidth(spec.width)
        f.frame:SetHeight(spec.height)
    else
        f:EnableResize(true)
        local minW = spec.minWidth  or 500
        local minH = spec.minHeight or 380
        if f.frame.SetResizeBounds then
            f.frame:SetResizeBounds(minW, minH)
        elseif f.frame.SetMinResize then
            f.frame:SetMinResize(minW, minH)
        end
        local saved = addon.DB.char.frames.mainWindow
        local w = math.max(minW, saved.width  or minW)
        local h = math.max(minH, saved.height or minH)
        f.frame:SetWidth(w)
        f.frame:SetHeight(h)
    end
end

-- ---------------------------------------------------------------------------
-- Open / Close / Toggle
-- ---------------------------------------------------------------------------
function MainWindow:Open(tabKey)
    if self.frame then
        if tabKey then self:SelectTab(tabKey) end
        self.frame.frame:Raise()
        return
    end

    local tabDefs = BuildTabDefs()
    if #tabDefs == 0 then return end

    -- Default to alphabetically first tab
    local defaultTab = tabKey or (tabDefs[1] and tabDefs[1].value)
    self.activeTab = defaultTab

    local f = AceGUI:Create("Frame")
    f:SetTitle("|cffFF8000TOG Tools|r")
    f:SetStatusText("v" .. addon.Version)
    f:SetLayout("Fill")
    f:EnableResize(true)

    local saved = addon.DB.char.frames.mainWindow
    saved.width  = saved.width  or 640
    saved.height = saved.height or 460
    f:SetStatusTable(saved)

    f:SetCallback("OnClose", function(_widget)
        self.frame = nil
        self.tabs  = nil
        _escProxy:Hide()
        AceGUI:Release(_widget)
    end)

    local tg = AceGUI:Create("TabGroup")
    tg:SetTabs(tabDefs)
    tg:SetLayout("Flow")
    tg:SetFullWidth(true)
    tg:SetFullHeight(true)

    tg:SetCallback("OnGroupSelected", function(_widget, _event, group)
        self.activeTab = group
        self:ApplyTabSize(group)
        _widget:ReleaseChildren()
        self:DrawTab(group, _widget)
    end)

    f:AddChild(tg)
    self.frame = f
    self.tabs  = tg

    _escProxy:Show()
    self:ApplyTabSize(defaultTab)
    tg:SelectTab(defaultTab)
end

function MainWindow:Close()
    if self.frame then
        AceGUI:Release(self.frame)
        self.frame = nil
        self.tabs  = nil
    end
    _escProxy:Hide()
end

function MainWindow:Toggle(tabKey)
    if self.frame then
        self:Close()
    else
        self:Open(tabKey)
    end
end

function MainWindow:SelectTab(key)
    if self.tabs then
        self.tabs:SelectTab(key)
    end
end

-- ---------------------------------------------------------------------------
-- Tab drawing — delegates to the module that owns the tab
-- ---------------------------------------------------------------------------
function MainWindow:DrawTab(group, container)
    local mod = addon.modules[group]
    if mod and mod.Draw then
        mod:Draw(container)
    end
end

function MainWindow:Refresh()
    if not (self.frame and self.tabs) then return end
    self.tabs:ReleaseChildren()
    self:DrawTab(self.activeTab, self.tabs)
end
