local addonName, ns = ...

---------------------------------------------------------------------------
-- Class colour helper (replaces hardcoded purple everywhere in the UI)
---------------------------------------------------------------------------
local function GetClassColor()
    local _, classFilename = UnitClass("player")
    if classFilename then
        local ok, color = pcall(function()
            return C_ClassColor.GetClassColor(classFilename)
        end)
        if ok and color then
            return color.r, color.g, color.b
        end
        local rc = RAID_CLASS_COLORS and RAID_CLASS_COLORS[classFilename]
        if rc then return rc.r, rc.g, rc.b end
    end
    return 0.7, 0.7, 0.7
end

local CCR, CCG, CCB
local function CC()
    if not CCR then CCR, CCG, CCB = GetClassColor() end
    return CCR, CCG, CCB
end

ns.GetClassColor = CC


local function GetAccent()
    if ns.Theme then return ns.Theme.GetAccent() end
    return 0, 207/255, 1.0
end

---------------------------------------------------------------------------
-- Main window
---------------------------------------------------------------------------
local MainWindow = CreateFrame("Frame", "BrightQoL_MainFrame", UIParent, "BackdropTemplate")
MainWindow:SetSize(950, 650)
MainWindow:SetPoint("CENTER")
MainWindow:SetFrameStrata("DIALOG")
MainWindow:SetMovable(true)
MainWindow:SetResizable(true)
MainWindow:SetResizeBounds(500, 380, 1400, 900)
MainWindow:EnableMouse(true)
MainWindow:RegisterForDrag("LeftButton")
MainWindow:SetScript("OnDragStart", MainWindow.StartMoving)
MainWindow:SetScript("OnDragStop",  MainWindow.StopMovingOrSizing)
MainWindow:Hide()

MainWindow:SetBackdrop({
    bgFile   = "Interface\\Buttons\\WHITE8X8",
    edgeFile = "Interface\\Buttons\\WHITE8X8",
    edgeSize = 1,
    insets   = { left = 1, right = 1, top = 1, bottom = 1 },
})
MainWindow:SetBackdropColor(0.02, 0.02, 0.02, 0.95)
do local ar,ag,ab = GetAccent() MainWindow:SetBackdropBorderColor(ar, ag, ab, 0.7) end

tinsert(UISpecialFrames, MainWindow:GetName())

-- Top accent — class colour
local TopAccent = MainWindow:CreateTexture(nil, "OVERLAY")
TopAccent:SetHeight(3)
TopAccent:SetPoint("TOPLEFT",  1, -1)
TopAccent:SetPoint("TOPRIGHT", -1, -1)

-- Bottom accent — cyan
local BottomAccent = MainWindow:CreateTexture(nil, "OVERLAY")
BottomAccent:SetHeight(2)
BottomAccent:SetPoint("BOTTOMLEFT",  1, 1)
BottomAccent:SetPoint("BOTTOMRIGHT", -1, 1)
do local ar,ag,ab = GetAccent() BottomAccent:SetColorTexture(ar, ag, ab, 0.7) end

-- Close button (BrightQoL style — created after Widgets are loaded, deferred via OnShow hook)
local CloseButton  -- set in ApplyClassColour after Widgets available

-- Resize handle
local ResizeHandle = CreateFrame("Button", nil, MainWindow)
ResizeHandle:SetSize(16, 16)
ResizeHandle:SetPoint("BOTTOMRIGHT", -2, 2)
ResizeHandle:SetNormalTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Up")
ResizeHandle:SetHighlightTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Highlight")
ResizeHandle:SetPushedTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Down")
ResizeHandle:SetScript("OnMouseDown", function() MainWindow:StartSizing("BOTTOMRIGHT") end)
ResizeHandle:SetScript("OnMouseUp",   function() MainWindow:StopMovingOrSizing() end)

---------------------------------------------------------------------------
-- Title bar
---------------------------------------------------------------------------
local TitleBar = CreateFrame("Frame", nil, MainWindow, "BackdropTemplate")
TitleBar:SetHeight(32)
TitleBar:SetPoint("TOPLEFT",  MainWindow, "TOPLEFT",  1,  -4)
TitleBar:SetPoint("TOPRIGHT", MainWindow, "TOPRIGHT", -36, -4)
TitleBar:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
TitleBar:SetBackdropColor(0.01, 0.01, 0.01, 0.9)

