local addonName, RLMage = ...

-- Helper für Checkboxen
local function CreateCheckbox(parent, label, onClickFunc)
    local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
    cb.text = cb:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    cb.text:SetPoint("LEFT", cb, "RIGHT", 5, 0)
    cb.text:SetText(label)
    cb:SetScript("OnClick", onClickFunc)
    return cb
end

-- =========================================================================
-- MAIN OPTIONS WINDOW
-- =========================================================================

local optionsFrame = CreateFrame("Frame", "RLMageOptionsFrame", UIParent, "BackdropTemplate")
optionsFrame:SetSize(400, 500)
optionsFrame:SetPoint("CENTER")
optionsFrame:SetFrameStrata("DIALOG")
optionsFrame:Hide()
optionsFrame:EnableMouse(true)
optionsFrame:SetMovable(true)
optionsFrame:RegisterForDrag("LeftButton")
optionsFrame:SetScript("OnDragStart", optionsFrame.StartMoving)
optionsFrame:SetScript("OnDragStop", optionsFrame.StopMovingOrSizing)

-- Hintergrund und Rahmen
optionsFrame:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
    edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
    tile = true, tileSize = 32, edgeSize = 32,
    insets = { left = 11, right = 12, top = 12, bottom = 11 }
})

-- Titel
local title = optionsFrame:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
title:SetPoint("TOP", 0, -15)
title:SetText(RLMage.L.OPTIONS_TITLE)

-- Schließen Button
local closeBtn = CreateFrame("Button", nil, optionsFrame, "UIPanelCloseButton")
closeBtn:SetPoint("TOPRIGHT", -5, -5)

-- =========================================================================
-- TABS
-- =========================================================================

local settingsPage = CreateFrame("Frame", nil, optionsFrame)
settingsPage:SetPoint("TOPLEFT", 15, -40)
settingsPage:SetPoint("BOTTOMRIGHT", -15, 15)

local aboutPage = CreateFrame("Frame", nil, optionsFrame)
aboutPage:SetPoint("TOPLEFT", 15, -40)
aboutPage:SetPoint("BOTTOMRIGHT", -15, 15)
aboutPage:Hide()

local function ShowTab(tabID)
    if tabID == 1 then
        settingsPage:Show()
        aboutPage:Hide()
    else
        settingsPage:Hide()
        aboutPage:Show()
    end
end

local tab1 = CreateFrame("Button", "RLMageOptionsFrameTab1", optionsFrame, "CharacterFrameTabButtonTemplate")
tab1:SetID(1)
tab1:SetText(RLMage.L.TAB_SETTINGS)
tab1:SetPoint("BOTTOMLEFT", optionsFrame, "BOTTOMLEFT", 15, -25)
tab1:SetScript("OnClick", function() 
    PanelTemplates_SetTab(optionsFrame, 1)
    ShowTab(1)
end)

local tab2 = CreateFrame("Button", "RLMageOptionsFrameTab2", optionsFrame, "CharacterFrameTabButtonTemplate")
tab2:SetID(2)
tab2:SetText(RLMage.L.TAB_ABOUT)
tab2:SetPoint("LEFT", tab1, "RIGHT", -16, 0)
tab2:SetScript("OnClick", function() 
    PanelTemplates_SetTab(optionsFrame, 2)
    ShowTab(2)
end)

optionsFrame.numTabs = 2
PanelTemplates_SetTab(optionsFrame, 1)

-- =========================================================================
-- TAB 1: SETTINGS
-- =========================================================================

-- Globale Einstellungen
local globalHeader = settingsPage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
globalHeader:SetPoint("TOPLEFT", 5, -10)
globalHeader:SetText(RLMage.L.ENABLE_CATEGORIES)

local cbTele = CreateCheckbox(settingsPage, RLMage.L.CAT_TELEPORTS, function(self)
    RLMageDB.showTeleports = self:GetChecked()
    if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
end)
cbTele:SetPoint("TOPLEFT", 5, -30)
cbTele:SetScript("OnShow", function(self) self:SetChecked(RLMageDB.showTeleports) end)

local cbPort = CreateCheckbox(settingsPage, RLMage.L.CAT_PORTALS, function(self)
    RLMageDB.showPortals = self:GetChecked()
    if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
end)
cbPort:SetPoint("TOPLEFT", 135, -30)
cbPort:SetScript("OnShow", function(self) self:SetChecked(RLMageDB.showPortals) end)

local cbFood = CreateCheckbox(settingsPage, RLMage.L.CAT_FOOD, function(self)
    RLMageDB.showFood = self:GetChecked()
    if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
end)
cbFood:SetPoint("TOPLEFT", 5, -60)
cbFood:SetScript("OnShow", function(self) self:SetChecked(RLMageDB.showFood) end)

