-------------------------
-- AiB.lua
-------------------------
-- Überprüfen, ob WeakAuras geladen ist
if not WeakAuras then
    print("|cFFFF0000AiB Fehler:|r WeakAuras ist nicht geladen!")
    return
end

-- Schriftart für Umlaute
local FONT = "Fonts\\ARIALN.TTF"

-- Globale Variablen und Einstellungen
AiB_Content = AiB_Content or {}
AiBSavedVars = AiBSavedVars or { mode = "Raid" }

-- SavedVariable für die Auto-Accept-Funktion
AiB_Settings = AiB_Settings or {
    backgroundEnabled = true,
    roles = { tank = true, healer = false, dps = false }
}

local currentMode = AiBSavedVars.mode

-------------------------------------------
-- Tabs definieren
-------------------------------------------
local raidTabs = {
    "Raid Allgemein",
    "Vexie Fullthrottle and the The Geargrinders",
    "Cauldron of Carnage",
    "Rik Reverb",
    "Stix Bunkjunker",
    "Sprocketmonger Lockenstock",
    "One Armed Bandit",
    "MugZee",
    "Chrome King Gallywix"
}

local dungeonTabs = {
    "Dungeon Allgemein",
    "Cinderbrew Meadery",
    "Darkflame Cleft",
    "The Rookery",
    "Priory of Sacred Flame",
    "The MOTHERLODE",
    "Operation Floodgate",
    "Theater of Pain",
    "Operation Mechagon Workshop"
}

-------------------------------------------
-- Hauptfenster
-------------------------------------------
AiB = CreateFrame("Frame", "AiBFrame", UIParent, "BackdropTemplate")
AiB:SetFrameStrata("HIGH")
AiB:SetFrameLevel(99)
AiB:SetSize(1200, 900)
AiB:SetPoint("CENTER")
AiB:Hide()
AiB:SetMovable(true)
AiB:EnableMouse(true)
AiB:RegisterForDrag("LeftButton")
AiB:SetScript("OnDragStart", AiB.StartMoving)
AiB:SetScript("OnDragStop", AiB.StopMovingOrSizing)

-- Hintergrund
AiB:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 2,
    insets = { left = 2, right = 2, top = 2, bottom = 2 }
})
AiB:SetBackdropBorderColor(1, 1, 1, 1)
AiB:SetBackdropColor(0.2, 0.2, 0.2, 1)

-- Schließen
local closeButton = CreateFrame("Button", nil, AiB, "UIPanelCloseButton")
closeButton:SetSize(24, 24)
closeButton:SetPoint("TOPRIGHT", AiB, "TOPRIGHT", -5, -5)
closeButton:SetScript("OnClick", function() AiB:Hide() end)

-- Titel
local title = AiB:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
title:SetPoint("CENTER", AiB, "TOP", 0, -20)
title:SetFont(FONT, 20)
title:SetTextColor(0.6, 0, 0, 1)
title:SetText("AiB - Weakauras & Raidinfos")

-- Banner
local banner = AiB:CreateTexture(nil, "ARTWORK")
banner:SetTexture("Interface\\AddOns\\aib\\textures\\aib.tga")
banner:SetSize(1196, 175)
banner:SetPoint("TOP", AiB, "TOP", 0, -40)

-- Trennlinie
local separator = AiB:CreateTexture(nil, "ARTWORK")
separator:SetColorTexture(1, 1, 1, 1)
separator:SetSize(1140, 2)
separator:SetPoint("TOP", AiB, "TOP", 0, -175)  -- wird nachher neu platziert

local contentFrame = CreateFrame("Frame", "AiBContentFrame", AiB)
contentFrame:SetSize(1140, 175)
contentFrame:SetPoint("TOP", separator, "BOTTOM", 0, 10)

-------------------------------------------
-- Inhalt laden
-------------------------------------------
local function LoadTabContent(tabName)
    contentFrame:Hide()
    for _, child in ipairs({contentFrame:GetChildren()}) do
        child:Hide()
        child:SetParent(nil)
    end

    if AiB_Content[tabName] then
        AiB_Content[tabName](contentFrame)
        contentFrame:Show()
    else
        print("|cFFFF0000AiB-Fehler:|r Kein Inhalt für Tab '"..tabName.."' gefunden.")
    end