local TitleText = TitleBar:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
TitleText:SetPoint("LEFT", TitleBar, "LEFT", 12, 0)

local TitleSep = TitleBar:CreateTexture(nil, "OVERLAY")
TitleSep:SetHeight(1)
TitleSep:SetPoint("BOTTOMLEFT",  TitleBar, "BOTTOMLEFT",  0, 0)
TitleSep:SetPoint("BOTTOMRIGHT", TitleBar, "BOTTOMRIGHT", 0, 0)
do local ar,ag,ab = GetAccent() TitleSep:SetColorTexture(ar, ag, ab, 0.4) end

-- ContentArea and ResetContent are created in UI/Sidebar.lua
-- (anchored to the right of the vertical sidebar panel)

ns.MainFrame = MainWindow

---------------------------------------------------------------------------
-- Apply class colour after login
---------------------------------------------------------------------------
local function ApplyClassColour()
    local r, g, b = ns.GetClassColor()
    TopAccent:SetColorTexture(r, g, b, 1)
    TitleText:SetText(string.format(
        "|cff%02x%02x%02xBright|r|cff00cfff QoL|r  |cff444444/bqol|r",
        r * 255, g * 255, b * 255))

    -- Refresh accent colour on all static elements
    local ar, ag, ab = GetAccent()
    MainWindow:SetBackdropBorderColor(ar, ag, ab, 0.7)
    BottomAccent:SetColorTexture(ar, ag, ab, 0.7)
    TitleSep:SetColorTexture(ar, ag, ab, 0.4)
    -- ContentArea border is refreshed by ns.SidebarRefresh()

    -- Create styled close button once (Widgets available after PLAYER_LOGIN)
    if not CloseButton and ns.Widgets then
        CloseButton = ns.Widgets:CreateButton(MainWindow, {
            text   = "X",
            width  = 26,
            height = 26,
        })
        CloseButton:SetPoint("TOPRIGHT", MainWindow, "TOPRIGHT", -4, -4)
        CloseButton:SetScript("OnClick", function() MainWindow:Hide() end)
    end
end

-- Public refresh — called by General tab when theme settings change
function ns.Theme.RefreshUI()
    -- 1. Apply font to all BrightQoL font objects
    if ns.Widgets and ns.Widgets.ApplyGuiFont then
        ns.Widgets.ApplyGuiFont(ns.Theme.GetFont())
    end
    -- 2. Re-trigger Sidebar to repaint active group/tab highlights
    if ns.SidebarRefresh then ns.SidebarRefresh() end
end

---------------------------------------------------------------------------
-- Slash commands
---------------------------------------------------------------------------
SLASH_BRIGHTQOL1 = "/bqol"
SLASH_BRIGHTQOL2 = "/bright"

SlashCmdList["BRIGHTQOL"] = function()
    if InCombatLockdown() then
        ns:Log("Cannot open settings during combat.", "ff4444")
        return
    end
    if MainWindow:IsShown() then
        MainWindow:Hide()
    else
        MainWindow:Show()
        MainWindow:ResetContent()
        local lastTab = BrightQoL and BrightQoL.config and BrightQoL.config.lastTab
        if lastTab and ns.OpenTab then
            ns:OpenTab(lastTab)
        else
            if ns.InitOptOptions then ns:InitOptOptions() end
        end
    end
end

function BrightQoL_OnAddonCompartmentClick()
    SlashCmdList["BRIGHTQOL"]()
end

---------------------------------------------------------------------------
-- Login
---------------------------------------------------------------------------
local WelcomeFrame = CreateFrame("Frame")

---------------------------------------------------------------------------
-- Blizzard Interface Options registration (Interface > AddOns)
---------------------------------------------------------------------------

local function ToggleMainWindow()
    if MainWindow:IsShown() then
        MainWindow:Hide()
    else
        MainWindow:Show()
        if ns.OpenTab and BrightQoL.config and BrightQoL.config.lastTab then
            ns:OpenTab(BrightQoL.config.lastTab)
        end
    end
