-------------------------
-- AiB v2.1 - All into Boss
-------------------------
-- Profil-System via AceDB-3.0 | 2.1.0.0

AiB = AiB or {}

-- AiB.db wird in ADDON_LOADED gesetzt (siehe Ende dieser Datei)
-- Alle Config-Globalen sind Aliases auf AiB.db.profile.*

-- Lokale Variablen
local currentMode = "Raid"  -- wird nach ADDON_LOADED aus AiB.db.char.mode geladen
local currentTabName = nil
local createdTabs = {}
local selectedTab = nil
local currentNavState = "HOME" -- HOME, SETTINGS, PORTALS, RAID_DUNGEON

-------------------------
-- MAIN FRAME
-------------------------
local mainFrame = CreateFrame("Frame", "AiBFrame", UIParent, "BackdropTemplate")
mainFrame:SetSize(AiB.Config:GetUIValue("MAIN_WIDTH"), AiB.Config:GetUIValue("MAIN_HEIGHT"))
mainFrame:SetPoint("CENTER")
mainFrame:SetFrameStrata("HIGH")
mainFrame:SetMovable(true)
mainFrame:EnableMouse(true)
mainFrame:RegisterForDrag("LeftButton")
mainFrame:SetClampedToScreen(false)  -- Erlaubt Verschieben über Bildschirmrand

-- Exportiere für Portal-System
AiB.MainFrame = mainFrame

-- Backdrop
mainFrame:SetBackdrop(AiB.Utils:CreateBackdrop(mainFrame))
AiB.Themes:ApplyToFrame(mainFrame, "bg_primary", "border_primary")

-- Drag & Drop
mainFrame:SetScript("OnDragStart", function(self)
    self:StartMoving()
end)

mainFrame:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
    AiB.Utils:SavePosition(self, "mainFrame")
end)

-- OnShow Handler - Safety Check für Position
mainFrame:SetScript("OnShow", function(self)
    -- Checke ob Fenster komplett außerhalb des Bildschirms ist
    local screenWidth = GetScreenWidth()
    local screenHeight = GetScreenHeight()
    local left = self:GetLeft()
    local right = self:GetRight()
    local top = self:GetTop()
    local bottom = self:GetBottom()
    
    -- Wenn Fenster komplett außerhalb oder Position ungültig
    if not left or not right or not top or not bottom or
       right < 0 or left > screenWidth or
       bottom > screenHeight or top < 0 then
        -- Reset zur Mitte
        self:ClearAllPoints()
        self:SetPoint("CENTER")
        print("|cFFFF8800[AiB]|r Fensterposition war außerhalb - zurückgesetzt. Nutze /aib reset für manuelle Zentrierung.")
    end
end)

-- OnHide Handler - schließt Portal-Popup mit
mainFrame:SetScript("OnHide", function()
    if AiB_Portals then
        AiB_Portals:Hide()
    end
end)

-- ESC-Taste schließt das Fenster
table.insert(UISpecialFrames, "AiBFrame")

-------------------------
-- COPYRIGHT TEXT
-------------------------
local copyright = mainFrame:CreateFontString(nil, "OVERLAY")
copyright:SetFont("Fonts\\FRIZQT__.TTF", 9)
copyright:SetPoint("BOTTOMLEFT", mainFrame, "BOTTOMLEFT", 10, 5)
copyright:SetText("© Rinova")
copyright:SetTextColor(0.5, 0.5, 0.5, 0.8) -- Grau, leicht transparent

-- Version Info (rechts neben Copyright)
local versionInfo = mainFrame:CreateFontString(nil, "OVERLAY")
versionInfo:SetFont("Fonts\\FRIZQT__.TTF", 9)
versionInfo:SetPoint("LEFT", copyright, "RIGHT", 10, 0)
versionInfo:SetText("AiB v" .. AiB.Config.VERSION .. " | Build " .. AiB.Config.BUILD)
versionInfo:SetTextColor(0.5, 0.5, 0.5, 0.8) -- Grau, leicht transparent

-- Speichere MainFrame für andere Module
AiB.MainFrame = mainFrame

-------------------------
-- CLOSE BUTTON (Modern Design)
-------------------------
local closeButton = CreateFrame("Button", nil, mainFrame, "BackdropTemplate")
closeButton:SetSize(28, 28)
closeButton:SetPoint("TOPRIGHT", mainFrame, "TOPRIGHT", -8, -8)

-- Backdrop (runder Hintergrund)
closeButton:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 1,
    insets = { left = 1, right = 1, top = 1, bottom = 1 },
})
closeButton:SetBackdropColor(0.15, 0.15, 0.15, 0.9)
closeButton:SetBackdropBorderColor(0.3, 0.3, 0.3, 1)

-- X-Symbol (mit FontString)
local xText = closeButton:CreateFontString(nil, "OVERLAY")
xText:SetFont("Fonts\\FRIZQT__.TTF", 18, "OUTLINE")
xText:SetPoint("CENTER", 0, 0)
xText:SetText("×")  -- Multiplikationszeichen (sieht besser aus als X)
xText:SetTextColor(0.8, 0.8, 0.8, 1)

