-------------------------
-- AiB Settings System (Tab-Based)
-------------------------
-- Strukturiertes Tab-System für alle Features

AiB = AiB or {}
AiB.Settings = {}

local settingsFrame = nil
local currentTab = nil
local tabButtons = {}
local contentFrame = nil

-------------------------
-- Create Settings Frame
-------------------------
function AiB.Settings:CreateSettingsFrame(parentFrame)
    if settingsFrame then
        return settingsFrame
    end
    
    local FONT = "Fonts\\FRIZQT__.TTF"
    
    -- Main Container
    settingsFrame = CreateFrame("Frame", "AiBSettingsFrame", parentFrame)
    settingsFrame:SetAllPoints(parentFrame)
    settingsFrame:Hide()
    
    -- Tab Container (horizontale Button-Leiste)
    local tabContainer = CreateFrame("Frame", nil, settingsFrame)
    tabContainer:SetPoint("TOPLEFT", settingsFrame, "TOPLEFT", 20, -20)
    tabContainer:SetPoint("TOPRIGHT", settingsFrame, "TOPRIGHT", -20, -20)
    tabContainer:SetHeight(30)  -- Kleiner für 26px Tabs
    settingsFrame.tabContainer = tabContainer
    
    -- Content Frame (wechselt je nach Tab)
    contentFrame = CreateFrame("ScrollFrame", "AiBSettingsContentFrame", settingsFrame, "UIPanelScrollFrameTemplate")
    contentFrame:SetPoint("TOPLEFT", tabContainer, "BOTTOMLEFT", 0, -5)  -- Weniger Spacing!
    contentFrame:SetPoint("BOTTOMRIGHT", settingsFrame, "BOTTOMRIGHT", -30, 20)
    contentFrame:EnableMouseWheel(true)
    
    -- Scroll Child (DYNAMISCHE Höhe!)
    local scrollChild = CreateFrame("Frame", nil, contentFrame)
    scrollChild:SetSize(900, 1)  -- Minimal - wird dynamisch angepasst!
    contentFrame:SetScrollChild(scrollChild)
    contentFrame.scrollChild = scrollChild
    
    -- MouseWheel Handling
    contentFrame:SetScript("OnMouseWheel", function(self, delta)
        local scrollBar = self.ScrollBar
        if scrollBar then
            local current = scrollBar:GetValue()
            local minVal, maxVal = scrollBar:GetMinMaxValues()
            local step = 20
            
            if delta > 0 then
                scrollBar:SetValue(math.max(current - step, minVal))
            else
                scrollBar:SetValue(math.min(current + step, maxVal))
            end
        end
    end)
    
    settingsFrame.contentFrame = contentFrame
    
    -- Create Tabs
    self:CreateTabs()
    
    -- Show first tab by default
    self:ShowTab("cursor")
    
    return settingsFrame
end