end

-- Register with Blizzard Settings (WoW 10.0+)
-- Pattern: canvas panel with title, version, description and an open button
local function RegisterBlizzardSettings()
    if not Settings or not Settings.RegisterCanvasLayoutCategory then return end

    local panel = CreateFrame("Frame")
    panel.name  = "|cffa855f7Bright|r|cff00cfff QoL|r"

    -- Title
    local title = panel:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", 16, -16)
    title:SetText("|cffa855f7Bright|r|cff00cfff QoL|r  |cff888888/bqol|r")

    -- Version
    local ver = panel:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall")
    ver:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
    ver:SetTextColor(0.5, 0.5, 0.5)
    local vStr = (C_AddOns and C_AddOns.GetAddOnMetadata("BrightQoL", "Version"))
              or (GetAddOnMetadata and GetAddOnMetadata("BrightQoL", "Version"))
              or ""
    ver:SetText("Version " .. vStr)

    -- Description
    local desc = panel:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
    desc:SetPoint("TOPLEFT", ver, "BOTTOMLEFT", 0, -12)
    desc:SetWidth(580)
    desc:SetJustifyH("LEFT")
    desc:SetWordWrap(true)
    desc:SetText("Quality of Life improvements for World of Warcraft. Open the BrightQoL panel to configure all modules.")

    -- Open button
    local btn = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    btn:SetSize(160, 26)
    btn:SetPoint("TOPLEFT", desc, "BOTTOMLEFT", 0, -20)
    btn:SetText("Open BrightQoL")
    btn:SetScript("OnClick", function()
        if SettingsPanel and SettingsPanel:IsShown() then
            HideUIPanel(SettingsPanel)
        end
        MainWindow:Show()
        if ns.OpenTab and BrightQoL and BrightQoL.config and BrightQoL.config.lastTab then
            ns:OpenTab(BrightQoL.config.lastTab)
        end
    end)

    local category = Settings.RegisterCanvasLayoutCategory(panel, "BrightQoL")
    Settings.RegisterAddOnCategory(category)
end

-- AddonCompartment click handler (minimap addon compartment button)
function BrightQoL_OnAddonCompartmentClick()
    ToggleMainWindow()
end

WelcomeFrame:RegisterEvent("PLAYER_LOGIN")
WelcomeFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
WelcomeFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_REGEN_DISABLED" then
        -- Auto-close settings when combat starts
        if MainWindow:IsShown() then
            MainWindow:Hide()
            print("|cff00cfffBrightQoL:|r Settings closed - combat started.")
        end
        return
    end
    -- PLAYER_LOGIN
    if ns.Widgets and ns.Widgets.ApplyGuiFont then
        ns.Widgets.ApplyGuiFont(ns.Theme.GetFont())
    end
    ApplyClassColour()
    ns:Log("Loaded. Type |cff00ff00/bqol|r to open settings.")
    RegisterBlizzardSettings()
end)

---------------------------------------------------------------------------
-- Home page
---------------------------------------------------------------------------
function ns:InitHomePage()
    local p = ns.MainFrame.Content
    local r, g, b = CC()

    local logo = p:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
    logo:SetPoint("CENTER", 0, 20)
    logo:SetText(string.format(
        "|cff%02x%02x%02xBright|r|cff00cfff QoL|r",
        r * 255, g * 255, b * 255))

    local sub = p:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    sub:SetPoint("TOP", logo, "BOTTOM", 0, -10)
    sub:SetText("Quality of Life · /bqol")
    sub:SetTextColor(0.5, 0.5, 0.5)

    local ver = p:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    ver:SetPoint("TOP", sub, "BOTTOM", 0, -6)
    local stage  = _G.BrightQoL_VersionStage  or "RELEASE"
    local number = _G.BrightQoL_VersionNumber or "1.0.0"
    ver:SetText(string.format("|cff%02x%02x%02x%s|r |cffaaaaaa%s|r",
        r*255, g*255, b*255, stage, number))
end