-- Click Handler
closeButton:SetScript("OnClick", function()
    mainFrame:Hide()
    -- Schließe auch Portal-Popup falls offen
    if AiB_Portals then
        AiB_Portals:Hide()
    end
    if AiB.Utils then
        AiB.Utils:PlaySound(AiB.Utils.Sounds.CLOSE)
    end
end)

-- Hover Effekt
closeButton:SetScript("OnEnter", function(self)
    self:SetBackdropColor(0.8, 0.1, 0.1, 1)  -- Rot beim Hover
    self:SetBackdropBorderColor(1, 0.2, 0.2, 1)
    xText:SetTextColor(1, 1, 1, 1)  -- Weißes X
    
    -- Glow
    AiB.Animations:StartGlow(self)
    
    -- Tooltip
    GameTooltip:SetOwner(self, "ANCHOR_LEFT")
    GameTooltip:SetText("Schließen", 1, 1, 1)
    GameTooltip:AddLine("ESC funktioniert auch", 0.5, 0.5, 0.5, 1)
    GameTooltip:Show()
end)

closeButton:SetScript("OnLeave", function(self)
    self:SetBackdropColor(0.15, 0.15, 0.15, 0.9)  -- Zurück zu dunkel
    self:SetBackdropBorderColor(0.3, 0.3, 0.3, 1)
    xText:SetTextColor(0.8, 0.8, 0.8, 1)  -- Zurück zu grau
    
    AiB.Animations:StopGlow(self)
    GameTooltip:Hide()
end)

-- Glow erstellen
AiB.Animations:CreateGlow(closeButton, {1, 0.2, 0.2})

-------------------------
-- TITEL & BANNER
-------------------------
local title = mainFrame:CreateFontString(nil, "OVERLAY")
title:SetFont(AiB.Config:GetFont("PRIMARY"), 28, "OUTLINE")
title:SetPoint("TOP", mainFrame, "TOP", 0, -55)
title:SetText("|cFFFF0000AiB|r |cFFFF0000- All|r |cFFFFFFFFinto|r |cFFFF0000Boss|r |cFFFFFFFFRaidtools|r")
title:SetDrawLayer("OVERLAY", 7) -- Höherer Layer damit es über Content liegt

local subtitle = mainFrame:CreateFontString(nil, "OVERLAY")
subtitle:SetFont(AiB.Config:GetFont("SECONDARY"), 14)
subtitle:SetPoint("TOP", title, "BOTTOM", 0, -5)
subtitle:SetText("Raidtools für Midnight")
subtitle:SetDrawLayer("OVERLAY", 7) -- Höherer Layer
AiB.Themes:ApplyToText(subtitle, "text_secondary")

local banner = mainFrame:CreateTexture(nil, "BACKGROUND")
banner:SetTexture("Interface\\AddOns\\aib\\textures\\aib.tga")
banner:SetSize(1196, 175)
banner:SetPoint("TOP", mainFrame, "TOP", 0, -85)
banner:SetAlpha(0.95)
banner:SetDrawLayer("BACKGROUND", 7) -- Höherer Layer im Background

-------------------------
-- NAVIGATION BAR (ÜBER DEM LOGO - auf gleicher Höhe wie Switch)
-------------------------
local navBar = CreateFrame("Frame", nil, mainFrame)
navBar:SetSize(850, 40) -- Für 5 Buttons: Home + Raid + M+ + Portale + Settings
navBar:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 30, -7)

local navButtons = {}
local homeBtn, settingsBtn, portalsBtn

-- Wird später befüllt

-- Navigation wird in Initialize erstellt

-------------------------
-- SEPARATOR
-------------------------
local separator = mainFrame:CreateTexture(nil, "ARTWORK")
separator:SetColorTexture(AiB.Themes:GetColor("border_accent"))
separator:SetSize(1140, 2)
separator:SetPoint("TOP", mainFrame, "TOP", 0, -265)

-------------------------
-- TAB CONTAINER
-------------------------
local tabContainer = CreateFrame("Frame", nil, mainFrame)
tabContainer:SetSize(1140, 80)
tabContainer:SetPoint("TOP", separator, "BOTTOM", 0, -10)
tabContainer:Hide() -- Standardmäßig versteckt

-------------------------
-- CONTENT FRAME
-------------------------
local contentFrame = CreateFrame("Frame", "AiBContentFrame", mainFrame)
contentFrame:SetSize(1140, 520)
-- WICHTIG: Wird dynamisch neu positioniert je nach State
contentFrame:SetPoint("TOP", separator, "BOTTOM", 0, -10) -- Direkt unter Separator
contentFrame:SetClipsChildren(true)

-- SEPARATE Container für Settings (NICHT im ContentFrame!)
local settingsContainer = CreateFrame("Frame", "AiBSettingsContainer", mainFrame)
settingsContainer:SetSize(1140, 600)
settingsContainer:SetPoint("TOP", separator, "BOTTOM", 0, -10)
settingsContainer:SetClipsChildren(true) -- WICHTIG: Verhindert dass Content über Frame hinaus sichtbar ist
settingsContainer:Hide()

-- Portals wird LAZY im ContentFrame erstellt (beim ersten ShowPortalsView Aufruf)

-------------------------
-- TAB FUNCTIONS
-------------------------
-- Forward declaration
local LoadTabContent