-------------------------
-- Create Tabs
-------------------------
function AiB.Settings:CreateTabs()
    local tabs = {
        {id = "cursor", name = "Cursor", icon = "Interface\\Icons\\Ability_Hunter_MasterMarksman"},
        {id = "crosshair", name = "Fadenkreuz", icon = "Interface\\Icons\\Ability_Hunter_SniperShot"},
        {id = "breaktimer", name = "BreakTimer", icon = "Interface\\Icons\\Spell_Nature_TimeStop"},
        {id = "portals", name = "Portals", icon = "Interface\\Icons\\Spell_Arcane_PortalDalaran"},
        {id = "autoaccept", name = "Auto-Accept", icon = "Interface\\Icons\\Ability_Warrior_VictoryRush"},
        {id = "calltoarms", name = "Call to Arms", icon = "Interface\\Icons\\Achievement_Dungeon_GloryoftheRaider"},
        {id = "dontrelease", name = "Don't Release", icon = "Interface\\Icons\\Spell_Holy_Resurrection"},
    }
    
    local xOffset = 0
    local buttonHeight = 26  -- Wie Boss-Tabs (nicht 35!)
    local spacing = 5
    
    for i, tabData in ipairs(tabs) do
        local btn = CreateFrame("Button", nil, settingsFrame.tabContainer, "BackdropTemplate")
        
        -- Backdrop wie Boss-Tabs
        btn:SetBackdrop(AiB.Utils:CreateBackdrop(btn, "Interface\\Buttons\\WHITE8x8", nil, 1))
        AiB.Themes:ApplyToFrame(btn, "tab_normal", "border_secondary")
        
        -- Icon
        local icon = btn:CreateTexture(nil, "ARTWORK")
        icon:SetSize(20, 20)
        icon:SetPoint("LEFT", btn, "LEFT", 5, 0)
        icon:SetTexture(tabData.icon)
        icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
        btn.icon = icon
        
        -- Text
        local text = btn:CreateFontString(nil, "OVERLAY")
        text:SetFont("Fonts\\FRIZQT__.TTF", 14)
        text:SetPoint("LEFT", icon, "RIGHT", 5, 0)
        text:SetText(tabData.name)
        AiB.Themes:ApplyToText(text, "text_primary")
        btn.text = text
        
        -- Dynamische Größe basierend auf Text
        local textWidth = text:GetUnboundedStringWidth()
        btn:SetSize(math.max(textWidth + 35, 100), buttonHeight)
        
        -- POSITION setzen!
        btn:SetPoint("LEFT", settingsFrame.tabContainer, "LEFT", xOffset, 0)
        
        -- GLOW-Effekt wie bei Boss-Tabs!
        AiB.Animations:CreateGlow(btn, {AiB.Themes:GetColor("glow_color")})
        
        -- Click Handler
        btn:SetScript("OnClick", function(self)
            AiB.Settings:ShowTab(tabData.id)
            
            -- Sound
            if AiB.Utils then
                AiB.Utils:PlaySound(AiB.Utils.Sounds.CLICK)
            end
        end)
        
        -- Hover mit Tooltip (wie Boss-Tabs!)
        btn:SetScript("OnEnter", function(self)
            if currentTab ~= tabData.id then
                AiB.Themes:ApplyToFrame(self, "tab_hover", "border_accent")
            end
            
            GameTooltip:SetOwner(self, "ANCHOR_TOP")
            GameTooltip:AddLine(tabData.name, 1, 1, 1)
            GameTooltip:AddLine("Klicke um Einstellungen anzuzeigen", 0.8, 0.8, 0.8)
            GameTooltip:Show()
            
            if AiB.Utils then
                AiB.Utils:PlaySound(AiB.Utils.Sounds.HOVER)
            end
        end)
        
        btn:SetScript("OnLeave", function(self)
            if currentTab ~= tabData.id then
                AiB.Themes:ApplyToFrame(self, "tab_normal", "border_secondary")
            end
            GameTooltip:Hide()
        end)
        
        tabButtons[tabData.id] = btn
        xOffset = xOffset + btn:GetWidth() + spacing
    end
end

