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

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

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

-- Color keys with display labels (order matters for layout)
local COLOR_KEYS = {
    -- Column 1
    { key = "dungeonName",       label = "Dungeon Name",         col = 1, row = 1 },
    { key = "keyLevel",          label = "Key Level (+10)",       col = 1, row = 2 },
    { key = "timerText",         label = "Timer (Normal)",        col = 1, row = 3 },
    { key = "timerOvertime",     label = "Timer (Overtime)",      col = 1, row = 4 },
    { key = "upgradeTwo",        label = "+2 Upgrade",            col = 1, row = 5 },
    { key = "upgradeThree",      label = "+3 Upgrade",            col = 1, row = 6 },
    { key = "upgradeDepleted",   label = "Depleted",              col = 1, row = 7 },
    -- Column 2
    { key = "enemyBar",          label = "Enemy Bar",             col = 2, row = 1 },
    { key = "enemyText",         label = "Enemy Text",            col = 2, row = 2 },
    { key = "enemyTextComplete", label = "Enemy Text (100%)",     col = 2, row = 3 },
    { key = "bossAlive",         label = "Boss (Alive)",          col = 2, row = 4 },
    { key = "bossDead",          label = "Boss (Dead)",           col = 2, row = 5 },
    { key = "deathText",         label = "Deaths",                col = 2, row = 6 },
    { key = "deathPenalty",      label = "Death Penalty",         col = 2, row = 7 },
    { key = "affixText",         label = "Affixes",               col = 2, row = 8 },
}

-- Immutable default colors — always available for reset, never modified at runtime
local COLOR_DEFAULTS = {
    dungeonName       = { r=1,    g=1,    b=1    },
    keyLevel          = { r=1,    g=1,    b=1    },
    timerText         = { r=1,    g=1,    b=1    },
    timerOvertime     = { r=1,    g=0,    b=0    },
    upgradeTwo        = { r=1,    g=1,    b=0    },
    upgradeThree      = { r=1,    g=1,    b=0    },
    upgradeDepleted   = { r=0.5,  g=0.5,  b=0.5  },
    enemyBar          = { r=0.45, g=0,    b=0.85 },
    enemyText         = { r=1,    g=1,    b=1    },
    enemyTextComplete = { r=0,    g=1,    b=0    },
    bossAlive         = { r=1,    g=1,    b=1    },
    bossDead          = { r=0,    g=1,    b=0    },
    deathText         = { r=1,    g=1,    b=1    },
    deathPenalty      = { r=1,    g=0,    b=0    },
    affixText         = { r=0.5,  g=0.5,  b=0.5  },
}