local function CreateDynamicTab(parent, text, index)
    local tab = CreateFrame("Button", nil, parent, "BackdropTemplate")
    
    tab:SetBackdrop(AiB.Utils:CreateBackdrop(tab, "Interface\\Buttons\\WHITE8x8", nil, 1))
    AiB.Themes:ApplyToFrame(tab, "tab_normal", "border_secondary")
    
    local icon = tab:CreateTexture(nil, "ARTWORK")
    icon:SetSize(20, 20)
    icon:SetPoint("LEFT", tab, "LEFT", 5, 0)
    icon:SetTexture("Interface\\AddOns\\aib\\textures\\aib_icon.tga")
    icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
    
    local tabText = tab:CreateFontString(nil, "OVERLAY")
    tabText:SetFont("Fonts\\FRIZQT__.TTF", 14)
    tabText:SetText(text)
    AiB.Themes:ApplyToText(tabText, "text_primary")
    tabText:SetPoint("LEFT", icon, "RIGHT", 5, 0)
    
    local textWidth = tabText:GetUnboundedStringWidth()
    tab:SetSize(math.max(textWidth + 35, 100), 26)
    
    AiB.Animations:CreateGlow(tab, {AiB.Themes:GetColor("glow_color")})
    
    tab:SetScript("OnClick", function(self)
        LoadTabContent(text)
        
        if selectedTab then
            AiB.Themes:ApplyToFrame(selectedTab, "tab_normal", "border_secondary")
            AiB.Animations:StopGlow(selectedTab)
        end
        
        selectedTab = self
        AiB.Themes:ApplyToFrame(self, "tab_selected", "border_accent")
        AiB.Animations:StartGlow(self)
        
        if AiB.Utils then
            AiB.Utils:PlaySound(AiB.Utils.Sounds.CLICK)
        end
    end)
    
    tab:SetScript("OnEnter", function(self)
        if self ~= selectedTab then
            AiB.Themes:ApplyToFrame(self, "tab_hover", "border_accent")
        end
        
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:AddLine(text, 1, 1, 1)
        GameTooltip:AddLine("Klicke um Inhalte anzuzeigen", 0.8, 0.8, 0.8)
        GameTooltip:Show()
        
        if AiB.Utils then
            AiB.Utils:PlaySound(AiB.Utils.Sounds.HOVER)
        end
    end)
    
    tab:SetScript("OnLeave", function(self)
        if self ~= selectedTab then
            AiB.Themes:ApplyToFrame(self, "tab_normal", "border_secondary")
        end
        GameTooltip:Hide()
    end)
    
    return tab
end

local function CreateTabs()
    -- Cleanup alte Tabs
    for _, tab in ipairs(createdTabs) do
        tab:Hide()
        tab:SetParent(nil)
    end
    wipe(createdTabs)
    selectedTab = nil
    
    local tabs = (currentMode == "Raid") and AiB.Config.RAID_TABS or AiB.Config.DUNGEON_TABS
    
    local tabSpacing = AiB.Config:GetUIValue("TAB_SPACING")
    local startY = 0
    local maxRowWidth = 1140
    local currentY = startY
    local rowTabs = {}
    local rowWidth = 0
    
    for i, tabName in ipairs(tabs) do
        local tab = CreateDynamicTab(tabContainer, tabName, i)
        local tabWidth = tab:GetWidth()
        
        if (rowWidth + tabWidth + tabSpacing) > maxRowWidth then
            -- Neue Reihe
            local startX = (1140 - rowWidth) / 2
            for idx, t in ipairs(rowTabs) do
                t:ClearAllPoints()
                t:SetPoint("TOPLEFT", tabContainer, "TOPLEFT", startX, currentY)
                startX = startX + t:GetWidth() + tabSpacing
                
                t:SetAlpha(1)
                t:Show()
            end
            
            rowTabs = {}
            rowWidth = 0
            currentY = currentY - 32
        end
        
        table.insert(rowTabs, tab)
        table.insert(createdTabs, tab)
        rowWidth = rowWidth + tabWidth + tabSpacing
    end
    
    -- Letzte Reihe platzieren
    if #rowTabs > 0 then
        local startX = (1140 - rowWidth) / 2
        for idx, t in ipairs(rowTabs) do
            t:ClearAllPoints()
            t:SetPoint("TOPLEFT", tabContainer, "TOPLEFT", startX, currentY)
            startX = startX + t:GetWidth() + tabSpacing
            
            t:SetAlpha(1)
            t:Show()
        end
    end
end