-------------------------
-- Show Tab
-------------------------
function AiB.Settings:ShowTab(tabId)
    -- Deselect all tabs (wie Boss-Tabs mit Glow!)
    for id, btn in pairs(tabButtons) do
        AiB.Themes:ApplyToFrame(btn, "tab_normal", "border_secondary")
        AiB.Themes:ApplyToText(btn.text, "text_primary")  -- Weiß
        AiB.Animations:StopGlow(btn)  -- GLOW stoppen!
    end
    
    -- Select current tab (wie Boss-Tabs mit Glow!)
    if tabButtons[tabId] then
        AiB.Themes:ApplyToFrame(tabButtons[tabId], "tab_selected", "border_accent")
        AiB.Themes:ApplyToText(tabButtons[tabId].text, "text_primary")  -- BLEIBT weiß!
        AiB.Animations:StartGlow(tabButtons[tabId])  -- GLOW starten!
    end
    
    currentTab = tabId
    
    -- Clear content - ROBUSTER!
    local scrollChild = contentFrame.scrollChild
    
    -- Methode 1: Hide und clear all children
    for i = scrollChild:GetNumChildren(), 1, -1 do
        local child = select(i, scrollChild:GetChildren())
        if child then
            child:Hide()
            child:ClearAllPoints()
            child:SetParent(nil)
        end
    end
    
    -- Methode 2: Clear all regions (FontStrings, Textures)
    for i = scrollChild:GetNumRegions(), 1, -1 do
        local region = select(i, scrollChild:GetRegions())
        if region and region ~= scrollChild then
            region:Hide()
            if region.ClearAllPoints then
                region:ClearAllPoints()
            end
        end
    end
    
    -- Load tab content
    if tabId == "cursor" then
        self:LoadCursorSettings(scrollChild)
    elseif tabId == "crosshair" then
        self:LoadCrosshairSettings(scrollChild)
    elseif tabId == "breaktimer" then
        self:LoadBreakTimerSettings(scrollChild)
    elseif tabId == "portals" then
        self:LoadPortalsSettings(scrollChild)
    elseif tabId == "autoaccept" then
        self:LoadAutoAcceptSettings(scrollChild)
    elseif tabId == "calltoarms" then
        self:LoadCallToArmsSettings(scrollChild)
    elseif tabId == "dontrelease" then
        self:LoadDontReleaseSettings(scrollChild)
    end
    
    -- DYNAMISCHE HÖHE basierend auf Content!
    C_Timer.After(0.1, function()
        if not scrollChild then return end
        
        -- Finde tiefsten Punkt aller Children
        local maxY = 0
        for i = 1, scrollChild:GetNumChildren() do
            local child = select(i, scrollChild:GetChildren())
            if child and child:IsShown() then
                local _, _, _, _, bottom = child:GetPoint(1)
                if bottom then
                    maxY = math.max(maxY, math.abs(bottom))
                end
            end
        end
        
        -- Setze Höhe auf Content + Buffer
        local contentHeight = math.max(maxY + 50, contentFrame:GetHeight())
        scrollChild:SetHeight(contentHeight)
        
        -- Update ScrollBar
        if contentFrame.ScrollBar then
            contentFrame.ScrollBar:SetMinMaxValues(0, math.max(0, contentHeight - contentFrame:GetHeight()))
        end
    end)
    
    -- Reset scroll
    if contentFrame.ScrollBar then
        contentFrame.ScrollBar:SetValue(0)
    end
end

-------------------------
-- Load Cursor Settings
-------------------------
function AiB.Settings:LoadCursorSettings(parent)
    local yOffset = -20
    
    -- Cursor Settings (hat eigene Aktivieren-Checkbox)
    if AiB.CursorSettings and AiB.CursorSettings.AddToSettingsPanel then
        yOffset = AiB.CursorSettings:AddToSettingsPanel(parent, yOffset)
    end
end

-------------------------
-- Load Crosshair Settings
-------------------------
function AiB.Settings:LoadCrosshairSettings(parent)
    local yOffset = -20
    
    -- Crosshair Settings (hat eigene Aktivieren-Checkbox)
    if AiB.CrosshairSettings and AiB.CrosshairSettings.AddToSettingsPanel then
        yOffset = AiB.CrosshairSettings:AddToSettingsPanel(parent, yOffset)
    end
end

-------------------------
-- Load BreakTimer Settings
-------------------------
function AiB.Settings:LoadBreakTimerSettings(parent)
    local yOffset = -20
    
    -- Aktivieren Checkbox
    local enableCB = AiB.Utils:CreateCheckbox(parent, "BreakTimer aktivieren",
        AiB_BreakTimerConfig and AiB_BreakTimerConfig.enabled or false,
        function(checked)
            if AiB_BreakTimerConfig then
                AiB_BreakTimerConfig.enabled = checked
            end
        end
    )
    enableCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    yOffset = yOffset - 40
    
    -- BreakTimer Settings
    if AiB.BreakTimerSettings and AiB.BreakTimerSettings.AddToSettingsPanel then
        yOffset = AiB.BreakTimerSettings:AddToSettingsPanel(parent, yOffset)
    end
