local ADDON_NAME, ns = ...

ns.config = ns.config or {}
local Cfg = ns.config

-- ------------------------------------------------------------
-- Skin dropdown list (popup)
-- ------------------------------------------------------------
local function ShowSkinList(anchor, skins, currentID, onPick)
if Cfg._skinList and Cfg._skinList:IsShown() then
    Cfg._skinList:Hide()
    end

    if not Cfg._skinList then
        local f = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
        f:SetFrameStrata("DIALOG")
        f:SetBackdrop({ bgFile="Interface\\Buttons\\WHITE8x8", edgeFile="Interface\\Buttons\\WHITE8x8", edgeSize=1 })
        f:SetBackdropColor(0,0,0,0.95)
        f:SetBackdropBorderColor(0.4,0.4,0.4,1)
        f.buttons = {}
        Cfg._skinList = f
        end

        local f = Cfg._skinList
        f:ClearAllPoints()
        f:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, -4)

        local rowH = 22
        local w = 240
        f:SetSize(w, (#skins * rowH) + 10)

        for i, skin in ipairs(skins) do
            local btn = f.buttons[i]
            if not btn then
                btn = CreateFrame("Button", nil, f)
                btn:SetSize(w-10, rowH)
                btn.text = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                btn.text:SetPoint("LEFT", btn, "LEFT", 6, 0)

                btn.hl = btn:CreateTexture(nil, "HIGHLIGHT")
                btn.hl:SetAllPoints()
                btn.hl:SetColorTexture(1,1,1,0.12)

                f.buttons[i] = btn
                end

                btn:ClearAllPoints()
                btn:SetPoint("TOPLEFT", f, "TOPLEFT", 5, -5 - ((i-1)*rowH))

                btn.text:SetText(skin.name)
                if skin.ignoreColor then
                    btn.text:SetTextColor(1, 0.8, 0)
                    else
                        btn.text:SetTextColor(1, 1, 1)
                        end

                        btn:SetScript("OnClick", function()
                        f:Hide()
                        if onPick then onPick(i) end
                            end)

                        if i == currentID then
                            btn.text:SetTextColor(0.2, 1, 0.2)
                            end

                            btn:Show()
                            end

                            for j = #skins + 1, #f.buttons do
                                if f.buttons[j] then f.buttons[j]:Hide() end
                                    end

                                    f:Show()
                                    end

                                    -- ------------------------------------------------------------
                                    -- Helpers
                                    -- ------------------------------------------------------------
                                    local function ApplyAll(applyAll)
                                    if applyAll then applyAll() end
                                        end

                                        local function MakeSectionTitle(parent, text, x, y)
                                        local t = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                                        t:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                                        t:SetText(text)
                                        return t
                                        end

                                        local function MakeCheck(parent, label, key, x, y, applyAll)
                                        local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
                                        cb:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                                        cb.text:SetText(label)
                                        cb:SetChecked(PlateOMaticDB[key] and true or false)
                                        cb:SetScript("OnClick", function(self)
                                        PlateOMaticDB[key] = self:GetChecked() and true or false
                                        ApplyAll(applyAll)
                                        end)
                                        return cb
                                        end

                                        local function MakeColorSwatch(parent, x, y, getColor, setColor, applyAll)
                                        local b = CreateFrame("Button", nil, parent)
                                        b:SetSize(18, 18)
                                        b:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)

                                        local bg = b:CreateTexture(nil, "BACKGROUND")
                                        bg:SetAllPoints()
                                        bg:SetColorTexture(0.15,0.15,0.15,1)

                                        local sw = b:CreateTexture(nil, "OVERLAY")
                                        sw:SetPoint("TOPLEFT", 1, -1)
                                        sw:SetPoint("BOTTOMRIGHT", -1, 1)

                                        local function refresh()
                                        local c = getColor()
                                        sw:SetColorTexture(c.r or 1, c.g or 1, c.b or 1, c.a or 1)
                                        end
                                        refresh()

                                        b:SetScript("OnClick", function()
                                        local c = getColor()
                                        ColorPickerFrame:SetupColorPickerAndShow({
                                            r = c.r or 1, g = c.g or 1, b = c.b or 1,
                                            opacity = 1 - (c.a or 1),
                                                                                 hasOpacity = true,
                                                                                 swatchFunc = function()
                                                                                 local r,g,b = ColorPickerFrame:GetColorRGB()
                                                                                 local a = 1 - (ColorPickerFrame:GetColorAlpha() or 0)
                                                                                 setColor(r,g,b,a)
                                                                                 refresh()
                                                                                 ApplyAll(applyAll)
                                                                                 end,
                                                                                 opacityFunc = function()
                                                                                 local r,g,b = ColorPickerFrame:GetColorRGB()
                                                                                 local a = 1 - (ColorPickerFrame:GetColorAlpha() or 0)
                                                                                 setColor(r,g,b,a)
                                                                                 refresh()
                                                                                 ApplyAll(applyAll)
                                                                                 end
                                        })
                                        end)

                                        return b, refresh
                                        end

                                        local function MakeSkinButton(parent, skins, key, x, y, applyAll)
                                        local btn = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
                                        btn:SetSize(140, 20)
                                        btn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)

                                        local function refresh()
                                        local id = PlateOMaticDB.skins[key] or 23
                                        local s = skins[id] or skins[23]
                                        btn:SetText(s.name)
                                        end
                                        refresh()

                                        btn:SetScript("OnClick", function()
                                        local current = PlateOMaticDB.skins[key] or 23
                                        ShowSkinList(btn, skins, current, function(pick)
                                        PlateOMaticDB.skins[key] = pick
                                        refresh()
                                        ApplyAll(applyAll)
                                        end)
                                        end)

                                        return btn, refresh
                                        end

                                        local function MakeRowType(parent, skins, label, key, x, y, applyAll)
                                        local row = CreateFrame("Frame", nil, parent)
                                        row:SetSize(390, 24)
                                        row:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)

                                        local txt = row:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
                                        txt:SetPoint("LEFT", row, "LEFT", 0, 0)
                                        txt:SetText(label)

                                        local _, refreshColor = MakeColorSwatch(
                                            row, 210, -2,
                                            function()
                                            PlateOMaticDB.colors = PlateOMaticDB.colors or {}
                                            return PlateOMaticDB.colors[key]
                                            end,
                                            function(r,g,b,a)
                                            local c = PlateOMaticDB.colors[key]
                                            c.r,c.g,c.b = r,g,b
                                            end,
                                            applyAll
                                        )

                                        local _, refreshSkin = MakeSkinButton(row, skins, key, 240, 0, applyAll)

                                        return row, function()
                                        refreshColor()
                                        refreshSkin()
                                        end
                                        end

                                        local function MakeThreatRow(parent, label, key, x, y, applyAll)
                                        local row = CreateFrame("Frame", nil, parent)
                                        row:SetSize(390, 22)
                                        row:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)

                                        local txt = row:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
                                        txt:SetPoint("LEFT", row, "LEFT", 0, 0)
                                        txt:SetText(label)

                                        MakeColorSwatch(
                                            row, 240, -2,
                                            function() return PlateOMaticDB.colors[key] end,
                                                        function(r,g,b,a)
                                                        local c = PlateOMaticDB.colors[key]
                                                        c.r,c.g,c.b = r,g,b
                                                        end,
                                                        applyAll
                                        )

                                        return row
                                        end

                                        -- FIX: Slider must have a NAME or OptionsSliderTemplate label regions are nil
                                        local function MakeSlider(parent, label, key, x, y, minV, maxV, step, applyAll)
                                        local row = CreateFrame("Frame", nil, parent)
                                        row:SetSize(380, 44)
                                        row:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)

                                        local name = row:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
                                        name:SetPoint("TOPLEFT", row, "TOPLEFT", 0, 0)
                                        name:SetText(label)

                                        local val = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
                                        val:SetPoint("TOPRIGHT", row, "TOPRIGHT", 0, 0)

                                        local sliderName = "POM_" .. key .. "_Slider"
                                        local s = CreateFrame("Slider", sliderName, row, "OptionsSliderTemplate")
                                        s:SetPoint("TOPLEFT", row, "TOPLEFT", 0, -18)
                                        s:SetWidth(380)
                                        s:SetMinMaxValues(minV, maxV)
                                        s:SetValueStep(step)
                                        s:SetObeyStepOnDrag(true)

                                        _G[sliderName .. "Low"]:SetText(tostring(minV))
                                        _G[sliderName .. "High"]:SetText(tostring(maxV))
                                        _G[sliderName .. "Text"]:SetText("") -- kill default

                                        local function refresh()
                                        local v = PlateOMaticDB[key]
                                        if v == nil then v = minV end
                                            s:SetValue(v)
                                            val:SetText(tostring(v))
                                            end

                                            s:SetScript("OnValueChanged", function(_, v)
                                            local fmt = (step < 1) and "%.2f" or "%.0f"
                                            v = tonumber(string.format(fmt, v))
                                            PlateOMaticDB[key] = v
                                            val:SetText(tostring(v))
                                            ApplyAll(applyAll)
                                            end)

                                            refresh()
                                            return row, refresh
                                            end

                                            -- ------------------------------------------------------------
                                            -- Build UI (NO PREVIEW)
                                            -- ------------------------------------------------------------
                                            function Cfg:Build(frame, skins, applyAll)
                                            --frame:SetSize(860, 560)

                                            -- Top buttons
                                            local namePos = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
                                            namePos:SetSize(160, 22)
                                            namePos:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -190, -28)
                                            namePos:SetText("Name Pos: " .. (PlateOMaticDB.nameAnchor or "LEFT"))
                                            namePos:SetScript("OnClick", function()
                                            local nxt = (PlateOMaticDB.nameAnchor == "LEFT") and "CENTER" or (PlateOMaticDB.nameAnchor == "CENTER") and "TOP" or "LEFT"
                                            PlateOMaticDB.nameAnchor = nxt
                                            namePos:SetText("Name Pos: " .. nxt)
                                            ApplyAll(applyAll)
                                            end)

                                            local resetBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
                                            resetBtn:SetSize(140, 22)
                                            resetBtn:SetPoint("LEFT", namePos, "RIGHT", 8, 0)
                                            resetBtn:SetText("Reset Settings")
                                            resetBtn:SetScript("OnClick", function()
                                            PlateOMaticDB = nil
                                            C_UI.Reload()
                                            end)

                                            -- Layout constants
                                            local Lx = 16
                                            local Rx = 460
                                            local top = -54

                                            -- LEFT: Unit + Threat + Target Border Color
                                            MakeSectionTitle(frame, "Unit Types", Lx, top)

                                            local y = top - 26
                                            local gap = 24

                                            MakeRowType(frame, skins, "Normal", "normal", Lx, y, applyAll); y = y - gap
                                            MakeRowType(frame, skins, "High Lvl (+2)", "highlevel", Lx, y, applyAll); y = y - gap
                                            MakeRowType(frame, skins, "Player Lvl +1", "plusOne", Lx, y, applyAll); y = y - gap
                                            MakeRowType(frame, skins, "Elite Caster", "caster", Lx, y, applyAll); y = y - gap
                                            MakeRowType(frame, skins, "Elite Melee", "melee", Lx, y, applyAll); y = y - gap

                                            y = y - 12
                                            MakeSectionTitle(frame, "Threat Colors", Lx, y)
                                            y = y - 26

                                            MakeThreatRow(frame, "Aggro (High Threat)", "threatHigh", Lx, y, applyAll); y = y - 22
                                            MakeThreatRow(frame, "Warning (Medium)", "threatMedium", Lx, y, applyAll); y = y - 22
                                            MakeThreatRow(frame, "Safe/Low", "threatLow", Lx, y, applyAll); y = y - 22
                                            MakeThreatRow(frame, "Tank: Safe (Have Aggro)", "threatTankSafe", Lx, y, applyAll); y = y - 26

                                            y = y - 10
                                            MakeSectionTitle(frame, "Target Border", Lx, y)
                                            y = y - 26

                                            local tbRow = CreateFrame("Frame", nil, frame)
                                            tbRow:SetSize(390, 22)
                                            tbRow:SetPoint("TOPLEFT", frame, "TOPLEFT", Lx, y)

                                            local tbTxt = tbRow:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
                                            tbTxt:SetPoint("LEFT", tbRow, "LEFT", 0, 0)
                                            tbTxt:SetText("Target Border Color")

                                            MakeColorSwatch(
                                                tbRow, 240, -2,
                                                function()
                                                PlateOMaticDB.targetBorderColor = PlateOMaticDB.targetBorderColor or { r=1, g=0.82, b=0, a=1 }
                                                return PlateOMaticDB.targetBorderColor
                                                end,
                                                function(r,g,b,a)
                                                PlateOMaticDB.targetBorderColor = PlateOMaticDB.targetBorderColor or {}
                                                PlateOMaticDB.targetBorderColor.r = r
                                                PlateOMaticDB.targetBorderColor.g = g
                                                PlateOMaticDB.targetBorderColor.b = b
                                                PlateOMaticDB.targetBorderColor.a = a
                                                end,
                                                applyAll
                                            )

                                            -- RIGHT: Checkboxes + Sliders (more compact, not "down forever")
                                            MakeSectionTitle(frame, "Options", Rx, top)

                                            local cy = top - 28
                                            local cgap = 24

                                            MakeCheck(frame, "Hide Elite Icon", "hideClassIcon", Rx, cy, applyAll); cy = cy - cgap
                                            MakeCheck(frame, "Flash Yellow (Threat Warning)", "flashAggro", Rx, cy, applyAll); cy = cy - cgap
                                            MakeCheck(frame, "Show Target Arrows", "showTargetArrow", Rx, cy, applyAll); cy = cy - cgap
                                            MakeCheck(frame, "Invert Arrows", "arrowPointingOut", Rx, cy, applyAll); cy = cy - cgap
                                            MakeCheck(frame, "Color Bar by Threat", "colorBarByThreat", Rx, cy, applyAll); cy = cy - cgap
                                            MakeCheck(frame, "Enable Tank Mode Logic", "tankModeEnabled", Rx, cy, applyAll); cy = cy - cgap
                                            MakeCheck(frame, "Show Threat %", "showThreatPerc", Rx, cy, applyAll); cy = cy - cgap

                                            local q1 = MakeCheck(frame, "Show Quest Icon", "showQuestIcon", Rx, cy, applyAll)
                                            if q1 and q1.text then q1.text:SetTextColor(1, 0.8, 0) end
                                                cy = cy - cgap

                                                local q2 = MakeCheck(frame, "Show Quest Progress", "showQuestProg", Rx, cy, applyAll)
                                                if q2 and q2.text then q2.text:SetTextColor(1, 0.8, 0) end
                                                    cy = cy - (cgap + 10)

                                                    MakeSectionTitle(frame, "Sliders", Rx, cy)
                                                    cy = cy - 26

                                                    MakeSlider(frame, "Global Scale", "globalScale", Rx, cy, 0.5, 1.5, 0.05, applyAll); cy = cy - 46
                                                    MakeSlider(frame, "Target Scale (Multiplier)", "targetScale", Rx, cy, 1.0, 1.5, 0.05, applyAll); cy = cy - 46

                                                    MakeSlider(frame, "Castbar Height", "castBarHeight", Rx, cy, 6, 30, 1, applyAll); cy = cy - 46
                                                    MakeSlider(frame, "Castbar Width Scale", "castBarScale", Rx, cy, 0.5, 1.5, 0.05, applyAll); cy = cy - 46
                                                    MakeSlider(frame, "Castbar Text Size", "castTextSize", Rx, cy, 6, 20, 1, applyAll); cy = cy - 46

                                                    MakeSlider(frame, "Buff Size", "buffSize", Rx, cy, 10, 50, 1, applyAll); cy = cy - 46
                                                    MakeSlider(frame, "Debuff Size", "debuffSize", Rx, cy, 10, 50, 1, applyAll); cy = cy - 46

                                                    MakeSlider(frame, "Flash Duration (0=Inf)", "flashDuration", Rx, cy, 0, 5, 1, applyAll)
                                                    end