function ns:InitMythicTimer()
    local p   = ns.MainFrame.Content
    local db  = BrightQoL.mythicTimer
    local MT  = ns.MythicTimer

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

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

        W:CreatePageHeader(sc,
            { {"M+", C.BLUE}, {" TIMER", C.ORANGE} },
            W.Colorize("Mythic+ run timer with enemy forces, boss tracking and deaths.", 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 M+ Timer",
            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 = function(val)
                if MT then MT:SetUnlocked(val) end
            end,
        })
        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(900)

        -- ============================================================
        -- 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 Boss Kill Times + Show Enemy %
        W:CreateCheckbox(dispContent, {
            label = "Show Boss Kill Times", db = db, key = "showBossKillTimes",
            x = DG:Col(1), y = DG:CheckboxY(1), onChange = refresh,
        })
        W:CreateCheckbox(dispContent, {
            label = "Show Enemy %", db = db, key = "showEnemyPercent",
            x = DG:Col(2), y = DG:CheckboxY(1), onChange = refresh,
        })

        -- Row 2: Show Enemy Count + Hide Objective Tracker
        W:CreateCheckbox(dispContent, {
            label = "Show Enemy Count (Absolute)", db = db, key = "showEnemyCount",
            x = DG:Col(1), y = DG:CheckboxY(2), onChange = refresh,
        })
        W:CreateCheckbox(dispContent, {
            label = "Hide Objective Tracker", db = db, key = "hideObjectiveTracker",
            x = DG:Col(2), y = DG:CheckboxY(2),
            onChange = function(val)
                if MT then
                    if val then MT:HideObjectiveTracker()
                    else MT:RestoreObjectiveTracker() end
                end
            end,
        })

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

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

        -- ============================================================
        -- POSITION SECTION
        -- ============================================================
        local posWrap, posContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "POSITION", startOpen = true,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        local resetBtn = W:CreateButton(posContent, {
            text = "Reset Position",
            width = 140, height = 24,
            onClick = function()
                if MT then MT:ResetPosition() end
            end,
        })
        resetBtn:SetPoint("TOPLEFT", 10, -10)

        local demoBtn = W:CreateButton(posContent, {
            text = "Toggle Demo",
            width = 140, height = 24,
            onClick = function()
                if MT then MT:ToggleDemo() end
            end,
        })
        demoBtn:SetPoint("LEFT", resetBtn, "RIGHT", 10, 0)

        posContent:SetHeight(50)
        posWrap:RecalcHeight()

        -- ============================================================
        -- COLORS SECTION
        -- ============================================================
        local colWrap, colContent = W:CreateCollapsibleSection(settingsContainer, {
            text = "COLORS", startOpen = false,
            onCollapse = function() if RelayoutAll then RelayoutAll() end end,
        })

        -- Two-column layout; each color row = 30px
        local COL1_X = 10
        local COL2_X = 240
        local COL_START_Y = -10
        local COL_ROW_H = 30
        local maxRow = 0

        for _, entry in ipairs(COLOR_KEYS) do
            local c = db.colors[entry.key]
            if not c then c = { r=1, g=1, b=1 }; db.colors[entry.key] = c end

            local x = (entry.col == 1) and COL1_X or COL2_X
            local y = COL_START_Y - (entry.row - 1) * COL_ROW_H

            -- Swatch button
            local swatch = CreateFrame("Button", nil, colContent, "BackdropTemplate")
            swatch:SetSize(18, 18)
            swatch:SetPoint("TOPLEFT", x, y - 2)
            swatch:SetBackdrop({ bgFile = [[Interface\Buttons\WHITE8x8]], edgeFile = [[Interface\Buttons\WHITE8x8]], edgeSize = 1 })
            swatch:SetBackdropColor(c.r, c.g, c.b, 1)
            swatch:SetBackdropBorderColor(0, 0, 0, 1)

            local lbl = colContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
            lbl:SetPoint("LEFT", swatch, "RIGHT", 6, 0)
            lbl:SetText(entry.label)

            -- Reset button
            local rstBtn = W:CreateButton(colContent, {
                text = "Reset", width = 50, height = 18,
                onClick = function()
                    local d = COLOR_DEFAULTS[entry.key]
                    db.colors[entry.key].r = d.r
                    db.colors[entry.key].g = d.g
                    db.colors[entry.key].b = d.b
                    swatch:SetBackdropColor(d.r, d.g, d.b, 1)
                    refresh()
                end,
            })
            rstBtn:SetPoint("LEFT", lbl, "RIGHT", 4, 0)

            swatch:SetScript("OnEnter", function(self)
                self:SetBackdropBorderColor(1, 1, 1, 1)
                GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                GameTooltip:SetText("Click to change color", 1, 1, 1)
                GameTooltip:Show()
            end)
            swatch:SetScript("OnLeave", function(self)
                self:SetBackdropBorderColor(0, 0, 0, 1)
                GameTooltip:Hide()
            end)
            swatch:SetScript("OnClick", function()
                ColorPickerFrame:SetupColorPickerAndShow({
                    r = c.r, g = c.g, b = c.b,
                    hasOpacity = false,
                    swatchFunc = function()
                        c.r, c.g, c.b = ColorPickerFrame:GetColorRGB()
                        swatch:SetBackdropColor(c.r, c.g, c.b, 1)
                        refresh()
                    end,
                    cancelFunc = function(prev)
                        c.r, c.g, c.b = prev.r, prev.g, prev.b
                        swatch:SetBackdropColor(c.r, c.g, c.b, 1)
                        refresh()
                    end,
                })
            end)

            if entry.row > maxRow then maxRow = entry.row end
        end

        colContent:SetHeight(COL_START_Y + maxRow * COL_ROW_H + 20)
        colWrap:RecalcHeight()

        -- ============================================================
        -- LAYOUT
        -- ============================================================
        local allSections = { dispWrap, posWrap, colWrap }

        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, 1400))
        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 = "mythicTimer", parent = sc,
            fixedParent = masterArea,
            yOffset = -10,
            initFunc   = function() ns:InitMythicTimer() end,
            onRestore  = function()
                if cache.mythicTimerFrame then
                    cache.mythicTimerFrame:Hide()
                    cache.mythicTimerFrame:SetParent(nil)
                    cache.mythicTimerFrame = nil
                end
                refresh()
            end,
        })

        RelayoutAll()
    end)
end