end

-------------------------
-- Load Auto-Accept Settings
-------------------------
function AiB.Settings:LoadAutoAcceptSettings(parent)
    local FONT = "Fonts\\FRIZQT__.TTF"
    local yOffset = -20
    
    -- Aktivieren Checkbox
    local enableCB = AiB.Utils:CreateCheckbox(parent, "Auto-Accept aktivieren",
        AiB_Settings and AiB_Settings.auto_accept or false,
        function(checked)
            if AiB_Settings then
                AiB_Settings.auto_accept = checked
            end
        end
    )
    enableCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    yOffset = yOffset - 50
    
    -- === ROLLEN-PRÄFERENZEN ===
    local rolesHeader = parent:CreateFontString(nil, "OVERLAY")
    rolesHeader:SetFont(FONT, 14, "OUTLINE")
    rolesHeader:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    rolesHeader:SetText("Rollen-Präferenzen")
    rolesHeader:SetTextColor(1, 0.8, 0, 1)
    yOffset = yOffset - 35
    
    -- Tank
    local tankIcon = parent:CreateTexture(nil, "ARTWORK")
    tankIcon:SetSize(20, 20)
    tankIcon:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset - 2)
    tankIcon:SetAtlas("roleicon-tiny-tank")
    
    local tankCB = AiB.Utils:CreateCheckbox(parent, "Tank",
        AiB_Settings.roles and AiB_Settings.roles.tank or false,
        function(checked)
            AiB_Settings.roles = AiB_Settings.roles or {}
            AiB_Settings.roles.tank = checked
        end
    )
    tankCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 45, yOffset)
    
    -- Healer
    local healerIcon = parent:CreateTexture(nil, "ARTWORK")
    healerIcon:SetSize(20, 20)
    healerIcon:SetPoint("TOPLEFT", parent, "TOPLEFT", 180, yOffset - 2)
    healerIcon:SetAtlas("roleicon-tiny-healer")
    
    local healerCB = AiB.Utils:CreateCheckbox(parent, "Healer",
        AiB_Settings.roles and AiB_Settings.roles.healer or false,
        function(checked)
            AiB_Settings.roles = AiB_Settings.roles or {}
            AiB_Settings.roles.healer = checked
        end
    )
    healerCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 205, yOffset)
    
    -- DPS
    local dpsIcon = parent:CreateTexture(nil, "ARTWORK")
    dpsIcon:SetSize(20, 20)
    dpsIcon:SetPoint("TOPLEFT", parent, "TOPLEFT", 340, yOffset - 2)
    dpsIcon:SetAtlas("roleicon-tiny-dps")
    
    local dpsCB = AiB.Utils:CreateCheckbox(parent, "DPS",
        AiB_Settings.roles and AiB_Settings.roles.dps or false,
        function(checked)
            AiB_Settings.roles = AiB_Settings.roles or {}
            AiB_Settings.roles.dps = checked
        end
    )
    dpsCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 365, yOffset)
    yOffset = yOffset - 40
    
    -- Kurzer Hinweis
    local info = parent:CreateFontString(nil, "OVERLAY")
    info:SetFont(FONT, 11)
    info:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    info:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, yOffset)
    info:SetJustifyH("LEFT")
    info:SetText("Wähle welche Rollen automatisch akzeptiert werden sollen.")
    info:SetTextColor(0.7, 0.7, 0.7, 1)
end