function LoadTabContent(tabName)
    if not tabName then
        print("|cFFFF0000AiB:|r LoadTabContent called with nil tabName!") -- ERROR
        return
    end
    
    
    -- Cleanup ContentFrame - verstecke alte Children (aber behalte sie als Parent!)
    for _, child in ipairs({contentFrame:GetChildren()}) do
        if child:GetName() ~= "AiBPortalFrame" then
            child:Hide()
        end
    end
    
    -- Spezial-Frame (AiB_Portals) extra verstecken falls vorhanden
    if AiB_Portals then
        AiB_Portals:Hide()
    end
    
    for _, region in ipairs({contentFrame:GetRegions()}) do
        if region:GetObjectType() == "FontString" then
            region:Hide()
            region:SetText("")
        end
    end
    
    contentFrame:Show()
    currentTabName = tabName
    
    -- Lade Content
    if AiB_Content and AiB_Content[tabName] then
        local success, err = pcall(function()
            AiB_Content[tabName](contentFrame)
        end)
        
        if not success then
            print("|cFFFF0000AiB:|r ERROR: " .. tostring(err)) -- ERROR
            
            local errorText = contentFrame:CreateFontString(nil, "OVERLAY")
            errorText:SetFont("Fonts\\FRIZQT__.TTF", 14)
            errorText:SetPoint("CENTER")
            errorText:SetText("Fehler:\n" .. tabName .. "\n\n" .. tostring(err))
            errorText:SetTextColor(1, 0, 0, 1)
        else
        end
        
        if AiB.Utils then
            AiB.Utils:PlaySound(AiB.Utils.Sounds.TAB)
        end
    else
        print("|cFFFF0000AiB:|r No content for: " .. tabName) -- ERROR
        
        local placeholderText = contentFrame:CreateFontString(nil, "OVERLAY")
        placeholderText:SetFont("Fonts\\FRIZQT__.TTF", 16)
        placeholderText:SetPoint("CENTER")
        placeholderText:SetText("[" .. tabName .. "]\n\nContent wird geladen...")
        placeholderText:SetTextColor(1, 1, 1, 1)
    end
end

-------------------------
-- VIEW FUNCTIONS  
-------------------------
function ShowHomeView()
    
    -- Verstecke andere Container
    settingsContainer:Hide()
    if AiB_Portals then AiB_Portals:Hide() end
    tabContainer:Hide()
    
    -- ContentFrame positionieren und anzeigen
    contentFrame:ClearAllPoints()
    contentFrame:SetPoint("TOP", separator, "BOTTOM", 0, -10)
    contentFrame:SetSize(1140, 600)
    contentFrame:Show()
    
    -- Content laden
    LoadTabContent("Home")
end

function ShowSettingsView()
    
    -- Verstecke andere Container
    contentFrame:Hide()
    tabContainer:Hide()
    if AiB_Portals then AiB_Portals:Hide() end
    
    -- Settings Container anzeigen
    settingsContainer:Show()
    
    -- Settings laden - prüfe ob das neue Tab-System existiert
    if AiB.Settings and AiB.Settings.CreateSettingsFrame then
        -- Neues Tab-basiertes System
        local settingsFrame = AiB.Settings:CreateSettingsFrame(settingsContainer)
        if settingsFrame then
            settingsFrame:Show()
        else
            print("|cFFFF0000[AiB Debug]|r Settings Frame konnte nicht erstellt werden!")
        end
    elseif AiB_Content and AiB_Content["Settings"] then
        -- Fallback auf Content-System
        AiB_Content["Settings"](settingsContainer)
    else
        -- Debug: Zeige was verfügbar ist
        print("|cFFFF0000[AiB Debug]|r Settings-System nicht gefunden!")
        print("AiB exists:", AiB ~= nil)
        print("AiB.Settings exists:", AiB and AiB.Settings ~= nil or false)
        print("AiB_Content exists:", AiB_Content ~= nil)
    end
end

function ShowPortalsView()
    
    -- Verstecke andere Container
    settingsContainer:Hide()
    tabContainer:Hide()
    contentFrame:Hide()
    
    -- Erstelle und zeige Portal Popup
    if AiB_Portals then
        AiB_Portals:CreatePopup(mainFrame, separator)
        AiB_Portals:Show()
    else
    end
end

function ShowRaidDungeonView()
    
    -- Verstecke andere Container
    settingsContainer:Hide()
    if AiB_Portals then AiB_Portals:Hide() end
    
    -- Tabs ANZEIGEN
    tabContainer:Show()
    
    -- ContentFrame positionieren und anzeigen (UNTER TabContainer)
    contentFrame:ClearAllPoints()
    contentFrame:SetPoint("TOP", tabContainer, "BOTTOM", 0, -10)
    contentFrame:SetSize(1140, 520)
    contentFrame:Show()
    
    -- Tabs erstellen und Content laden
    CreateTabs()
    
    if currentMode == "Raid" then
        LoadTabContent("Raid Allgemein")
    else
        LoadTabContent("Dungeon Allgemein")
    end
end

-------------------------
-- MINIMAP BUTTON
-- Note: Minimap button is loaded separately in aib_minimap.lua (loaded FIRST in TOC)
-- This ensures button collectors can detect it early!
-------------------------