local cbBuffs = CreateCheckbox(settingsPage, RLMage.L.CAT_BUFFS, function(self)
    RLMageDB.showBuffs = self:GetChecked()
    if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
end)
cbBuffs:SetPoint("TOPLEFT", 135, -60)
cbBuffs:SetScript("OnShow", function(self) self:SetChecked(RLMageDB.showBuffs) end)

-- Trennlinie
local line = settingsPage:CreateTexture(nil, "ARTWORK")
line:SetColorTexture(1, 1, 1, 0.2)
line:SetHeight(1)
line:SetPoint("TOPLEFT", 5, -100)
line:SetPoint("TOPRIGHT", -5, -100)

local listHeader = settingsPage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
listHeader:SetPoint("TOPLEFT", 5, -110)
listHeader:SetText(RLMage.L.VISIBLE_SPELLS)

-- ScrollFrame für Zauberliste
local scrollFrame = CreateFrame("ScrollFrame", "RLMageSettingsScroll", settingsPage, "UIPanelScrollFrameTemplate")
scrollFrame:SetPoint("TOPLEFT", 5, -130)
scrollFrame:SetPoint("BOTTOMRIGHT", -25, 40)

local scrollChild = CreateFrame("Frame")
scrollChild:SetSize(scrollFrame:GetWidth(), 500) 
scrollFrame:SetScrollChild(scrollChild)

local spellCheckboxes = {}

function RLMage.RefreshSpellList()
    -- Alte Checkboxen verstecken
    for _, cb in pairs(spellCheckboxes) do
        cb:Hide()
    end
    
    local spellsByName = {}
    
    -- Helper um IDs zu sammeln
    local function AddIDs(list)
        if not list then return end
        for _, v in pairs(list) do
            if type(v) == "table" then
                AddIDs(v)
            elseif type(v) == "number" then
                if IsSpellKnown(v) then
                    local name, _, icon = GetSpellInfo(v)
                    if name then
                        if not spellsByName[name] then
                            spellsByName[name] = {ids = {}, icon = icon, name = name}
                        end
                        table.insert(spellsByName[name].ids, v)
                    end
                end
            end
        end
    end
    
    if RLMage.teleportIDs then AddIDs(RLMage.teleportIDs) end
    if RLMage.portalIDs then AddIDs(RLMage.portalIDs) end
    if RLMage.conjureIDs then AddIDs(RLMage.conjureIDs) end
    if RLMage.buffIDs then AddIDs(RLMage.buffIDs) end
    
    -- Sortieren nach Namen
    local sortedNames = {}
    for name, data in pairs(spellsByName) do
        table.insert(sortedNames, data)
    end
    table.sort(sortedNames, function(a,b) return a.name < b.name end)
    
    local yOffset = 0
    
    for i, data in ipairs(sortedNames) do
        local cb = spellCheckboxes[i]
        if not cb then
            cb = CreateCheckbox(scrollChild, "", function(self)
                local shouldBeHidden = not self:GetChecked()
                for _, id in ipairs(self.spellIDs) do
                    if shouldBeHidden then
                        RLMageDB.hiddenSpells[id] = true
                    else
                        RLMageDB.hiddenSpells[id] = nil
                    end
                end
                if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
            end)
            spellCheckboxes[i] = cb
        end
        
        cb:SetPoint("TOPLEFT", 0, yOffset)
        cb.text:SetText("|T"..data.icon..":16|t " .. data.name)
        cb.spellIDs = data.ids
        
        -- Checkbox Status
        local isVisible = false
        for _, id in ipairs(data.ids) do
            if not RLMageDB.hiddenSpells[id] then
                isVisible = true
                break
            end
        end
        cb:SetChecked(isVisible)
        
        cb:Show()
        yOffset = yOffset - 25
    end
    
    scrollChild:SetHeight(math.abs(yOffset) + 20)
end

-- Reset Button ganz unten
local resetBtn = CreateFrame("Button", nil, settingsPage, "UIPanelButtonTemplate")
resetBtn:SetSize(150, 25)
resetBtn:SetPoint("BOTTOM", 0, 5)
resetBtn:SetText("Alle sichtbar machen")
resetBtn:SetScript("OnClick", function()
    RLMageDB.hiddenSpells = {}
    RLMage.RefreshSpellList()
    if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
    print("|cff00ff00RLMage:|r Alle Zauber sind nun sichtbar.")
end)

-- =========================================================================
-- TAB 2: ABOUT
-- =========================================================================

local aboutTitle = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
aboutTitle:SetPoint("TOP", 0, -20)
aboutTitle:SetText(RLMage.L.ABOUT_TITLE)