end

-------------------------------------------
-- Tabs dynamisch
-------------------------------------------
local createdTabs = {}

local function CreateDynamicTab(parent, text)
    local tab = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    
    local bg = tab:CreateTexture(nil, "BACKGROUND")
    bg:SetColorTexture(0.2, 0.2, 0.2, 1)
    bg:SetAllPoints(tab)
    tab:SetNormalTexture(bg)

    local icon = tab:CreateTexture(nil, "ARTWORK")
    icon:SetSize(25, 25)
    icon:SetPoint("LEFT", 3, 0)
    icon:SetTexture("Interface\\AddOns\\aib\\textures\\aib_icon.tga")
    icon:SetDrawLayer("ARTWORK", 5)
    icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)

    local tabText = tab:CreateFontString(nil, "OVERLAY")
    tabText:SetFont("Interface\\AddOns\\aib\\fonts\\Fast_Respond.otf", 19)
    tabText:SetText(text)
    tabText:SetTextColor(0.6, 0, 0, 1)
    tabText:SetPoint("LEFT", icon, "RIGHT", 3, 0)

    local textWidth = tabText:GetUnboundedStringWidth()
    tab:SetSize(math.max(textWidth + 40, 120), 28)

    tab:SetScript("OnClick", function()
        LoadTabContent(text)
    end)

    return tab
end

local function CreateTabs()
    for _, tab in ipairs(createdTabs) do
        tab:Hide()
        tab:SetParent(nil)
    end
    wipe(createdTabs)

    local tabs = (currentMode == "Raid") and raidTabs or dungeonTabs

    local tabSpacing = 2
    local startY = -210
    local maxRowWidth = 1140
    local currentY = startY
    local rowTabs = {}
    local rowWidth = 0

    for _, tabName in ipairs(tabs) do
        local tab = CreateDynamicTab(AiB, tabName)
        local tabWidth = tab:GetWidth()

        if (rowWidth + tabWidth + tabSpacing) > maxRowWidth then
            local startX = (1200 - rowWidth) / 2
            for _, t in ipairs(rowTabs) do
                t:ClearAllPoints()
                t:SetPoint("TOPLEFT", AiB, "TOPLEFT", startX, currentY)
                startX = startX + t:GetWidth() + tabSpacing
            end
            rowTabs = {}
            rowWidth = 0
            currentY = currentY - 35
        end

        table.insert(rowTabs, tab)
        table.insert(createdTabs, tab)
        rowWidth = rowWidth + tabWidth + tabSpacing
    end

    if #rowTabs > 0 then
        local startX = (1200 - rowWidth) / 2
        for _, t in ipairs(rowTabs) do
            t:ClearAllPoints()
            t:SetPoint("TOPLEFT", AiB, "TOPLEFT", startX, currentY)
            startX = startX + t:GetWidth() + tabSpacing
        end
        currentY = currentY - 35
    end

    separator:ClearAllPoints()
    separator:SetPoint("TOP", AiB, "TOP", 0, currentY)
end

-------------------------------
-- Modus-Switch
-------------------------------
local modeSwitch = CreateFrame("Frame", nil, AiB, "BackdropTemplate")
modeSwitch:SetSize(120, 28)
modeSwitch:SetPoint("TOPRIGHT", closeButton, "TOPLEFT", -15, 0)
modeSwitch:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 2,
    insets = { left = 2, right = 2, top = 2, bottom = 2 }
})
modeSwitch:SetBackdropColor(0.2, 0.2, 0.2, 1)
modeSwitch:SetBackdropBorderColor(1, 1, 1, 1)

local switchCircle = modeSwitch:CreateTexture(nil, "OVERLAY")
switchCircle:SetSize(20, 20)
switchCircle:SetColorTexture(0.9, 0, 0)
switchCircle:SetPoint("LEFT", 5, 0)

local switchText = modeSwitch:CreateFontString(nil, "OVERLAY")
switchText:SetFont(FONT, 14)
switchText:SetTextColor(0.6, 0, 0, 1)
switchText:SetPoint("CENTER")
switchText:SetText("Raid")