-- Enhance button with Glow and Click Handlers (after main addon loads)
if AiBMinimapButton then
    -- Add Glow effect
    AiB.Animations:CreateGlow(AiBMinimapButton, {AiB.Themes:GetColor("glow_color")})
    
    -- Enhanced Tooltip with Glow
    AiBMinimapButton:SetScript("OnEnter", function(self)
        AiB.Animations:StartGlow(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:AddLine("|cFFFF0000AiB|r - All into Boss", 1, 1, 1)
        GameTooltip:AddLine("Links-Klick: Öffnen", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Rechts-Klick: Settings", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Ziehen: Verschieben", 0.8, 0.8, 0.8)
        GameTooltip:Show()
    end)
    
    AiBMinimapButton:SetScript("OnLeave", function(self)
        AiB.Animations:StopGlow(self)
        GameTooltip:Hide()
    end)
end

-------------------------
-- SLASH COMMANDS
-------------------------
SLASH_AIB1 = "/aib"
SLASH_AIB2 = "/alliintoboss"
SlashCmdList["AIB"] = function(msg)
    msg = msg:lower():trim()
    
    if msg == "config" or msg == "settings" then
        if not mainFrame:IsShown() then
            mainFrame:Show()
        end
        settingsBtn:GetScript("OnClick")(settingsBtn)
    elseif msg == "portals" or msg == "portal" then
        if not mainFrame:IsShown() then
            mainFrame:Show()
        end
        portalsBtn:GetScript("OnClick")(portalsBtn)
    elseif msg == "reset" then
        mainFrame:ClearAllPoints()
        mainFrame:SetPoint("CENTER")
        if AiB.db then AiB.db.profile.settings.positions = nil end
        print("|cFF00FF00AiB:|r Fensterposition zurückgesetzt")
    elseif msg == "debug" then
        AiB.Config.DEBUG = not AiB.Config.DEBUG
        print("|cFF00FF00AiB:|r Debug Modus " .. (AiB.Config.DEBUG and "aktiviert" or "deaktiviert"))
    elseif msg == "version" or msg == "v" then
        print("|cFF00FF00AiB:|r Version " .. AiB.Config.VERSION .. " (Build " .. AiB.Config.BUILD .. ")")
    elseif msg == "help" then
        print("|cFF00FF00=== AiB Commands ===|r")
        print("|cFFFFFF00/aib|r - Öffnet das Hauptfenster")
        print("|cFFFFFF00/aib config|r - Öffnet die Einstellungen")
        print("|cFFFFFF00/aib portals|r - Öffnet die Portal-Bibliothek")
        print("|cFFFFFF00/aib reset|r - Setzt Fensterposition zurück")
        print("|cFFFFFF00/aib version|r - Zeigt Version an")
        print("|cFFFFFF00/aib debug|r - Aktiviert Debug-Modus")
    elseif msg == "test" then
        print("|cFF00FF00AiB Debug Info:|r")
        print("MainFrame exists: " .. tostring(mainFrame ~= nil))
        print("MainFrame shown: " .. tostring(mainFrame and mainFrame:IsShown()))
        print("Current Mode: " .. currentMode)
        print("Current Nav State: " .. currentNavState)
        print("Current Tab: " .. (currentTabName or "nil"))
        print("ContentFrame shown: " .. tostring(contentFrame:IsShown()))
        print("TabContainer shown: " .. tostring(tabContainer:IsShown()))
        print("Available Content:")
        if AiB_Content then
            local count = 0
            for name, _ in pairs(AiB_Content) do
                print("  - " .. name)
                count = count + 1
            end
            print("Total: " .. count .. " content entries")
        else
            print("  ERROR: AiB_Content is nil!")
        end
        
        local contentCount = 0
        if AiB_Content then
            for k, v in pairs(AiB_Content) do
                contentCount = contentCount + 1
                print("  Content key: '" .. tostring(k) .. "'")
            end
        end
        print("Content entries: " .. contentCount)
        
        print("Current mode: " .. currentMode)
        print("Current tab: " .. tostring(currentTabName))
        print("Current nav state: " .. currentNavState)
        
        print("\nExpected content:")
        print("  'Raid Allgemein': " .. tostring(AiB_Content and AiB_Content["Raid Allgemein"] ~= nil))
        print("  'Dungeon Allgemein': " .. tostring(AiB_Content and AiB_Content["Dungeon Allgemein"] ~= nil))
    else
        -- Toggle main window
        if mainFrame:IsShown() then
            mainFrame:Hide()
        else
            mainFrame:Show()
            
            -- Standardmäßig Home zeigen
            currentNavState = "HOME"
            homeBtn:GetScript("OnClick")(homeBtn)
            AiB.Themes:ApplyToFrame(homeBtn, "tab_selected", "border_accent")
            homeBtn.isActive = true
        end
    end
end

-------------------------
-- AUTO-ACCEPT ROLE CHECK (UI Checkbox Methode)
-------------------------
local function CheckAndAcceptRoles()
    if not AiB_Settings.auto_accept then return end
    
    -- Prüfe ob Role Check UI sichtbar ist
    if not (LFDRoleCheckPopup and LFDRoleCheckPopup:IsVisible()) then
        return
    end
    
    -- Prüfe verfügbare Rollen für diesen Char
    local canTank, canHeal, canDPS = UnitGetAvailableRoles("player")
    
    local roles = AiB_Settings.roles or {}
    local tank = false
    local healer = false
    local dps = false
    
    -- Setze Rollen NUR wenn Char sie auch spielen kann!
    if canTank and roles.tank then tank = true end
    if canHeal and roles.healer then healer = true end
    if canDPS and roles.dps then dps = true end
    
    -- Wenn KEINE Rolle ausgewählt oder verfügbar, verwende aktuelle Spec
    if not tank and not healer and not dps then
        local spec = GetSpecialization()
        if spec then
            local role = GetSpecializationRole(spec)
            tank = (role == "TANK")
            healer = (role == "HEALER")
            dps = (role == "DAMAGER")
        end
    end
    
    -- Setze UI Checkboxen direkt
    if LFDRoleCheckPopupRoleButtonTank and LFDRoleCheckPopupRoleButtonTank.checkButton then
        LFDRoleCheckPopupRoleButtonTank.checkButton:SetChecked(tank)
    end
    
    if LFDRoleCheckPopupRoleButtonHealer and LFDRoleCheckPopupRoleButtonHealer.checkButton then
        LFDRoleCheckPopupRoleButtonHealer.checkButton:SetChecked(healer)
    end
    
    if LFDRoleCheckPopupRoleButtonDPS and LFDRoleCheckPopupRoleButtonDPS.checkButton then
        LFDRoleCheckPopupRoleButtonDPS.checkButton:SetChecked(dps)
    end
    
    -- Warte kurz, dann klicke Accept
    C_Timer.After(0.1, function()
        if LFDRoleCheckPopupAcceptButton and LFDRoleCheckPopupAcceptButton:IsEnabled() then
            LFDRoleCheckPopupAcceptButton:Click()
            AiB.Config:Log("Auto-Accept", "Role check auto-accepted")
        end
    end)
end

-- Polling Loop
local function PollRoleCheck()
    CheckAndAcceptRoles()
    
    -- Prüfe alle 0.3s
    C_Timer.After(0.3, function()
        PollRoleCheck()
    end)
end

-- Start Polling
PollRoleCheck()

-- Zusätzlich auch auf Event reagieren
local autoAcceptFrame = CreateFrame("Frame")
autoAcceptFrame:RegisterEvent("LFG_ROLE_CHECK_SHOW")
autoAcceptFrame:SetScript("OnEvent", function(self, event)
    if not AiB_Settings.auto_accept then return end
    
    -- Warte kurz dann check
    C_Timer.After(0.2, function()
        CheckAndAcceptRoles()
    end)
end)

-------------------------
-- INITIALIZATION
-------------------------
local function Initialize()
    -- Navigation Button Erstellen Funktion
    local function CreateNavButton(text, icon, onClick)
        local btn = CreateFrame("Button", nil, navBar, "BackdropTemplate")
        btn:SetSize(140, 35)
        btn:SetBackdrop(AiB.Utils:CreateBackdrop(btn))
        AiB.Themes:ApplyToFrame(btn, "tab_normal", "border_secondary")
        
        if icon then
            local iconTex = btn:CreateTexture(nil, "ARTWORK")
            iconTex:SetSize(20, 20)
            iconTex:SetPoint("LEFT", btn, "LEFT", 10, 0)
            iconTex:SetTexture(icon)
            btn.icon = iconTex
        end
        
        local btnText = btn:CreateFontString(nil, "OVERLAY")
        btnText:SetFont("Fonts\\FRIZQT__.TTF", 14)
        btnText:SetText(text)
        if icon then
            btnText:SetPoint("LEFT", btn.icon, "RIGHT", 8, 0)
        else
            btnText:SetPoint("CENTER")
        end
        AiB.Themes:ApplyToText(btnText, "text_primary")
        
        btn.text = btnText
        btn.onClick = onClick
        btn.isActive = false
        
        btn:SetScript("OnClick", function(self)
            -- Deaktiviere alle Navigation-Buttons
            for _, b in ipairs(navButtons) do
                AiB.Themes:ApplyToFrame(b, "tab_normal", "border_secondary")
                b.isActive = false
            end
            
            -- Aktiviere diesen
            AiB.Themes:ApplyToFrame(self, "tab_selected", "border_accent")
            self.isActive = true
            
            -- Führe Aktion aus
            if self.onClick then
                self.onClick()
            end
            
            if AiB.Utils then
                AiB.Utils:PlaySound(AiB.Utils.Sounds.CLICK)
            end
        end)
        
        btn:SetScript("OnEnter", function(self)
            if not self.isActive then
                AiB.Themes:ApplyToFrame(self, "tab_hover", "border_accent")
            end
        end)
        
        btn:SetScript("OnLeave", function(self)
            if not self.isActive then
                AiB.Themes:ApplyToFrame(self, "tab_normal", "border_secondary")
            end
        end)
        
        return btn
    end
    
    -- 1. Home Button
    homeBtn = CreateNavButton("Home", "Interface\\Icons\\INV_Misc_Home_01", function()
        currentNavState = "HOME"
        ShowHomeView()
    end)
    homeBtn:SetPoint("LEFT", navBar, "LEFT", 0, 0)
    table.insert(navButtons, homeBtn)
    
    -- 2. Raid Button
    local raidBtn = CreateNavButton("Raid", "Interface\\Icons\\Achievement_Boss_Ragnaros", function()
        currentMode = "Raid"
        if AiB.db then AiB.db.char.mode = currentMode end
        currentNavState = "RAID_DUNGEON"
        ShowRaidDungeonView()
    end)
    raidBtn:SetPoint("LEFT", homeBtn, "RIGHT", 10, 0)
    table.insert(navButtons, raidBtn)
    
    -- 3. M+ Button
    local dungeonBtn = CreateNavButton("M+", "Interface\\Icons\\Achievement_ChallengeMode_Gold", function()
        currentMode = "Dungeon"
        if AiB.db then AiB.db.char.mode = currentMode end
        currentNavState = "RAID_DUNGEON"
        ShowRaidDungeonView()
    end)
    dungeonBtn:SetPoint("LEFT", raidBtn, "RIGHT", 10, 0)
    table.insert(navButtons, dungeonBtn)
    
    -- 4. Portale Button
    portalsBtn = CreateNavButton("Portale", "Interface\\Icons\\Spell_Arcane_PortalDarnassus", function()
        currentNavState = "PORTALS"
        ShowPortalsView()
    end)
    portalsBtn:SetPoint("LEFT", dungeonBtn, "RIGHT", 10, 0)
    table.insert(navButtons, portalsBtn)
    
    -- 5. Settings Button
    settingsBtn = CreateNavButton("Settings", "Interface\\Icons\\Trade_Engineering", function()
        currentNavState = "SETTINGS"
        ShowSettingsView()
    end)
    settingsBtn:SetPoint("LEFT", portalsBtn, "RIGHT", 10, 0)
    table.insert(navButtons, settingsBtn)
    
    -- Position laden
    AiB.Utils:LoadPosition(mainFrame, "mainFrame")
    mainFrame:Hide()
    
    -- Minimap Button Setup (wird in aib_minimap.lua erstellt)
    -- OnClick Handler wird hier gesetzt nachdem Button existiert
    if AiBMinimapButton then
        -- Rechtsklick-Menü mit UIDropDownMenu
        local function ShowMinimapMenu(self)
            local menu = CreateFrame("Frame", "AiBMinimapDropDown", UIParent, "UIDropDownMenuTemplate")
            
            local function InitializeMenu(frame, level)
                local info = UIDropDownMenu_CreateInfo()
                
                -- Titel
                info.text = "|cFFFF0000AiB|r - All into Boss"
                info.isTitle = true
                info.notCheckable = true
                UIDropDownMenu_AddButton(info)
                
                -- Addon öffnen
                info = UIDropDownMenu_CreateInfo()
                info.text = "Addon öffnen"
                info.notCheckable = true
                info.func = function()
                    if mainFrame:IsShown() then
                        mainFrame:Hide()
                    else
                        mainFrame:Show()
                        currentNavState = "HOME"
                        if ShowHomeView then
                            ShowHomeView()
                        end
                    end
                    CloseDropDownMenus()
                end
                UIDropDownMenu_AddButton(info)
                
                -- Einstellungen
                info = UIDropDownMenu_CreateInfo()
                info.text = "Einstellungen"
                info.notCheckable = true
                info.func = function()
                    if not mainFrame:IsShown() then
                        mainFrame:Show()
                    end
                    currentNavState = "SETTINGS"
                    if ShowSettingsView then
                        ShowSettingsView()
                    end
                    CloseDropDownMenus()
                end
                UIDropDownMenu_AddButton(info)
                
                -- Position zurücksetzen
                info = UIDropDownMenu_CreateInfo()
                info.text = "Position zurücksetzen"
                info.notCheckable = true
                info.func = function()
                    mainFrame:ClearAllPoints()
                    mainFrame:SetPoint("CENTER")
                    if AiB.db then AiB.db.profile.settings.positions = nil end
                    print("|cFF00FF00[AiB]|r Fensterposition zurückgesetzt")
                    CloseDropDownMenus()
                end
                UIDropDownMenu_AddButton(info)
            end
            
            UIDropDownMenu_Initialize(menu, InitializeMenu, "MENU")
            ToggleDropDownMenu(1, nil, menu, "cursor", 0, 0)
        end
        
        AiBMinimapButton:SetScript("OnClick", function(self, button)
            if button == "LeftButton" then
                if mainFrame:IsShown() then
                    mainFrame:Hide()
                else
                    mainFrame:Show()
                    currentNavState = "HOME"
                    ShowHomeView()
                    
                    -- Home Button aktivieren
                    for _, b in ipairs(navButtons) do
                        AiB.Themes:ApplyToFrame(b, "tab_normal", "border_secondary")
                        b.isActive = false
                    end
                    AiB.Themes:ApplyToFrame(homeBtn, "tab_selected", "border_accent")
                    homeBtn.isActive = true
                end
                
                if AiB.Utils then
                    AiB.Utils:PlaySound(AiB.Utils.Sounds.OPEN)
                end
            elseif button == "RightButton" then
                ShowMinimapMenu(self)
            end
        end)
    end
    
    AiB.Config:Log("Main", "Initialized successfully")
    
    -- Initialize Hearthstone Toys
    if AiB.HearthstoneToys then
        AiB.HearthstoneToys:Init()
    end
    
end

local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_LOGIN")
initFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        C_Timer.After(1, function()
            Initialize()
            
            print("|cFF00FF00===========================================|r")
            print("|cFFFF0000AiB|r - All into Boss Raidtools |cFFFFFF00v" .. AiB.Config.VERSION .. "|r")
            print("Type |cFFFFFF00/aib|r to open or use the minimap button")
            print("|cFFFFFF00Theme:|r " .. AiB.Themes.List[AiB.Themes.Current].name)
            print("|cFF00FF00===========================================|r")
        end)
        
        self:UnregisterEvent("PLAYER_LOGIN")
    end
end)

