local addonName, ns = ...
local L = ns.L

local cache = {}
local W = ns.Widgets
local C = ns.COLORS

local ALL_MANA_BUFFS = {
    { id = 29166,  name = "Innervate",          class = "Druid"   },
    { id = 64901,  name = "Symbol of Hope",     class = "Priest"  },
    { id = 16191,  name = "Mana Tide Totem",    class = "Shaman"  },
    { id = 388019, name = "Blessing of Winter", class = "Paladin" },
}

local function PlaceSlider(slider, parent, x, y)
    slider:GetParent():ClearAllPoints()
    slider:GetParent():SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
end

-- ============================================================
-- HEALER MANA CONFIG
-- ============================================================

function ns:InitHealerMana()
    local p   = ns.MainFrame.Content
    local db  = BrightQoL.healerMana
    local HMW = ns.HealerManaWatch

    local function refresh()
        if HMW then HMW:Refresh() end
    end

    W:CachedPanel(cache, "healerManaFrame", p, function(f)
        local sf, sc = W:CreateScrollFrame(f, 1300)

        W:CreatePageHeader(sc,
            { { "HEALER", C.BLUE }, { " MANA", C.ORANGE } },
            W.Colorize("Shows mana bars for healers with mana-recovery buff detection.", C.GRAY))

        local RelayoutAll

        -- ============================================================
        -- MASTER TOGGLE
        -- ============================================================

        local masterArea = CreateFrame("Frame", nil, sc, "BackdropTemplate")
        masterArea:SetSize(460, 62)
        masterArea:SetPoint("TOPLEFT", 10, -75)
        masterArea:SetBackdrop({ bgFile = [[Interface\Buttons\WHITE8x8]] })
        masterArea:SetBackdropColor(0.01, 0.56, 0.91, 0.08)

        local masterCB = W:CreateCheckbox(masterArea, {
            label    = "Enable Healer Mana",
            db       = db, key = "enabled",
            x        = 15, y = -8,
            isMaster = true,
            onChange = refresh,
        })

        local unlockCB = W:CreateCheckbox(masterArea, {
            label    = "Unlock Frame",
            db       = db, key = "unlock",
            x        = 15, y = -38,
            template = "ChatConfigCheckButtonTemplate",
            onChange = refresh,
        })
        unlockCB:SetShown(db.enabled)

        local noteText = masterArea:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        noteText:SetPoint("TOPLEFT", 200, -42)
        noteText:SetText(W.Colorize("Enable + Unlock to drag the frame.", C.GRAY))
        noteText:SetWidth(250)
        noteText:SetJustifyH("LEFT")

        -- Settings container
        local settingsContainer = CreateFrame("Frame", nil, sc)
        settingsContainer:SetPoint("TOPLEFT", masterArea, "BOTTOMLEFT", 0, -10)
        settingsContainer:SetPoint("RIGHT", sc, "RIGHT", -10, 0)
        settingsContainer:SetHeight(900)

        -- ============================================================
        -- DISPLAY SECTION
        -- ============================================================

        local displayWrap, displayContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "DISPLAY", startOpen = true,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local DG = ns.Layout:New(2)

        -- Reload note
        local reloadNote = displayContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        reloadNote:SetPoint("TOPLEFT", DG:Col(1), DG:Row(1) + 4)
        reloadNote:SetWidth(500)
        reloadNote:SetJustifyH("LEFT")
        reloadNote:SetText(W.Colorize("Note: If your class can play multiple roles, switching to a healing spec requires a /reload to show this frame.", C.RED))

        -- Row 2: Show Background + Show Border + Border Color
        W:CreateCheckbox(displayContent, {
            label = "Show Background", db = db, key = "showBackground",
            x = DG:Col(1), y = DG:CheckboxY(2),
            onChange = function() if HMW then HMW:ApplyBackdrop() end end,
        })
        W:CreateCheckbox(displayContent, {
            label = "Show Border", db = db, key = "showBorder",
            x = DG:Col(2), y = DG:CheckboxY(2),
            onChange = function() if HMW then HMW:ApplyBackdrop() end end,
        })
        W:CreateColorPicker(displayContent, {
            label    = "Border Color",
            x = DG:Col(2) + 150, y = DG:CheckboxY(2),
            db       = db,
            rKey     = "borderColorR", gKey = "borderColorG", bKey = "borderColorB", classColorKey = "borderUseClassColor",
            onChange = function() if HMW then HMW:ApplyBackdrop() end end,
        })

        -- Row 3: Buff on Right + Show Buff as Icon
        W:CreateCheckbox(displayContent, {
            label = "Buff on the Right", db = db, key = "buffRight",
            x = DG:Col(1), y = DG:CheckboxY(3), onChange = refresh,
        })
        W:CreateCheckbox(displayContent, {
            label = "Show Buff as Icon", db = db, key = "buffIcon",
            x = DG:Col(2), y = DG:CheckboxY(3), onChange = refresh,
        })

        -- Row 4: Font Outline checkbox + Outline Style dropdown
        W:CreateCheckbox(displayContent, {
            label = "Font Outline", db = db, key = "fontOutline",
            x = DG:Col(1), y = DG:CheckboxY(4),
            onChange = function() if HMW then HMW:RefreshRows() end end,
        })
        db.fontOutlineStyle = db.fontOutlineStyle or "OUTLINE"
        W:CreateDropdown(displayContent, {
            label = "Outline Style",
            db = db, key = "fontOutlineStyle",
            options = { "OUTLINE", "THICKOUTLINE", "MONOCHROME" },
            x = DG:Col(2), y = DG:Row(4),
            width = 160,
            globalName = "BrightHMWOutlineDrop",
            onChange = function() if HMW then HMW:RefreshRows() end end,
        })

        -- Row 5: Font Picker
        local fontLbl = displayContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontHighSmall")
        fontLbl:SetPoint("TOPLEFT", DG:Col(1), DG:Row(5) - 2)
        fontLbl:SetText(W.Colorize("FONT", C.BLUE))
        W:CreateFontPicker(displayContent, DG:Col(1), DG:Row(5) - 16,
            db.font or "Fonts\\FRIZQT__.TTF",
            function(path)
                db.font = path
                if HMW then HMW:RefreshRows() end
            end)

        -- Row 7: Scale
        local scaleSlider = W:CreateAdvancedSlider(displayContent,
            W.Colorize("Scale", C.BLUE), 50, 200, DG:Row(7), 5, true,
            function(val) db.scale = val / 100; refresh() end,
            { value = (db.scale or 1.0) * 100 })
        PlaceSlider(scaleSlider, displayContent, DG:Col(1), DG:SliderY(7))

        -- Row 8: Width + Row Height
        local widthSlider = W:CreateAdvancedSlider(displayContent,
            W.Colorize("Width", C.BLUE), 80, 400, DG:Row(8), 10, false,
            function(val) db.width = val; refresh() end,
            { db = db, key = "width", moduleName = "healerMana" })
        PlaceSlider(widthSlider, displayContent, DG:Col(1), DG:SliderY(8))

        local heightSlider = W:CreateAdvancedSlider(displayContent,
            W.Colorize("Row Height", C.BLUE), 10, 40, DG:Row(8), 1, false,
            function(val) db.barHeight = val; refresh() end,
            { db = db, key = "barHeight", moduleName = "healerMana" })
        PlaceSlider(heightSlider, displayContent, DG:Col(2), DG:SliderY(8))

        -- Row 9: Row Spacing + Font Size
        local gapSlider = W:CreateAdvancedSlider(displayContent,
            W.Colorize("Row Spacing", C.BLUE), 0, 10, DG:Row(9), 1, false,
            function(val) db.barGap = val; refresh() end,
            { db = db, key = "barGap", moduleName = "healerMana" })
        PlaceSlider(gapSlider, displayContent, DG:Col(1), DG:SliderY(9))

        local fontSlider = W:CreateAdvancedSlider(displayContent,
            W.Colorize("Font Size", C.BLUE), 7, 20, DG:Row(9), 1, false,
            function(val) db.fontSize = val; refresh() end,
            { db = db, key = "fontSize", moduleName = "healerMana" })
        PlaceSlider(fontSlider, displayContent, DG:Col(2), DG:SliderY(9))

        displayContent:SetHeight(DG:Height(9) + 30)
        displayWrap:RecalcHeight()

        -- ============================================================
        -- TRACKED BUFFS SECTION
        -- ============================================================

        local buffsWrap, buffsContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "TRACKED MANA SPELLS", startOpen = true,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local BG = ns.Layout:New(2)
        for i, info in ipairs(ALL_MANA_BUFFS) do
            local col = ((i - 1) % 2) + 1
            local row = math.ceil(i / 2)
            local label = info.name .. W.Colorize("  (" .. info.class .. ")", C.GRAY)
            W:CreateCheckbox(buffsContent, {
                label    = label,
                x = BG:Col(col), y = BG:CheckboxY(row),
                getValue = function() return db.trackedBuffs and db.trackedBuffs[info.id] and true or false end,
                setValue = function(val)
                    db.trackedBuffs = db.trackedBuffs or {}
                    db.trackedBuffs[info.id] = val and true or nil
                    if HMW then HMW:RebuildActiveBuffs() end
                end,
            })
        end
        buffsContent:SetHeight(BG:Height(math.ceil(#ALL_MANA_BUFFS / 2)))
        buffsWrap:RecalcHeight()

        -- ============================================================
        -- LAYOUT
        -- ============================================================

        local allSections = { displayWrap, buffsWrap }

        RelayoutAll = function()
            for i, s in ipairs(allSections) do
                s:ClearAllPoints()
                if i == 1 then
                    s:SetPoint("TOPLEFT", settingsContainer, "TOPLEFT", 0, 0)
                else
                    s:SetPoint("TOPLEFT", allSections[i-1], "BOTTOMLEFT", 0, -12)
                end
                s:SetPoint("RIGHT", settingsContainer, "RIGHT", 0, 0)
            end
            local totalH = 0
            if db.enabled then
                for _, s in ipairs(allSections) do totalH = totalH + s:GetHeight() + 12 end
            end
            settingsContainer:SetHeight(math.max(totalH, 1))
            sc:SetHeight(math.max(75 + 62 + 10 + totalH + 60, 1300))
        end

        masterCB:HookScript("OnClick", function(self)
            db.enabled = self:GetChecked() and true or false
            refresh()
            unlockCB:SetShown(db.enabled)
            settingsContainer:SetShown(db.enabled)
            RelayoutAll()
        end)
        settingsContainer:SetShown(db.enabled)

        local restoreBtn = W:CreateRestoreDefaultsButton({
            moduleName = "healerMana", parent = sc,
            fixedParent = masterArea,
            yOffset = -10,
            initFunc   = function() ns:InitHealerMana() end,
            onRestore  = function()
                if cache.healerManaFrame then
                    cache.healerManaFrame:Hide()
                    cache.healerManaFrame:SetParent(nil)
                    cache.healerManaFrame = nil
                end
                refresh()
            end,
        })

        RelayoutAll()
        if HMW then HMW:Init() end
    end)
end

-- ============================================================
-- SWIFT STATS CONFIG
-- ============================================================

function ns:InitStats()
    local p  = ns.MainFrame.Content
    local db = BrightQoL.swiftStats
    local SS = ns.Stats

    local function refresh()     if SS then SS:Refresh()     end end
    local function refreshStats() if SS then SS.UpdateStats() end end

    W:CachedPanel(cache, "swiftStatsFrame", p, function(f)
        local sf, sc = W:CreateScrollFrame(f, 1500)

        W:CreatePageHeader(sc,
            { { "STATS", C.BLUE }, { " DISPLAY", C.ORANGE } },
            W.Colorize("Floating text display for secondary, primary and tertiary stats.", C.GRAY))

        local RelayoutAll

        -- ============================================================
        -- MASTER TOGGLE
        -- ============================================================

        local masterArea = CreateFrame("Frame", nil, sc, "BackdropTemplate")
        masterArea:SetSize(460, 62)
        masterArea:SetPoint("TOPLEFT", 10, -75)
        masterArea:SetBackdrop({ bgFile = [[Interface\Buttons\WHITE8x8]] })
        masterArea:SetBackdropColor(0.01, 0.56, 0.91, 0.08)

        local masterCB = W:CreateCheckbox(masterArea, {
            label = "Enable Stats Display",
            db = db, key = "enabled",
            x = 15, y = -8, isMaster = true, onChange = refresh,
        })

        local unlockCB = W:CreateCheckbox(masterArea, {
            label = "Unlock Frame",
            db = db, key = "unlock",
            x = 15, y = -38,
            template = "ChatConfigCheckButtonTemplate",
            onChange = refresh,
        })
        unlockCB:SetShown(db.enabled)

        local noteText = masterArea:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        noteText:SetPoint("TOPLEFT", 200, -42)
        noteText:SetText(W.Colorize("Enable + Unlock to drag the frame.", C.GRAY))
        noteText:SetWidth(250)
        noteText:SetJustifyH("LEFT")

        local settingsContainer = CreateFrame("Frame", nil, sc)
        settingsContainer:SetPoint("TOPLEFT", masterArea, "BOTTOMLEFT", 0, -10)
        settingsContainer:SetPoint("RIGHT", sc, "RIGHT", -10, 0)
        settingsContainer:SetHeight(1200)

        -- ============================================================
        -- DISPLAY SECTION
        -- ============================================================

        local dispWrap, dispContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "DISPLAY", startOpen = true,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local DG = ns.Layout:New(2)

        -- Row 1: Show Background + Show Border
        W:CreateCheckbox(dispContent, {
            label = "Show Background", db = db, key = "showBackground",
            x = DG:Col(1), y = DG:CheckboxY(1),
            onChange = function() if SS then SS:ApplyBackdrop() end end,
        })
        W:CreateCheckbox(dispContent, {
            label = "Show Border", db = db, key = "showBorder",
            x = DG:Col(2), y = DG:CheckboxY(1),
            onChange = function() if SS then SS:ApplyBackdrop() end end,
        })

        W:CreateColorPicker(dispContent, {
            label    = "Border Color",
            x = DG:Col(2) + 150, y = DG:CheckboxY(1),
            db       = db,
            rKey     = "borderColorR", gKey = "borderColorG", bKey = "borderColorB", classColorKey = "borderUseClassColor",
            onChange = function() if ns.Stats then ns.Stats:ApplySettings() end end,
        })

        -- Row 2: Font Size + Scale
        local fontSlider = W:CreateAdvancedSlider(dispContent,
            W.Colorize("Font Size", C.BLUE), 8, 32, DG:Row(2), 1, false,
            function(val) db.fontSize = val; refresh() end,
            { db = db, key = "fontSize", moduleName = "swiftStats" })
        PlaceSlider(fontSlider, dispContent, DG:Col(1), DG:SliderY(2))

        local scaleSlider = W:CreateAdvancedSlider(dispContent,
            W.Colorize("Scale", C.BLUE), 50, 200, DG:Row(2), 5, true,
            function(val) db.scale = val / 100; refresh() end,
            { value = (db.scale or 1.0) * 100 })
        PlaceSlider(scaleSlider, dispContent, DG:Col(2), DG:SliderY(2))

        -- Row 3: Font Picker
        local fontLbl = dispContent:CreateFontString(nil, "OVERLAY", "BrightQoL_FontHighSmall")
        fontLbl:SetPoint("TOPLEFT", DG:Col(1), DG:Row(3) - 2)
        fontLbl:SetText(W.Colorize("FONT", C.BLUE))

        W:CreateFontPicker(dispContent, DG:Col(1), DG:Row(3) - 16,
            db.font or "Fonts\\FRIZQT__.TTF",
            function(path)
                db.font = path
                refresh()
            end)

        dispContent:SetHeight(DG:Height(5))
        dispWrap:RecalcHeight()

        -- ============================================================
        -- VALUE FORMAT SECTION
        -- ============================================================

        local fmtWrap, fmtContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "VALUE FORMAT", startOpen = true,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local FG = ns.Layout:New(2)

        W:CreateCheckbox(fmtContent, { label = "Show Rating",
            db = db, key = "showRating",
            x = FG:Col(1), y = FG:CheckboxY(1), onChange = refreshStats })
        W:CreateCheckbox(fmtContent, { label = "Show Percentage",
            db = db, key = "showPercentage",
            x = FG:Col(2), y = FG:CheckboxY(1), onChange = refreshStats })
        W:CreateCheckbox(fmtContent, { label = "Match Value Color to Stat",
            db = db, key = "matchValueColor",
            x = FG:Col(1), y = FG:CheckboxY(2), onChange = refreshStats })

        fmtContent:SetHeight(FG:Height(2))
        fmtWrap:RecalcHeight()

        -- ============================================================
        -- SECONDARY COLORS SECTION
        -- ============================================================

        local secWrap, secContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "SECONDARY STAT COLORS", startOpen = true,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local SG = ns.Layout:New(2)

        W:CreateColorPicker(secContent, { label = "Crit", db = db,
            rKey = "colorCritR",       gKey = "colorCritG",       bKey = "colorCritB",
            x = SG:Col(1), y = SG:ColorY(1), onChange = refreshStats })
        W:CreateColorPicker(secContent, { label = "Haste", db = db,
            rKey = "colorHasteR",      gKey = "colorHasteG",      bKey = "colorHasteB",
            x = SG:Col(2), y = SG:ColorY(1), onChange = refreshStats })
        W:CreateColorPicker(secContent, { label = "Mastery", db = db,
            rKey = "colorMasteryR",    gKey = "colorMasteryG",    bKey = "colorMasteryB",
            x = SG:Col(1), y = SG:ColorY(2), onChange = refreshStats })
        W:CreateColorPicker(secContent, { label = "Versatility", db = db,
            rKey = "colorVersR",       gKey = "colorVersG",       bKey = "colorVersB",
            x = SG:Col(2), y = SG:ColorY(2), onChange = refreshStats })
        W:CreateColorPicker(secContent, { label = "Rating Value", db = db,
            rKey = "colorRatingR",     gKey = "colorRatingG",     bKey = "colorRatingB",
            x = SG:Col(1), y = SG:ColorY(3), onChange = refreshStats })
        W:CreateColorPicker(secContent, { label = "% Value", db = db,
            rKey = "colorPercentageR", gKey = "colorPercentageG", bKey = "colorPercentageB",
            x = SG:Col(2), y = SG:ColorY(3), onChange = refreshStats })

        secContent:SetHeight(SG:Height(3))
        secWrap:RecalcHeight()

        -- ============================================================
        -- PRIMARY STATS SECTION
        -- ============================================================

        local primWrap, primContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "PRIMARY STATS", startOpen = false,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local PG = ns.Layout:New(2)

        W:CreateCheckbox(primContent, { label = "Show Strength",
            db = db, key = "showStrength",
            x = PG:Col(1), y = PG:CheckboxY(1), onChange = refreshStats })
        W:CreateCheckbox(primContent, { label = "Show Agility",
            db = db, key = "showAgility",
            x = PG:Col(2), y = PG:CheckboxY(1), onChange = refreshStats })
        W:CreateCheckbox(primContent, { label = "Show Intellect",
            db = db, key = "showIntellect",
            x = PG:Col(1), y = PG:CheckboxY(2), onChange = refreshStats })
        W:CreateColorPicker(primContent, { label = "Primary Color", db = db,
            rKey = "colorPrimaryR", gKey = "colorPrimaryG", bKey = "colorPrimaryB",
            x = PG:Col(2), y = PG:ColorY(2), onChange = refreshStats })

        primContent:SetHeight(PG:Height(2))
        primWrap:RecalcHeight()

        -- ============================================================
        -- TERTIARY STATS SECTION
        -- ============================================================

        local terWrap, terContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "TERTIARY STATS", startOpen = false,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local TG = ns.Layout:New(2)

        W:CreateCheckbox(terContent, { label = "Show Tertiary Stats",
            db = db, key = "showTertiary",
            x = TG:Col(1), y = TG:CheckboxY(1), onChange = refreshStats })
        W:CreateCheckbox(terContent, { label = "Hide Zero Values",
            db = db, key = "hideZeroTertiary",
            x = TG:Col(2), y = TG:CheckboxY(1), onChange = refreshStats })
        W:CreateCheckbox(terContent, { label = "Show Leech",
            db = db, key = "showLeech",
            x = TG:Col(1), y = TG:CheckboxY(2), onChange = refreshStats })
        W:CreateCheckbox(terContent, { label = "Show Avoidance",
            db = db, key = "showAvoidance",
            x = TG:Col(2), y = TG:CheckboxY(2), onChange = refreshStats })
        W:CreateCheckbox(terContent, { label = "Show Speed",
            db = db, key = "showSpeed",
            x = TG:Col(1), y = TG:CheckboxY(3), onChange = refreshStats })
        W:CreateColorPicker(terContent, { label = "Leech", db = db,
            rKey = "colorLeechR",     gKey = "colorLeechG",     bKey = "colorLeechB",
            x = TG:Col(1), y = TG:ColorY(4), onChange = refreshStats })
        W:CreateColorPicker(terContent, { label = "Avoidance", db = db,
            rKey = "colorAvoidanceR", gKey = "colorAvoidanceG", bKey = "colorAvoidanceB",
            x = TG:Col(2), y = TG:ColorY(4), onChange = refreshStats })
        W:CreateColorPicker(terContent, { label = "Speed", db = db,
            rKey = "colorSpeedR",     gKey = "colorSpeedG",     bKey = "colorSpeedB",
            x = TG:Col(1), y = TG:ColorY(5), onChange = refreshStats })

        terContent:SetHeight(TG:Height(5))
        terWrap:RecalcHeight()

        -- ============================================================
        -- LAYOUT
        -- ============================================================

        local allSections = { dispWrap, fmtWrap, secWrap, primWrap, terWrap }

        RelayoutAll = function()
            for i, s in ipairs(allSections) do
                s:ClearAllPoints()
                if i == 1 then
                    s:SetPoint("TOPLEFT", settingsContainer, "TOPLEFT", 0, 0)
                else
                    s:SetPoint("TOPLEFT", allSections[i-1], "BOTTOMLEFT", 0, -12)
                end
                s:SetPoint("RIGHT", settingsContainer, "RIGHT", 0, 0)
            end
            local totalH = 0
            if db.enabled then
                for _, s in ipairs(allSections) do totalH = totalH + s:GetHeight() + 12 end
            end
            settingsContainer:SetHeight(math.max(totalH, 1))
            sc:SetHeight(math.max(75 + 62 + 10 + totalH + 60, 1500))
        end

        masterCB:HookScript("OnClick", function(self)
            db.enabled = self:GetChecked() and true or false
            refresh()
            unlockCB:SetShown(db.enabled)
            settingsContainer:SetShown(db.enabled)
            RelayoutAll()
        end)
        settingsContainer:SetShown(db.enabled)

        local restoreBtn = W:CreateRestoreDefaultsButton({
            moduleName = "swiftStats", parent = sc,
            fixedParent = masterArea,
            yOffset = -10,
            initFunc   = function() ns:InitStats() end,
            onRestore  = function()
                if cache.swiftStatsFrame then
                    cache.swiftStatsFrame:Hide()
                    cache.swiftStatsFrame:SetParent(nil)
                    cache.swiftStatsFrame = nil
                end
                refresh()
            end,
        })

        RelayoutAll()
        if SS then SS:Init() end
    end)
end