modeSwitch:SetScript("OnMouseDown", function()
    currentMode = (currentMode == "Raid") and "Dungeon" or "Raid"
    AiBSavedVars.mode = currentMode

    switchCircle:ClearAllPoints()
    if currentMode == "Dungeon" then
        switchCircle:SetPoint("RIGHT", modeSwitch, "RIGHT", -5, 0)
        switchCircle:SetColorTexture(0, 0.5, 0)
        switchText:SetText("M+")
    else
        switchCircle:SetPoint("LEFT", modeSwitch, "LEFT", 5, 0)
        switchCircle:SetColorTexture(0.9, 0, 0)
        switchText:SetText("Raid")
    end
    
    CreateTabs()
    if currentMode == "Raid" then
        if AiB_Content["RaidStart"] then
            LoadTabContent("RaidStart")
        end
    else
        if AiB_Content["DungeonStart"] then
            LoadTabContent("DungeonStart")
        end
    end
end)

-------------------------------------------
-- Zahnrad-Button (Settings-Popup)
-------------------------------------------
local gearButton = CreateFrame("Button", nil, AiB, "BackdropTemplate")
gearButton:SetSize(28, 28)
gearButton:SetPoint("TOPRIGHT", modeSwitch, "TOPLEFT", -15, 0)
gearButton:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = nil,
    edgeSize = 0,
    insets = { left = 2, right = 2, top = 2, bottom = 2 }
})
gearButton:SetBackdropColor(0.2, 0.2, 0.2, 1)

local gearIcon = gearButton:CreateTexture(nil, "ARTWORK")
gearIcon:SetTexture("Interface\\AddOns\\aib\\textures\\gear.tga")
gearIcon:SetAllPoints(gearButton)

local settingsPopup
gearButton:SetScript("OnClick", function()
    if not settingsPopup then
        settingsPopup = CreateFrame("Frame", "AiB_SettingsPopup", AiB, "BackdropTemplate")
        settingsPopup:SetSize(300, 200)
        settingsPopup:SetPoint("TOPLEFT", AiB, "TOPRIGHT", 0, 0)
        settingsPopup:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Buttons\\WHITE8x8",
            edgeSize = 2,
            insets = { left = 2, right = 2, top = 2, bottom = 2 }
        })
        settingsPopup:SetBackdropBorderColor(1, 1, 1, 1)
        settingsPopup:SetBackdropColor(0.2, 0.2, 0.2, 1)
        settingsPopup:EnableMouse(true)
        settingsPopup:SetMovable(true)
        settingsPopup:RegisterForDrag("LeftButton")
        settingsPopup:SetScript("OnDragStart", function(self) self:StartMoving() end)
        settingsPopup:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)

        local popupTitle = settingsPopup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        popupTitle:SetPoint("TOP", settingsPopup, "TOP", 0, -16)
        popupTitle:SetText("AiB Einstellungen")
        popupTitle:SetTextColor(0.6, 0, 0, 1)

        local bgFuncCheckbox = CreateFrame("CheckButton", "$parent_BGFuncCheckbox", settingsPopup, "UICheckButtonTemplate")
        bgFuncCheckbox:SetPoint("TOPLEFT", settingsPopup, "TOPLEFT", 20, -50)
        bgFuncCheckbox.text = bgFuncCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        bgFuncCheckbox.text:SetPoint("LEFT", bgFuncCheckbox, "RIGHT", 5, 0)
        bgFuncCheckbox.text:SetText("Auto-Accept Role Check aktivieren")
        bgFuncCheckbox.text:SetTextColor(1, 1, 1, 1)
        bgFuncCheckbox:SetChecked(AiB_Settings.backgroundEnabled)
        bgFuncCheckbox:SetScript("OnClick", function(self)
            AiB_Settings.backgroundEnabled = self:GetChecked()
        end)

        local roles = {"Tank", "Heiler", "DPS"}
        for i, role in ipairs(roles) do
            local roleCheckbox = CreateFrame("CheckButton", "$parent_RoleCheckbox_"..role, settingsPopup, "UICheckButtonTemplate")
            roleCheckbox:SetPoint("TOPLEFT", settingsPopup, "TOPLEFT", 20, -90 - (i - 1) * 30)
            roleCheckbox.text = roleCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            roleCheckbox.text:SetPoint("LEFT", roleCheckbox, "RIGHT", 5, 0)
            roleCheckbox.text:SetText(role)
            roleCheckbox.text:SetTextColor(1, 1, 1, 1)

            local key = (role == "Tank" and "tank") or (role == "Heiler" and "healer") or "dps"
            roleCheckbox:SetChecked(AiB_Settings.roles[key])
            roleCheckbox:SetScript("OnClick", function(self)
                AiB_Settings.roles[key] = self:GetChecked()
            end)
        end

        local closePopup = CreateFrame("Button", nil, settingsPopup, "UIPanelButtonTemplate")
        closePopup:SetSize(80, 25)
        closePopup:GetFontString():SetTextColor(1, 1, 1)
        closePopup:SetPoint("BOTTOM", settingsPopup, "BOTTOM", 0, 15)
        closePopup:SetText("Schließen")
        closePopup:SetScript("OnClick", function() settingsPopup:Hide() end)
    end

    if settingsPopup:IsShown() then
        settingsPopup:Hide()
    else
        settingsPopup:Show()
    end
