local addonName, RF = ...
local T

-------------------------------------------------------------------------------
-- Tab Definitions
-------------------------------------------------------------------------------
local TAB_DEFS = {
    { key = "Roster",     label = "Roster"     },
    { key = "Info",       label = "Info"        },
    { key = "Chat",       label = "Chat"        },
    { key = "Perks",      label = "Perks"       },
    { key = "Management", label = "Management"  },
    { key = "Dashboard",  label = "Health"       },
    { key = "Teams",      label = "Teams"        },
    { key = "Settings",   label = "Settings"    },
}

-------------------------------------------------------------------------------
-- Build Main Frame on ADDON_LOADED
-------------------------------------------------------------------------------
local function CreateMainFrame()
    T = RF.Theme

    local frame = RF:CreateStyledFrame("RosterForgeFrame", UIParent, 1100, 620, {
        title = "RosterForge",
        closable = true,
        movable = true,
        escClose = true,
        combatHide = true,
        applySettings = true,
    })
    frame:SetPoint("CENTER")
    frame:Hide()

    RF.mainFrame = frame

    ---------------------------------------------------------------------------
    -- Guild Name (centered on title bar)
    ---------------------------------------------------------------------------
    local guildLabel = frame.titleBar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    guildLabel:SetFont(guildLabel:GetFont(), RF.FONT_SIZES.large, "")
    guildLabel:SetPoint("CENTER", frame.titleBar, "CENTER", 0, 0)
    guildLabel:SetTextColor(T.textSecondary[1], T.textSecondary[2], T.textSecondary[3])
    guildLabel:SetText("")

    local function UpdateGuildLabel()
        local guildName = GetGuildInfo("player")
        guildLabel:SetText(guildName and ("<" .. guildName .. ">") or "")
    end
    frame:HookScript("OnShow", UpdateGuildLabel)

    ---------------------------------------------------------------------------
    -- Tab Bar (below title bar)
    ---------------------------------------------------------------------------
    local tabBar = RF:CreateTabBar(frame, TAB_DEFS, function(key)
        RF:SwitchTab(key)
    end)
    tabBar:SetPoint("TOPLEFT", frame.titleBar, "BOTTOMLEFT", 8, -2)
    tabBar:SetPoint("TOPRIGHT", frame.titleBar, "BOTTOMRIGHT", -8, -2)
    frame.tabBar = tabBar

    -- Tab divider line
    local tabDivider = frame:CreateTexture(nil, "ARTWORK")
    tabDivider:SetHeight(1)
    tabDivider:SetPoint("TOPLEFT", frame.titleBar, "BOTTOMLEFT", 0, -34)
    tabDivider:SetPoint("TOPRIGHT", frame.titleBar, "BOTTOMRIGHT", 0, -34)
    tabDivider:SetColorTexture(unpack(T.border))
    frame.tabDivider = tabDivider

    ---------------------------------------------------------------------------
    -- Compact Mode Toggle Button (on title bar, left of close button)
    ---------------------------------------------------------------------------
    local compactBtn = CreateFrame("Button", nil, frame.titleBar)
    compactBtn:SetSize(24, 24)
    -- Position to the left of close button (close btn is typically at RIGHT, -4, 0)
    if frame.closeButton then
        compactBtn:SetPoint("RIGHT", frame.closeButton, "LEFT", -2, 0)
    else
        compactBtn:SetPoint("RIGHT", frame.titleBar, "RIGHT", -28, 0)
    end

    local compactLabel = compactBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    compactLabel:SetFont(compactLabel:GetFont(), RF.FONT_SIZES.medium, "")
    compactLabel:SetAllPoints()
    compactLabel:SetText("-")
    compactLabel:SetTextColor(unpack(T.textSecondary))

    compactBtn:SetScript("OnEnter", function()
        compactLabel:SetTextColor(unpack(T.textHighlight))
        GameTooltip:SetOwner(compactBtn, "ANCHOR_TOP")
        GameTooltip:AddLine("Toggle Compact Mode")
        GameTooltip:Show()
    end)
    compactBtn:SetScript("OnLeave", function()
        compactLabel:SetTextColor(unpack(T.textSecondary))
        GameTooltip:Hide()
    end)
    compactBtn:SetScript("OnClick", function()
        RF:ToggleCompactMode()
    end)
    frame.compactBtn = compactBtn

    ---------------------------------------------------------------------------
    -- Content Area (below tabs, above status bar)
    ---------------------------------------------------------------------------
    local contentArea = CreateFrame("Frame", nil, frame)
    contentArea:SetPoint("TOPLEFT", tabDivider, "BOTTOMLEFT", 0, -2)
    contentArea:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 24)
    frame.contentArea = contentArea

    ---------------------------------------------------------------------------
    -- Status Bar
    ---------------------------------------------------------------------------
    local statusBar = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    statusBar:SetHeight(22)
    statusBar:SetPoint("BOTTOMLEFT", 0, 0)
    statusBar:SetPoint("BOTTOMRIGHT", 0, 0)
    statusBar:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1,
    })
    statusBar:SetBackdropColor(unpack(T.bgSecondary))
    statusBar:SetBackdropBorderColor(unpack(T.border))
    frame.statusBar = statusBar

    -- Status bar tooltip
    statusBar:EnableMouse(true)
    statusBar:SetScript("OnEnter", function(self)
        local stats = RF:GetRosterStats()
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:AddLine("Guild Status", 1, 1, 1)
        GameTooltip:AddDoubleLine("Online:", tostring(stats.online), 0.7,0.7,0.7, 0.3,0.9,0.3)
        GameTooltip:AddDoubleLine("Offline:", tostring(stats.offline), 0.7,0.7,0.7, 0.5,0.5,0.5)
        GameTooltip:AddDoubleLine("Total:", tostring(stats.total), 0.7,0.7,0.7, 1,1,1)
        GameTooltip:Show()
    end)
    statusBar:SetScript("OnLeave", function() GameTooltip:Hide() end)

    local statusText = statusBar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    statusText:SetFont(statusText:GetFont(), RF.FONT_SIZES.small, "")
    statusText:SetPoint("LEFT", 8, 0)
    statusText:SetTextColor(unpack(T.textSecondary))
    statusText:SetText("")
    frame.statusText = statusText

    local versionText = statusBar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    versionText:SetFont(versionText:GetFont(), RF.FONT_SIZES.small, "")
    versionText:SetPoint("RIGHT", -8, 0)
    versionText:SetTextColor(unpack(T.textMuted))
    versionText:SetText("By: |cFF3B82F6Waxilliam|r")
    frame.versionText = versionText

    local syncIndicator = statusBar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    syncIndicator:SetFont(syncIndicator:GetFont(), RF.FONT_SIZES.small, "")
    syncIndicator:SetPoint("RIGHT", versionText, "LEFT", -12, 0)
    syncIndicator:SetTextColor(unpack(T.textMuted))
    syncIndicator:SetText("")
    frame.syncIndicator = syncIndicator

    ---------------------------------------------------------------------------
    -- Tab Content Frames (lazy-init, one per tab)
    ---------------------------------------------------------------------------
    frame.tabFrames = {}

    function frame:GetOrCreateTabFrame(key)
        if frame.tabFrames[key] then
            return frame.tabFrames[key]
        end
        local tabFrame = CreateFrame("Frame", nil, contentArea)
        tabFrame:SetAllPoints(contentArea)
        tabFrame:Hide()
        frame.tabFrames[key] = tabFrame
        return tabFrame
    end

    ---------------------------------------------------------------------------
    -- Tab Switching
    ---------------------------------------------------------------------------
    frame.activeTabKey = nil

    -- Default to Roster tab
    tabBar:SetActive("Roster")

    ---------------------------------------------------------------------------
    -- Ctrl+F Search Focus
    ---------------------------------------------------------------------------
    frame:EnableKeyboard(true)
    frame:SetPropagateKeyboardInput(true)
    frame:SetScript("OnKeyDown", function(self, key)
        if InCombatLockdown() then return end
        if key == "F" and IsControlKeyDown() then
            self:SetPropagateKeyboardInput(false)
            local tabFrame = frame.tabFrames[frame.activeTabKey]
            if tabFrame and tabFrame.searchBar then
                tabFrame.searchBar:SetFocus()
            end
        else
            self:SetPropagateKeyboardInput(true)
        end
    end)

    ---------------------------------------------------------------------------
    -- Periodic status bar update (elapsed time)
    ---------------------------------------------------------------------------
    C_Timer.NewTicker(5, function()
        if frame:IsShown() then RF:UpdateStatusBar() end
    end)

    -- Update status bar on roster refresh
    RF:RegisterCallback("ROSTER_REFRESHED", function(_, total, online)
        RF:UpdateStatusBar()
    end)

    -- Update status bar when sync status changes
    RF:RegisterCallback("SYNC_STATUS_CHANGED", function()
        RF:UpdateStatusBar()
    end)
