-------------------------
-- AiB Gear Check Settings
-------------------------

local frame = CreateFrame("Frame")
frame:RegisterEvent("PLAYER_LOGIN")
frame:SetScript("OnEvent", function()
    C_Timer.After(2.5, function()
        if not _G.AiB then return end

        AiB.GearCheckSettings = {}

        function AiB.GearCheckSettings:AddToSettingsPanel(parent, startY)
            local FONT    = "Fonts\\FRIZQT__.TTF"
            local yOffset = startY

            local function AddHeader(text, y)
                local h = parent:CreateFontString(nil, "OVERLAY")
                h:SetFont(FONT, 16, "OUTLINE")
                h:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, y)
                h:SetText(text)
                h:SetTextColor(1, 0.8, 0, 1)
                return h
            end

            local function AddSubHeader(text, y)
                local h = parent:CreateFontString(nil, "OVERLAY")
                h:SetFont(FONT, 13, "OUTLINE")
                h:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, y)
                h:SetText(text)
                h:SetTextColor(1, 0.6, 0, 1)
                return h
            end

            local function AddDesc(text, y)
                local d = parent:CreateFontString(nil, "OVERLAY")
                d:SetFont(FONT, 11)
                d:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, y)
                d:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, y)
                d:SetJustifyH("LEFT")
                d:SetWordWrap(true)
                d:SetText(text)
                d:SetTextColor(0.6, 0.6, 0.6, 1)
                return d
            end

            local function AddCheckbox(labelText, x, y, getValue, setValue)
                local label = parent:CreateFontString(nil, "OVERLAY")
                label:SetFont(FONT, 12)
                label:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                label:SetText(labelText)
                label:SetTextColor(1, 1, 1, 1)
                local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
                cb:SetPoint("LEFT", label, "RIGHT", 5, 0)
                cb:SetSize(24, 24)
                cb:SetChecked(getValue())
                cb:SetScript("OnClick", function(self) setValue(self:GetChecked()) end)
                return cb
            end

            local function AddSlider(labelText, x, y, minV, maxV, step, getValue, setValue)
                local labelFS = parent:CreateFontString(nil, "OVERLAY")
                labelFS:SetFont(FONT, 12)
                labelFS:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                labelFS:SetText(labelText .. ": " .. getValue())
                labelFS:SetTextColor(1, 1, 1, 1)
                local sl = CreateFrame("Slider", nil, parent, "OptionsSliderTemplate")
                sl:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y - 22)
                sl:SetMinMaxValues(minV, maxV)
                sl:SetValue(getValue())
                sl:SetValueStep(step)
                sl:SetObeyStepOnDrag(true)
                sl:SetWidth(220)
                sl:SetScript("OnValueChanged", function(self, value)
                    value = math.floor(value / step + 0.5) * step
                    setValue(value)
                    labelFS:SetText(labelText .. ": " .. value)
                end)
                return sl
            end

            local function AddButton(text, x, y, onClick, width)
                local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
                btn:SetSize(width or 220, 26)
                btn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                btn:SetBackdrop({
                    bgFile   = "Interface\\Buttons\\WHITE8x8",
                    edgeFile = "Interface\\Buttons\\WHITE8x8",
                    edgeSize = 1,
                })
                btn:SetBackdropColor(0.15, 0.15, 0.15, 0.9)
                btn:SetBackdropBorderColor(0.4, 0.4, 0.4, 1)
                local btnText = btn:CreateFontString(nil, "OVERLAY")
                btnText:SetFont(FONT, 12)
                btnText:SetPoint("CENTER")
                btnText:SetText(text)
                btnText:SetTextColor(1, 1, 1, 1)
                btn:SetScript("OnClick", onClick)
                btn:SetScript("OnEnter", function(self) self:SetBackdropBorderColor(1, 0.8, 0, 1) end)
                btn:SetScript("OnLeave", function(self) self:SetBackdropBorderColor(0.4, 0.4, 0.4, 1) end)
                return btn
            end

            local function Separator(y)
                local sep = parent:CreateTexture(nil, "ARTWORK")
                sep:SetColorTexture(0.3, 0.3, 0.3, 0.6)
                sep:SetSize(860, 1)
                sep:SetPoint("TOPLEFT", parent, "TOPLEFT", 10, y)
                return sep
            end

            -- Passt die ScrollFrame-Höhe nach Grid-Rebuild an
            local function RefreshScrollHeight(totalBottom)
                -- 0.2s: läuft NACH ShowTab's eigenem 0.1s-Reset, sonst wird die Höhe überschrieben
                C_Timer.After(0.2, function()
                    local sf = _G["AiBSettingsContentFrame"]
                    if not sf or not sf.scrollChild then return end
                    local sc     = sf.scrollChild
                    local needed = math.abs(totalBottom) + 80
                    sc:SetHeight(needed)  -- immer setzen, ohne Bedingung
                    if sf.ScrollBar then
                        sf.ScrollBar:SetMinMaxValues(0, math.max(0, needed - sf:GetHeight()))
                        sf.ScrollBar:SetValue(0)
                    end
                end)
            end

            -------------------------
            -- Titel
            -------------------------
            AddHeader("|cFFFF0000Gear|r |cFFFFFFFFCheck|r", yOffset)
            yOffset = yOffset - 30
            AddDesc("Zeigt ausgerüstete Schmuckstücke und Waffen beim Betreten von Instanzen oder bei Bereitschaftschecks an.", yOffset)
            yOffset = yOffset - 45
            Separator(yOffset) ; yOffset = yOffset - 15

            -------------------------
            -- Aktivieren
            -------------------------
            AddCheckbox("Gear Check aktivieren", 20, yOffset,
                function() return AiB_GearCheckConfig and AiB_GearCheckConfig.enabled or false end,
                function(v)
                    AiB_GearCheckConfig = AiB_GearCheckConfig or {}
                    AiB_GearCheckConfig.enabled = v
                    -- Toggle-Button live ein-/ausblenden wenn CharacterFrame offen ist
                    if CharacterFrame and CharacterFrame:IsShown() then
                        if AiB.GearCheck then
                            if v then
                                if AiB.GearCheck.ShowToggleButton then AiB.GearCheck.ShowToggleButton() end
                            else
                                if AiB.GearCheck.HideToggleButton then AiB.GearCheck.HideToggleButton() end
                            end
                        end
                    end
                end)
            yOffset = yOffset - 40
            Separator(yOffset) ; yOffset = yOffset - 15

            -------------------------
            -- Auslöser
            -------------------------
            AddSubHeader("AUSLÖSER", yOffset) ; yOffset = yOffset - 30

            AddCheckbox("Bei Instanz-Betreten anzeigen", 20, yOffset,
                function() return AiB_GearCheckConfig and AiB_GearCheckConfig.showOnInstance ~= false end,
                function(v) AiB_GearCheckConfig = AiB_GearCheckConfig or {} ; AiB_GearCheckConfig.showOnInstance = v end)
            yOffset = yOffset - 28
            AddDesc("Ausrüstung beim Betreten von Dungeons, Schlachtzügen oder Szenarien anzeigen.", yOffset)
            yOffset = yOffset - 38

            AddCheckbox("Bei Bereitschaftsprüfung anzeigen", 20, yOffset,
                function() return AiB_GearCheckConfig and AiB_GearCheckConfig.showOnReadyCheck ~= false end,
                function(v) AiB_GearCheckConfig = AiB_GearCheckConfig or {} ; AiB_GearCheckConfig.showOnReadyCheck = v end)
            yOffset = yOffset - 28
            AddDesc("Ausrüstung bei einer Bereitschaftsprüfung anzeigen.", yOffset)
            yOffset = yOffset - 40
            Separator(yOffset) ; yOffset = yOffset - 15

            -------------------------
            -- Anzeige
            -------------------------
            AddSubHeader("ANZEIGE", yOffset) ; yOffset = yOffset - 30

            AddSlider("Autom. Ausblenden (Sek.)", 20, yOffset, 0, 30, 1,
                function() return (AiB_GearCheckConfig and AiB_GearCheckConfig.autoHideDelay) or 10 end,
                function(v) AiB_GearCheckConfig = AiB_GearCheckConfig or {} ; AiB_GearCheckConfig.autoHideDelay = v end)
            yOffset = yOffset - 55
            AddDesc("Sekunden bis das Fenster automatisch ausgeblendet wird (0 = nur manuell schließen).", yOffset)
            yOffset = yOffset - 35

            AddSlider("Symbolgröße", 20, yOffset, 32, 64, 2,
                function() return (AiB_GearCheckConfig and AiB_GearCheckConfig.iconSize) or 40 end,
                function(v)
                    AiB_GearCheckConfig = AiB_GearCheckConfig or {}
                    AiB_GearCheckConfig.iconSize = v
                    if AiB.GearCheck and AiB.GearCheck.ResetFrame then AiB.GearCheck.ResetFrame() end
                end)
            yOffset = yOffset - 55
            Separator(yOffset) ; yOffset = yOffset - 15

            -------------------------
            -- Vorschau
            -------------------------
            AddSubHeader("VORSCHAU", yOffset) ; yOffset = yOffset - 30
            AddButton("Gear Check anzeigen", 20, yOffset, function()
                if AiB.GearCheck and AiB.GearCheck.ShowFrame then AiB.GearCheck.ShowFrame(true) end
            end)
            yOffset = yOffset - 40
            Separator(yOffset) ; yOffset = yOffset - 15

            -------------------------
            -- Verzauberungs-Prüfer
            -------------------------
            AddSubHeader("VERZAUBERUNGS-PRÜFER", yOffset) ; yOffset = yOffset - 30
            AddDesc("Prüft ob die erwarteten Verzauberungen auf deinen Items aktiv sind. Wird im Gear-Check-Fenster angezeigt.", yOffset)
            yOffset = yOffset - 40

            AddCheckbox("Verzauberungs-Prüfer aktivieren", 20, yOffset,
                function() return AiB_GearCheckConfig and AiB_GearCheckConfig.ecEnabled or false end,
                function(v) AiB_GearCheckConfig = AiB_GearCheckConfig or {} ; AiB_GearCheckConfig.ecEnabled = v end)
            yOffset = yOffset - 35

            AddCheckbox("Gleiche Regeln für alle Spezialisierungen", 20, yOffset,
                function() return AiB_GearCheckConfig and AiB_GearCheckConfig.ecUseAllSpecs ~= false end,
                function(v)
                    AiB_GearCheckConfig = AiB_GearCheckConfig or {}
                    AiB_GearCheckConfig.ecUseAllSpecs = v
                    if self._rebuildGrid then self._rebuildGrid() end
                end)
            yOffset = yOffset - 40

            AddButton("Aktuelle Verzauberungen & Öle erfassen", 20, yOffset, function()

                AiB_GearCheckConfig.ecSpecRules = AiB_GearCheckConfig.ecSpecRules or {}
                local db        = AiB_GearCheckConfig
                local specIndex = GetSpecialization()
                local specID    = specIndex and GetSpecializationInfo(specIndex)
                local ruleKey   = (db.ecUseAllSpecs ~= false) and 0 or specID
                if not ruleKey then
                    print("|cFFFF0000[AiB Gear Check]|r Keine aktive Spezialisierung gefunden.")
                    return
                end
                db.ecSpecRules[ruleKey] = db.ecSpecRules[ruleKey] or {}
                local rules        = db.ecSpecRules[ruleKey]
                local SLOTS        = AiB.GearCheck and AiB.GearCheck.ENCHANTABLE_SLOTS or {}
                local capturedEnch = 0
                local capturedOil  = 0

                for _, slot in ipairs(SLOTS) do
                    local entry = rules[slot.id] or {}

                    -- Permanente Verzauberung via Item-Link erfassen
                    if AiB.GearCheck.GetEnchantFromLink then
                        local enchName, enchID = AiB.GearCheck.GetEnchantFromLink(slot.id)
                        if enchName and enchID then
                            entry.id   = enchID
                            entry.name = enchName
                            capturedEnch = capturedEnch + 1
                        end
                    end

                    -- Öl via GetWeaponEnchantInfo erfassen (nur Waffen-Slots)
                    if slot.id == 16 or slot.id == 17 then
                        local hasMain, _, _, _, hasOff = GetWeaponEnchantInfo()
                        local hasOil = (slot.id == 16 and hasMain) or (slot.id == 17 and hasOff)
                        if hasOil then
                            entry.oil = "Öl"  -- Öl vorhanden
                            capturedOil = capturedOil + 1
                        end
                    end

                    if next(entry) then
                        rules[slot.id] = entry
                    end
                end

                local msg = "|cFF00FF00[AiB Gear Check]|r Erfasst: " .. capturedEnch .. " Verzauberung(en)"
                if capturedOil > 0 then msg = msg .. ", " .. capturedOil .. " Öl/Öle" end
                print(msg)
                if self._rebuildGrid then self._rebuildGrid() end
            end, 265)
            yOffset = yOffset - 45

            -------------------------
            -- Grid: alle Elemente direkt in parent (kein gridContainer!)
            -- Damit misst der ScrollFrame sie korrekt
            -------------------------
            local gridStartY = yOffset
            local gridFrames = {}

            local function ClearGrid()
                for _, elem in ipairs(gridFrames) do
                    if elem and elem.Hide then elem:Hide() end
                    if elem and elem.SetParent then
                        pcall(function() elem:SetParent(nil) end)
                    end
                end
                gridFrames = {}
            end

            local function GridText(text, x, y, r, g, b, size)
                local fs = parent:CreateFontString(nil, "OVERLAY")
                fs:SetFont(FONT, size or 11)
                fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
                fs:SetText(text)
                fs:SetTextColor(r or 1, g or 1, b or 1, 1)
                table.insert(gridFrames, fs)
                return fs
            end

            local RebuildGrid
            RebuildGrid = function()
                ClearGrid()

                local db       = AiB_GearCheckConfig or {}
                local useAll   = db.ecUseAllSpecs ~= false
                local numSpecs = GetNumSpecializations()
                local rules    = db.ecSpecRules or {}
                local SLOTS    = (AiB.GearCheck and AiB.GearCheck.ENCHANTABLE_SLOTS) or {}

                local rowH       = 26
                local labelW     = 100
                local entryW     = 185
                local colSpacing = 10
                local gY         = gridStartY

                -- Spalten-Header
                if useAll then
                    GridText("Erwartete Verzauberung", labelW + 20, gY, 0.8, 0.8, 0.8, 11)
                else
                    for i = 1, numSpecs do
                        local _, specName = GetSpecializationInfo(i)
                        local colX = labelW + 20 + (i - 1) * (entryW + colSpacing)
                        GridText(specName or ("Spec " .. i), colX, gY, 0.8, 0.8, 0.8, 11)
                    end
                end
                gY = gY - 20

                -- Slot-Zeilen
                for _, slot in ipairs(SLOTS) do
                    local lbl = GridText(slot.name .. " :", 20, gY - 4, 0.9, 0.9, 0.9, 11)
                    lbl:SetWidth(labelW)
                    lbl:SetJustifyH("RIGHT")

                    local function DrawEntry(colX, specRuleSet, slotID)
                        local data       = specRuleSet and specRuleSet[slotID]
                        local hasEnchant = data and data.name and data.name ~= ""
                        -- oil kann boolean (alt) oder string (neu) sein
                        local oilVal     = data and data.oil
                        local hasOil     = oilVal and oilVal ~= "" and oilVal ~= false
                        local oilText    = type(oilVal) == "string" and oilVal or "Öl"

                        if hasEnchant or hasOil then
                            local lineY = gY - 4
                            if hasEnchant then
                                local nameFS = GridText(data.name, colX, lineY, 0.4, 0.9, 0.4, 11)
                                local delBtn = CreateFrame("Button", nil, parent)
                                delBtn:SetSize(14, 14)
                                delBtn:SetPoint("LEFT", nameFS, "RIGHT", 4, 0)
                                delBtn:SetNormalTexture([[Interface\Buttons\UI-StopButton]])
                                delBtn:SetHighlightTexture([[Interface\Buttons\UI-StopButton]])
                                delBtn:GetHighlightTexture():SetVertexColor(1, 0.3, 0.3, 1)
                                delBtn:SetScript("OnClick", function()
                                    if specRuleSet then
                                        specRuleSet[slotID].name = nil
                                        specRuleSet[slotID].id   = nil
                                        if not next(specRuleSet[slotID]) then specRuleSet[slotID] = nil end
                                    end
                                    RebuildGrid()
                                end)
                                table.insert(gridFrames, delBtn)
                                lineY = lineY - 14
                            end
                            if hasOil then
                                local oilFS = GridText("🛢 " .. oilText, colX, lineY, 0.4, 0.7, 1.0, 10)
                                local delOil = CreateFrame("Button", nil, parent)
                                delOil:SetSize(14, 14)
                                delOil:SetPoint("LEFT", oilFS, "RIGHT", 4, 0)
                                delOil:SetNormalTexture([[Interface\Buttons\UI-StopButton]])
                                delOil:SetHighlightTexture([[Interface\Buttons\UI-StopButton]])
                                delOil:GetHighlightTexture():SetVertexColor(1, 0.3, 0.3, 1)
                                delOil:SetScript("OnClick", function()
                                    if specRuleSet and specRuleSet[slotID] then
                                        specRuleSet[slotID].oil = nil
                                        if not next(specRuleSet[slotID]) then specRuleSet[slotID] = nil end
                                    end
                                    RebuildGrid()
                                end)
                                table.insert(gridFrames, delOil)
                            end
                        else
                            GridText("-", colX, gY - 4, 0.45, 0.45, 0.45, 11)
                        end
                    end

                    if useAll then
                        rules[0] = rules[0] or {}
                        DrawEntry(labelW + 20, rules[0], slot.id)
                    else
                        for i = 1, numSpecs do
                            local specID = GetSpecializationInfo(i)
                            rules[specID] = rules[specID] or {}
                            DrawEntry(labelW + 20 + (i - 1) * (entryW + colSpacing), rules[specID], slot.id)
                        end
                    end

                    gY = gY - rowH
                end

                -- Unsichtbarer Anker-Frame ganz unten — damit ScrollFrame Höhe korrekt berechnet wird
                local anchor = CreateFrame("Frame", nil, parent)
                anchor:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, gY - 10)
                anchor:SetSize(1, 1)
                table.insert(gridFrames, anchor)

                RefreshScrollHeight(gY - 60)
            end

            self._rebuildGrid = RebuildGrid
            RebuildGrid()

            -- yOffset nach Grid (für den Reset-Button darunter)
            local numSlots = #((AiB.GearCheck and AiB.GearCheck.ENCHANTABLE_SLOTS) or {})
            yOffset = gridStartY - 20 - (numSlots * 26) - 20

            -------------------------
            -- Standards zurücksetzen
            -------------------------
            Separator(yOffset) ; yOffset = yOffset - 15

            AddButton("Standards zurücksetzen", 20, yOffset, function()
                AiB_GearCheckConfig = {
                    enabled          = false,
                    showOnInstance   = true,
                    showOnReadyCheck = true,
                    autoHideDelay    = 10,
                    iconSize         = 40,
                    point            = "CENTER",
                    x                = 0,
                    y                = 100,
                    ecEnabled        = false,
                    ecUseAllSpecs    = true,
                    ecSpecRules      = {},
                }
                if AiB.GearCheck and AiB.GearCheck.ResetFrame then AiB.GearCheck.ResetFrame() end
                print("|cFF00FF00[AiB Gear Check]|r Einstellungen zurückgesetzt. Bitte Settings-Tab neu öffnen.")
            end)
            yOffset = yOffset - 50

            return yOffset
        end
    end)
end)