local versionText = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
versionText:SetPoint("TOP", aboutTitle, "BOTTOM", 0, -5)
versionText:SetText(RLMage.L.VERSION .. " " .. RLMage.version)

local updateText = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontRed")
updateText:SetPoint("TOP", versionText, "BOTTOM", 0, -5)
updateText:Hide()

function RLMage.UpdateAboutPage()
    if RLMage.newVersion then
        updateText:SetText(string.format(RLMage.L.NEW_VERSION, RLMage.newVersion))
        updateText:Show()
    else
        updateText:Hide()
    end
end

-- Init
RLMage.UpdateAboutPage()

local creatorText = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
creatorText:SetPoint("TOP", updateText, "BOTTOM", 0, -15)
creatorText:SetText(RLMage.L.ABOUT_CREATOR)

local addressText = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
addressText:SetPoint("TOP", creatorText, "BOTTOM", 0, -10)
addressText:SetText("Schwarzbach 148\n42277 Wuppertal\nDeutschland")

local contactHeader = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
contactHeader:SetPoint("TOP", addressText, "BOTTOM", 0, -20)
contactHeader:SetText(RLMage.L.ABOUT_CONTACT)

local emailText = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
emailText:SetPoint("TOP", contactHeader, "BOTTOM", 0, -5)
emailText:SetText("E-Mail: robin@rl-dev.de")

local homepageHeader = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
homepageHeader:SetPoint("TOP", emailText, "BOTTOM", 0, -20)
homepageHeader:SetText(RLMage.L.ABOUT_HOMEPAGE)

local homepageLink = CreateFrame("EditBox", nil, aboutPage, "InputBoxTemplate")
homepageLink:SetSize(250, 30)
homepageLink:SetPoint("TOP", homepageHeader, "BOTTOM", 0, -5)
homepageLink:SetText("https://rl-dev.de")
homepageLink:SetAutoFocus(false)
homepageLink:SetCursorPosition(0)
homepageLink:SetScript("OnTextChanged", function(self)
    self:SetText("https://rl-dev.de")
    self:SetCursorPosition(0)
    self:ClearFocus()
end)
homepageLink:SetScript("OnMouseUp", function(self) self:HighlightText() end)

local bugHeader = aboutPage:CreateFontString(nil, "ARTWORK", "GameFontNormal")
bugHeader:SetPoint("TOP", homepageLink, "BOTTOM", 0, -20)
bugHeader:SetText(RLMage.L.ABOUT_BUGTRACKER)

local bugLink = CreateFrame("EditBox", nil, aboutPage, "InputBoxTemplate")
bugLink:SetSize(250, 30)
bugLink:SetPoint("TOP", bugHeader, "BOTTOM", 0, -5)
bugLink:SetText("https://rl-dev.de/bugtracker.html")
bugLink:SetAutoFocus(false)
bugLink:SetCursorPosition(0)
bugLink:SetScript("OnTextChanged", function(self)
    self:SetText("https://rl-dev.de/bugtracker.html")
    self:SetCursorPosition(0)
    self:ClearFocus()
end)
bugLink:SetScript("OnMouseUp", function(self) self:HighlightText() end)

-- =========================================================================
-- SHOW/HIDE LOGIC
-- =========================================================================

function RLMage.ToggleOptions()
    if optionsFrame:IsShown() then
        optionsFrame:Hide()
    else
        optionsFrame:Show()
        RLMage.RefreshSpellList()
    end
end

-- =========================================================================
-- INTERFACE OPTIONS CATEGORY
-- =========================================================================

local categoryPanel = CreateFrame("Frame", "RLMageConfigCategory")
categoryPanel.name = "RL-Dev.de"

local catTitle = categoryPanel:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
catTitle:SetPoint("TOPLEFT", 16, -16)
catTitle:SetText("RL-Dev.de")

local catDesc = categoryPanel:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
catDesc:SetPoint("TOPLEFT", catTitle, "BOTTOMLEFT", 0, -10)
catDesc:SetText(RLMage.L.DESC_CATEGORY)

local openBtn = CreateFrame("Button", nil, categoryPanel, "UIPanelButtonTemplate")
openBtn:SetSize(150, 30)
openBtn:SetPoint("TOPLEFT", catDesc, "BOTTOMLEFT", 0, -20)
openBtn:SetText(RLMage.L.OPEN_OPTIONS)
openBtn:SetScript("OnClick", function()
    -- Schließe Interface Optionen, öffne unser Fenster
    if InterfaceOptionsFrame then InterfaceOptionsFrame:Hide() end
    if SettingsPanel then SettingsPanel:Hide() end -- Retail/Modern
    RLMage.ToggleOptions()
end)

if InterfaceOptions_AddCategory then
    InterfaceOptions_AddCategory(categoryPanel)
end