end

-------------------------------------------------------------------------------
-- Switch Tab
-------------------------------------------------------------------------------
function RF:SwitchTab(key)
    local frame = RF.mainFrame
    if not frame then return end

    -- Hide all tab frames
    for _, tf in pairs(frame.tabFrames) do
        tf:Hide()
    end

    frame.activeTabKey = key
    frame.tabBar:SetActive(key)

    -- Initialize tab content on first activation
    local tabFrame = frame:GetOrCreateTabFrame(key)

    if key == "Roster" and not tabFrame.initialized then
        if RF.InitRosterTab then
            RF:InitRosterTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Info" and not tabFrame.initialized then
        if RF.InitInfoTab then
            RF:InitInfoTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Chat" and not tabFrame.initialized then
        if RF.InitChatTab then
            RF:InitChatTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Perks" and not tabFrame.initialized then
        if RF.InitPerksTab then
            RF:InitPerksTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Management" and not tabFrame.initialized then
        if RF.InitManagementTab then
            RF:InitManagementTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Dashboard" and not tabFrame.initialized then
        if RF.InitDashboardTab then
            RF:InitDashboardTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Teams" and not tabFrame.initialized then
        if RF.InitTeamsTab then
            RF:InitTeamsTab(tabFrame)
            tabFrame.initialized = true
        end
    elseif key == "Settings" and not tabFrame.initialized then
        if RF.InitSettingsPanel then
            RF:InitSettingsPanel(tabFrame)
            tabFrame.initialized = true
        end
    end

    tabFrame:Show()

    -- Fire callback so tabs can refresh
    RF:FireCallbacks("SWITCH_TAB", key)