end)

-------------------------------------------
-- Slash Command
-------------------------------------------
SLASH_AiB1 = "/aib"
SlashCmdList["AiB"] = function()
    AiB:SetShown(not AiB:IsShown())
    if AiB:IsShown() then
        CreateTabs()
    end
end

-------------------------------------------
-- Initialisierung
-------------------------------------------
CreateTabs()

-------------------------------------------
-- Auto-Accept Role Check
-------------------------------------------
local function AutoAcceptRoleCheck()
    local tank, dps, healer = false, false, false

    local posTank, posHealer, posDps = UnitGetAvailableRoles("player")
    if posDps then dps = AiB_Settings.roles.dps end
    if posTank then tank = AiB_Settings.roles.tank end
    if posHealer then healer = AiB_Settings.roles.healer end

    if not (tank or healer or dps) then
        local role = UnitGroupRolesAssigned("player")
        if role == "NONE" and GetSpecialization() then
            role = GetSpecializationRole(GetSpecialization())
        end
        if role == "TANK" then
            tank = true
        elseif role == "DAMAGER" then
            dps = true
        elseif role == "HEALER" then
            healer = true
        end
    end

    if LFDRoleCheckPopupRoleButtonTank
       and LFDRoleCheckPopupRoleButtonTank.checkButton
       and LFDRoleCheckPopupRoleButtonTank.checkButton:IsEnabled() then
        LFDRoleCheckPopupRoleButtonTank.checkButton:SetChecked(tank)
    end
    if LFDRoleCheckPopupRoleButtonHealer
       and LFDRoleCheckPopupRoleButtonHealer.checkButton
       and LFDRoleCheckPopupRoleButtonHealer.checkButton:IsEnabled() then
        LFDRoleCheckPopupRoleButtonHealer.checkButton:SetChecked(healer)
    end
    if LFDRoleCheckPopupRoleButtonDPS
       and LFDRoleCheckPopupRoleButtonDPS.checkButton
       and LFDRoleCheckPopupRoleButtonDPS.checkButton:IsEnabled() then
        LFDRoleCheckPopupRoleButtonDPS.checkButton:SetChecked(dps)
    end

    if LFDRoleCheckPopupAcceptButton then
        LFDRoleCheckPopupAcceptButton:Enable()
        LFDRoleCheckPopupAcceptButton:Click()
    end
end

local roleCheckFrame = CreateFrame("Frame")
roleCheckFrame:RegisterEvent("LFG_ROLE_CHECK_SHOW")
roleCheckFrame:SetScript("OnEvent", function(self, event)
    if event == "LFG_ROLE_CHECK_SHOW" and AiB_Settings.backgroundEnabled then
        AutoAcceptRoleCheck()
    end
end)

---------------------------------------------
-- Copyright-Text in der linken unteren Ecke
---------------------------------------------
local copyrightText = AiB:CreateFontString(nil, "OVERLAY")
copyrightText:SetFont(FONT, 10, "OUTLINE")
copyrightText:SetText("© Rinova")
copyrightText:SetTextColor(1, 1, 1, 1) -- Weiß
copyrightText:SetPoint("BOTTOMLEFT", AiB, "BOTTOMLEFT", 10, 10)

print("|cFF00FF00AiB|r geladen! Mit /aib öffnen.")