-- Export für andere Module
_G.AiBMainFrame = mainFrame

-------------------------------------------
-- Portal Content Registration
-------------------------------------------
-- Portale wird jetzt als eigenständiger Container behandelt (wie Settings)
-- und nicht mehr über das AiB_Content System
-------------------------------------------
AiB_Content = AiB_Content or {}


-------------------------
-- AceDB-3.0 INITIALISIERUNG
-- Muss NACH allen anderen Definitionen laufen (aib.lua ist letzte Datei)
-------------------------

local aibInitFrame = CreateFrame("Frame")
aibInitFrame:RegisterEvent("ADDON_LOADED")
aibInitFrame:SetScript("OnEvent", function(self, event, addonName)
    if addonName ~= "aib" then return end
    self:UnregisterEvent("ADDON_LOADED")

    -- AceDB-Datenbank erstellen
    -- "true" = Standard-Profil = "Charname - Realm"
    AiB.db = LibStub("AceDB-3.0"):New("AiBDB", AiB.DB_DEFAULTS, "AiB Default")

    -- Profil-Wechsel Callbacks registrieren
    AiB.db.RegisterCallback(AiB, "OnProfileChanged", "OnProfileChanged")
    AiB.db.RegisterCallback(AiB, "OnProfileCopied",  "OnProfileChanged")
    AiB.db.RegisterCallback(AiB, "OnProfileReset",   "OnProfileChanged")

    -- =====================================================
    -- ALIASES: Alte globale Variablennamen zeigen jetzt
    -- auf die jeweiligen AceDB-Profil-Untertabellen.
    -- Dadurch müssen die Module intern NICHTS geändert werden.
    -- =====================================================
    AiB_Settings         = AiB.db.profile.settings
    AiB_CursorConfig     = AiB.db.profile.cursor
    AiB_CrosshairConfig  = AiB.db.profile.crosshair
    AiB_BreakTimerConfig = AiB.db.profile.breaktimer
    AiB_CallToArmsConfig = AiB.db.profile.calltoarms
    AiB_DontReleaseConfig= AiB.db.profile.dontrelease
    AiB_GearCheckConfig  = AiB.db.profile.gearcheck
    AiB_BuffWatcherConfig= AiB.db.profile.buffwatcher
    AiBQOL               = AiB.db.profile.qol
    AiB_CoTankConfig     = AiB.db.profile.coTank

    -- Modus (Raid/Dungeon) aus char-DB laden
    currentMode = AiB.db.char.mode or "Raid"

    -- Migrationsmeldung beim ersten Start mit 2.1.0.0
    if not AiB.db.global then AiB.db.global = {} end
    if not AiB.db.global.migratedTo210 then
        AiB.db.global.migratedTo210 = true
        C_Timer.After(5, function()
            print("|cFFFF8800[AiB]|r |cFFFFD700Update auf v2.1.0.0:|r Profil-System aktiviert!")
            print("|cFFFF8800[AiB]|r Deine Einstellungen wurden in das Profil |cFFFFD700'" ..
                  AiB.db:GetCurrentProfile() .. "'|r übertragen.")
            print("|cFFFF8800[AiB]|r Weitere Profile kannst du unter |cFFFFFF00Einstellungen → Profile|r erstellen.")
        end)
    end
end)