end

-------------------------------------------------------------------------------
-- Compact Mode
-------------------------------------------------------------------------------
function RF:ToggleCompactMode()
    local frame = RF.mainFrame
    if not frame then return end

    frame.isCompact = not frame.isCompact

    if frame.isCompact then
        -- Save current size
        frame._savedWidth = frame:GetWidth()
        frame._savedHeight = frame:GetHeight()

        -- Resize to compact
        frame:SetSize(320, 400)

        -- Hide tab bar and divider
        frame.tabBar:Hide()
        frame.tabDivider:Hide()

        -- Re-anchor content area directly below title bar
        frame.contentArea:ClearAllPoints()
        frame.contentArea:SetPoint("TOPLEFT", frame.titleBar, "BOTTOMLEFT", 0, -2)
        frame.contentArea:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 24)

        -- Switch to Chat tab
        RF:SwitchTab("Chat")
    else
        -- Restore full size
        frame:SetSize(frame._savedWidth or 1100, frame._savedHeight or 620)

        -- Show tab bar and divider
        frame.tabBar:Show()
        frame.tabDivider:Show()

        -- Re-anchor content area below tab divider
        frame.contentArea:ClearAllPoints()
        frame.contentArea:SetPoint("TOPLEFT", frame.tabDivider, "BOTTOMLEFT", 0, -2)
        frame.contentArea:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 24)

        -- Switch to Roster tab
        RF:SwitchTab("Roster")
    end

    -- Persist preference
    if RF.charDB then
        RF.charDB.compactMode = frame.isCompact
    end
end

-------------------------------------------------------------------------------
-- Update Status Bar
-------------------------------------------------------------------------------
function RF:UpdateStatusBar()
    local frame = RF.mainFrame
    if not frame then return end

    local stats = RF:GetRosterStats()
    local elapsed = ""
    if RF._lastRosterRefresh then
        local diff = math.floor(GetTime() - RF._lastRosterRefresh)
        if diff < 60 then
            elapsed = format("  |  Updated %ds ago", diff)
        else
            elapsed = format("  |  Updated %dm ago", math.floor(diff / 60))
        end
    end
    frame.statusText:SetText(
        format("|cFF4ADE80%d|r online / %d total%s", stats.online, stats.total, elapsed)
    )

    -- Sync indicator
    if frame.syncIndicator then
        local syncCount = RF.GetOnlineSyncUsers and RF:GetOnlineSyncUsers() or 0
        if syncCount > 0 then
            frame.syncIndicator:SetText(format("Sync: %d user%s", syncCount, syncCount == 1 and "" or "s"))
        else
            frame.syncIndicator:SetText("")
        end
    end
end

-------------------------------------------------------------------------------
-- Initialize on ADDON_LOADED
-------------------------------------------------------------------------------
RF:RegisterCallback("ADDON_LOADED", function()
    CreateMainFrame()
    -- Auto-switch to Roster tab, restore compact mode if saved
    C_Timer.After(0, function()
        if RF.charDB and RF.charDB.compactMode then
            RF.mainFrame.isCompact = false -- will be toggled to true
            RF:ToggleCompactMode()
        else
            RF:SwitchTab("Roster")
        end
    end)
end)

-- Handle SWITCH_TAB from slash commands
RF:RegisterCallback("SWITCH_TAB", function(_, key)
    if RF.mainFrame and RF.mainFrame.activeTabKey ~= key then
        RF:SwitchTab(key)
    end
end)