-------------------------
-- Load Portals Settings (Portal Visibility + Hearthstone Toys)
-------------------------
function AiB.Settings:LoadPortalsSettings(parent)
    local FONT = "Fonts\\FRIZQT__.TTF"
    local yOffset = -20
    
    -------------------------
    -- SECTION 1: Portal Visibility
    -------------------------
    local portalHeader = parent:CreateFontString(nil, "OVERLAY")
    portalHeader:SetFont(FONT, 14, "OUTLINE")
    portalHeader:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    portalHeader:SetText("Portal Sichtbarkeit")
    portalHeader:SetTextColor(1, 0.8, 0, 1)
    yOffset = yOffset - 35
    
    -- Hide Unlearned Portals Checkbox
    local hideUnlearnedCB = AiB.Utils:CreateCheckbox(parent, "Nicht gelernte Portale ausblenden",
        AiB_Settings.hide_unlearned_portals or false,
        function(checked)
            AiB_Settings.hide_unlearned_portals = checked
            
            -- Reset Portal-Frame damit es beim nächsten Öffnen neu erstellt wird
            if AiB_Portals and AiB_Portals.ResetPopup then
                AiB_Portals:ResetPopup()
            end
        end
    )
    hideUnlearnedCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    yOffset = yOffset - 35
    
    local portalInfo = parent:CreateFontString(nil, "OVERLAY")
    portalInfo:SetFont(FONT, 11)
    portalInfo:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
    portalInfo:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, yOffset)
    portalInfo:SetJustifyH("LEFT")
    portalInfo:SetWordWrap(true)
    portalInfo:SetText("Wenn aktiviert, werden nur gelernte Portale im normalen Portal-Frame angezeigt. Das Extra-Frame über dem LFG zeigt immer alle Portale.")
    portalInfo:SetTextColor(0.7, 0.7, 0.7, 1)
    yOffset = yOffset - 60
    
    -------------------------
    -- SECTION 2: Hearthstone Toys (kein Header hier - kommt von HearthstoneToys:LoadSettings)
    -------------------------
    
    -- Delegate to HearthstoneToys system
    if AiB.HearthstoneToys and AiB.HearthstoneToys.LoadSettings then
        -- Create sub-parent für Hearthstone Settings
        local hearthParent = CreateFrame("Frame", nil, parent)
        hearthParent:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, yOffset)
        hearthParent:SetPoint("TOPRIGHT", parent, "TOPRIGHT", 0, yOffset)
        hearthParent:SetHeight(800) -- Erhöht von 600 auf 800
        
        -- Speichere scrollChild Referenz für Höhen-Update
        hearthParent.scrollChild = parent
        
        AiB.HearthstoneToys:LoadSettings(hearthParent)
    else
        local errorText = parent:CreateFontString(nil, "OVERLAY")
        errorText:SetFont(FONT, 11)
        errorText:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        errorText:SetText("Hearthstone Toy System nicht geladen")
        errorText:SetTextColor(1, 0.5, 0.5, 1)
    end
end

-------------------------
-- Load Call to Arms Settings
-------------------------
function AiB.Settings:LoadCallToArmsSettings(parent)
    local yOffset = -20
    
    -- Call to Arms Settings (hat eigene Aktivieren-Checkbox)
    if AiB.CallToArmsSettings and AiB.CallToArmsSettings.AddToSettingsPanel then
        yOffset = AiB.CallToArmsSettings:AddToSettingsPanel(parent, yOffset)
    end
end

-------------------------
-- Load Don't Release Settings
-------------------------
function AiB.Settings:LoadDontReleaseSettings(parent)
    local yOffset = -20
    
    -- Don't Release Settings (hat eigene Aktivieren-Checkbox)
    if AiB.DontReleaseSettings and AiB.DontReleaseSettings.AddToSettingsPanel then
        yOffset = AiB.DontReleaseSettings:AddToSettingsPanel(parent, yOffset)
    end
end

-------------------------
-- Show Settings
-------------------------
function AiB.Settings:Show()
    if settingsFrame then
        settingsFrame:Show()
    end
end

-------------------------
-- Hide Settings
-------------------------
function AiB.Settings:Hide()
    if settingsFrame then
        settingsFrame:Hide()
    end
end

-------------------------
-- Register as Content
-------------------------
AiB_Content = AiB_Content or {}
AiB_Content["Settings"] = function(contentFrame)
    -- Create or get settings frame
    local settings = AiB.Settings:CreateSettingsFrame(contentFrame)
    settings:Show()
end