-- Wird aufgerufen wenn Profil gewechselt, kopiert oder resettet wird
function AiB:OnProfileChanged()
    -- Aliases auf neue Profil-Tabellen umbiegen
    AiB_Settings         = AiB.db.profile.settings
    AiB_CursorConfig     = AiB.db.profile.cursor
    AiB_CrosshairConfig  = AiB.db.profile.crosshair
    AiB_BreakTimerConfig = AiB.db.profile.breaktimer
    AiB_CallToArmsConfig = AiB.db.profile.calltoarms
    AiB_DontReleaseConfig= AiB.db.profile.dontrelease
    AiB_GearCheckConfig  = AiB.db.profile.gearcheck
    AiB_BuffWatcherConfig= AiB.db.profile.buffwatcher
    AiBQOL               = AiB.db.profile.qol
    AiB_CoTankConfig     = AiB.db.profile.coTank

    -- Module neu initialisieren
    if AiB_Cursor and AiB_Cursor.ApplySettings then
        pcall(function() AiB_Cursor:ApplySettings() end)
    end
    if AiB_Crosshair and AiB_Crosshair.UpdateVisibility then
        pcall(function() AiB_Crosshair:UpdateVisibility() end)
    end
    if AiB_BreakTimer and AiB_BreakTimer.UpdateLayout then
        pcall(function() AiB_BreakTimer:UpdateLayout() end)
    end
    if AiB.DontRelease then
        -- DontRelease liest Config live, kein Reload nötig
    end
    if AiB.BWV2 and AiB.BWV2.InitSavedVars then
        pcall(function() AiB.BWV2:InitSavedVars() end)
    end

    -- Settings-Panel neu rendern falls offen
    if AiB.Settings and AiB.Settings.currentTab then
        pcall(function() AiB.Settings:ShowTab(AiB.Settings.currentTab) end)
    end

    print("|cFFFF8800[AiB]|r Profil gewechselt zu |cFFFFD700'" ..
          AiB.db:GetCurrentProfile() .. "'|r – Einstellungen neu geladen.")
end
