-- Datei: core\portals\AiB_Portals.lua
-- Achte darauf, dass dein "aib.lua" in der TOC zuerst geladen wird!

----------------------------
-- 1) Fraktionsabhängige Spells
----------------------------
local factionGroup = UnitFactionGroup("player")

-- Siege Dungeon ID
local siegeID
if factionGroup == "Horde" then
    siegeID = 464256
else
    siegeID = 445418
end

-- Motherlode Dungeon ID
local motherID
if factionGroup == "Horde" then
    motherID = 467555
else
    motherID = 467553
end

----------------------------
-- 2) Season 2 (zusammengefasst)
----------------------------
MDT_PL_Season2 = {
    {icon = "Interface\\Icons\\inv_achievement_dungeon_cinderbrewmeadery",  spellID = 445440, name = "CM"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_darkflamecleft",     spellID = 445441, name = "DFC"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_prioryofthesacredflame", spellID = 445444, name = "PSF"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_rookery",            spellID = 445443, name = "ROOK"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_waterworks",         spellID = 1216786, name = "FLOOD"},
    {icon = "Interface\\Icons\\achievement_dungeon_kezan",                  spellID = motherID, name = "ML"},
    {icon = "Interface\\Icons\\achievement_dungeon_theatreofpain",          spellID = 354467,   name = "TOP"},
    {icon = "Interface\\Icons\\achievement_boss_mechagon",                  spellID = 373274,   name = "WORK"},
}

----------------------------
-- 3) Größere Portal-Tabellen
----------------------------
-- The War Within
MDT_PL_TWW = {
    {icon = "Interface\\Icons\\inv_achievement_dungeon_arak-ara",          spellID = 445417, name = "ARAK"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_cinderbrewmeadery", spellID = 445440, name = "CM"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_cityofthreads",     spellID = 445416, name = "COT"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_darkflamecleft",    spellID = 445441, name = "DFC"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_dawnbreaker",       spellID = 445414, name = "DAWN"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_waterworks",        spellID = 1216786, name = "FLOOD"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_prioryofthesacredflame", spellID = 445444, name = "PSF"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_rookery",           spellID = 445443, name = "ROOK"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_stonevault",        spellID = 445269,  name = "SV"},
}

-- Dragonflight
MDT_PL_DF = {
    {icon = "Interface\\Icons\\achievement_dungeon_dragonacademy",         spellID = 393273, name = "AA"},
    {icon = "Interface\\Icons\\achievement_dungeon_arcanevaults",          spellID = 393279, name = "AV"},
    {icon = "Interface\\Icons\\achievement_dungeon_brackenhidehollow",     spellID = 393267, name = "BH"},
    {icon = "Interface\\Icons\\achievement_dungeon_hallsofinfusion",       spellID = 393283, name = "HOI"},
    {icon = "Interface\\Icons\\achievement_dungeon_neltharus",             spellID = 393276, name = "NELTH"},
    {icon = "Interface\\Icons\\achievement_dungeon_centaurplains",         spellID = 393262, name = "NO"},
    {icon = "Interface\\Icons\\achievement_dungeon_lifepools",             spellID = 393256, name = "RLP"},
    {icon = "Interface\\Icons\\achievement_dungeon_uldaman",               spellID = 393222, name = "ULD"},
    {icon = "Interface\\Icons\\achievement_dungeon_dawnoftheinfinite",     spellID = 424197, name = "DOTI"},
}

-- Shadowlands
MDT_PL_SL = {
    {icon = "Interface\\Icons\\achievement_dungeon_theotherside",          spellID = 354468, name = "DOS"},
    {icon = "Interface\\Icons\\achievement_dungeon_hallsofattonement",     spellID = 354465, name = "HOA"},
    {icon = "Interface\\Icons\\achievement_dungeon_mistsoftirnascithe",    spellID = 354464, name = "MISTS"},
    {icon = "Interface\\Icons\\achievement_dungeon_theneroticwake",        spellID = 354462, name = "NW"},
    {icon = "Interface\\Icons\\achievement_dungeon_plaguefall",            spellID = 354463, name = "PF"},
    {icon = "Interface\\Icons\\achievement_dungeon_sanguinedepths",        spellID = 354469, name = "SD"},
    {icon = "Interface\\Icons\\achievement_dungeon_spireofascension",      spellID = 354466, name = "SOA"},
    {icon = "Interface\\Icons\\achievement_dungeon_theatreofpain",         spellID = 354467, name = "TOP"},
    {icon = "Interface\\Icons\\achievement_dungeon_brokerdungeon",         spellID = 367416, name = "TAZ"},
}

-- Battle for Azeroth
MDT_PL_BFA = {
    {icon = "Interface\\Icons\\achievement_dungeon_ataldazar",             spellID = 424187, name = "AD"},
    {icon = "Interface\\Icons\\achievement_dungeon_freehold",              spellID = 410071, name = "FH"},
    {icon = "Interface\\Icons\\achievement_boss_mechagon",                 spellID = 373274, name = "MECHA"},
    {icon = "Interface\\Icons\\achievement_dungeon_kezan",                 spellID = motherID, name = "ML"},
    {icon = "Interface\\Icons\\achievement_dungeon_siegeofboralus",        spellID = siegeID,  name = "SIEGE"},
    {icon = "Interface\\Icons\\achievement_dungeon_underrot",              spellID = 410074,   name = "UNDR"},
    {icon = "Interface\\Icons\\achievement_dungeon_waycrestmannor",        spellID = 424167,   name = "WM"},
}

-- Legion
MDT_PL_Legion = {
    {icon = "Interface\\Icons\\achievement_dungeon_blackrookhold",         spellID = 424153, name = "BRH"},
    {icon = "Interface\\Icons\\achievement_dungeon_courtofstars",          spellID = 393766, name = "COS"},
    {icon = "Interface\\Icons\\achievement_dungeon_darkheartthicket",      spellID = 424163, name = "DT"},
    {icon = "Interface\\Icons\\achievement_dungeon_hallsofvalor",          spellID = 393764, name = "HOV"},
    {icon = "Interface\\Icons\\achievement_raid_karazhan",                 spellID = 373262, name = "KARA"},
    {icon = "Interface\\Icons\\achievement_dungeon_neltharionslair",       spellID = 410078, name = "NL"},
}

-- Warlords of Draenor
MDT_PL_WOD = {
    {icon = "Interface\\Icons\\achievement_dungeon_auchindoun",           spellID = 159897, name = "AUCH"},
    {icon = "Interface\\Icons\\achievement_dungeon_ogreslagmines",        spellID = 159895, name = "BSM"},
    {icon = "Interface\\Icons\\achievement_dungeon_everbloom",            spellID = 159901, name = "EB"},
    {icon = "Interface\\Icons\\achievement_dungeon_blackrockdepot",       spellID = 159900, name = "GD"},
    {icon = "Interface\\Icons\\achievement_boss_ironjuggernaut",          spellID = 159896, name = "ID"},
    {icon = "Interface\\Icons\\achievement_dungeon_shadowmoonhideout",    spellID = 159899, name = "SBG"},
    {icon = "Interface\\Icons\\achievement_dungeon_arakkoaspires",        spellID = 159898, name = "SR"},
    {icon = "Interface\\Icons\\achievement_dungeon_upperblackrockspire",  spellID = 159902, name = "UBRS"},
}

-- Mists of Pandaria
MDT_PL_MOP = {
    {icon = "Interface\\Icons\\achievement_greatwall",                    spellID = 131225, name = "GOTSS"},
    {icon = "Interface\\Icons\\achievement_dungeon_mogupalace",           spellID = 131222, name = "MSP"},
    {icon = "Interface\\Icons\\spell_holy_senseundead",                   spellID = 131232, name = "SCHOLO"},
    {icon = "Interface\\Icons\\inv_helmet_52",                            spellID = 131231, name = "SH"},
    {icon = "Interface\\Icons\\spell_holy_resurrection",                  spellID = 131229, name = "SM"},
    {icon = "Interface\\Icons\\achievement_dungeon_siegeofniuzaotemple",  spellID = 131228, name = "SNT"},
    {icon = "Interface\\Icons\\achievement_shadowpan_hideout",            spellID = 131206, name = "SPM"},
    {icon = "Interface\\Icons\\achievement_brewery",                      spellID = 131205, name = "SSB"},
    {icon = "Interface\\Icons\\achievement_jadeserpent",                  spellID = 131204, name = "TJS"},
}

-- Cataclysm
MDT_PL_CATA = {
    {icon = "Interface\\Icons\\achievement_dungeon_grimbatol",            spellID = 445424, name = "GB"},
    {icon = "Interface\\Icons\\achievement_dungeon_throne of the tides",  spellID = 424142, name = "TOTT"},
    {icon = "Interface\\Icons\\achievement_dungeon_skywall",              spellID = 410080, name = "VP"},
}

------------------------------------------------------------------------
-- 3) Cooldown-Funktionen (C_Spell-API)
------------------------------------------------------------------------
local function FormatCooldownTime(seconds)
    if seconds >= 3600 then
        return string.format("%dh", math.floor(seconds / 3600))
    elseif seconds >= 60 then
        return string.format("%dm", math.floor(seconds / 60))
    else
        return string.format("%ds", math.floor(seconds))
    end
end

local function AddCooldownOverlay(button, spellID, iconTexture, portalName)
    if not button.cooldownText then
        local cdText = button:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        cdText:SetPoint("CENTER", button, "CENTER", 0, 0)
        cdText:SetTextColor(1, 1, 1)
        cdText:SetShadowOffset(1, -1)
        cdText:Hide()
        button.cooldownText = cdText
    end

    if not button.cooldownOverlay then
        local overlay = button:CreateTexture(nil, "OVERLAY")
        overlay:SetAllPoints(true)
        overlay:SetColorTexture(0, 0, 0, 0.4) -- leichte Verdunkelung
        overlay:Hide()
        button.cooldownOverlay = overlay
    end

    button:SetScript("OnUpdate", function(self, elapsed)
        local info = C_Spell.GetSpellCooldown(spellID)
        if not info then
            self.cooldownText:SetText("")
            self.cooldownOverlay:Hide()
            return
        end

        local startTime = info.startTime
        local duration  = info.duration
        local isEnabled = info.isEnabled

        if startTime > 0 and duration > 0 and isEnabled then
            local remaining = math.max(0, (startTime + duration) - GetTime())
            if remaining > 0 then
                self.cooldownText:SetText(FormatCooldownTime(remaining))
                self.cooldownText:Show()
                self.cooldownOverlay:Show()

                if GameTooltip:IsOwned(self) then
                    GameTooltip:ClearLines()
                    GameTooltip:AddLine(portalName, 1, 1, 1)
                    GameTooltip:AddLine("Noch " .. FormatCooldownTime(remaining), 0.8, 0.8, 0.8)
                    GameTooltip:Show()
                end
                return
            end
        end

        self.cooldownText:SetText("")
        self.cooldownText:Hide()
        self.cooldownOverlay:Hide()
    end)
end

------------------------------------------------------------------------
-- 4) Button am AiB-Fenster ("Portal-Popup")
------------------------------------------------------------------------
local portalButtonLeft = CreateFrame("Button", nil, AiB, "BackdropTemplate")
portalButtonLeft:SetSize(28, 28)
portalButtonLeft:SetPoint("TOPLEFT", AiB, "TOPLEFT", 5, -5)
portalButtonLeft:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = nil,
    edgeSize = 0,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
})
portalButtonLeft:SetBackdropColor(0.2, 0.2, 0.2, 1)

local portalIconLeft = portalButtonLeft:CreateTexture(nil, "ARTWORK")
portalIconLeft:SetTexture("Interface\\AddOns\\aib\\textures\\aib_icon.tga")
portalIconLeft:SetAllPoints(portalButtonLeft)

-- Popup-Frame (erstellt bei erstem Klick)
local portalPopup
portalButtonLeft:SetScript("OnClick", function()
    if not portalPopup then
        portalPopup = CreateFrame("Frame", "AiB_PortalLibraryPopup", AiB, "BackdropTemplate")
        portalPopup:SetSize(385, 840)
        portalPopup:SetPoint("TOPRIGHT", AiB, "TOPLEFT", 0, 0)

        portalPopup:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Buttons\\WHITE8x8",
            edgeSize = 2,
            insets = { left = 2, right = 2, top = 2, bottom = 2 },
        })
        portalPopup:SetBackdropBorderColor(1, 1, 1, 1)
        portalPopup:SetBackdropColor(0.2, 0.2, 0.2, 1)
        portalPopup:EnableMouse(true)
        portalPopup:SetMovable(true)
        portalPopup:RegisterForDrag("LeftButton")
        portalPopup:SetScript("OnDragStart", function(self) self:StartMoving() end)
        portalPopup:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)

        local popupTitle = portalPopup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        popupTitle:SetPoint("TOP", portalPopup, "TOP", 0, -10)
        popupTitle:SetText("Portal Library")
        popupTitle:SetTextColor(0.6, 0, 0, 1)

        local scrollFrame = CreateFrame("ScrollFrame", "$parent_ScrollFrame", portalPopup)
        scrollFrame:SetSize(portalPopup:GetWidth() - 30, portalPopup:GetHeight() - 50)
        scrollFrame:SetPoint("TOPLEFT", portalPopup, "TOPLEFT", 10, -40)

        local scrollChild = CreateFrame("Frame", "$parent_ScrollChild", scrollFrame)
        scrollChild:SetSize(scrollFrame:GetWidth(), 840)
        scrollFrame:SetScrollChild(scrollChild)

        local expansionsData = {
            { expansion="Season 2",         portals=MDT_PL_Season2 },
            { expansion="The War Within",   portals=MDT_PL_TWW },
            { expansion="Dragonflight",     portals=MDT_PL_DF },
            { expansion="Shadowlands",      portals=MDT_PL_SL },
            { expansion="Battle for Azeroth", portals=MDT_PL_BFA },
            { expansion="Legion",           portals=MDT_PL_Legion },
            { expansion="Warlords of Draenor", portals=MDT_PL_WOD },
            { expansion="Mists of Pandaria", portals=MDT_PL_MOP },
            { expansion="Cataclysm",        portals=MDT_PL_CATA },
        }

        local buttonSize = 30
        local buttonSpacing = 10
        local columns = 9
        local xPos = 0
        local yPos = 5

        for _, expData in ipairs(expansionsData) do
            local expTitle = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            expTitle:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", 0, -yPos)
            expTitle:SetText(expData.expansion)
            expTitle:SetTextColor(0.2, 0.8, 0.9)
            expTitle:SetFont("Fonts\\FRIZQT__.TTF", 14, "OUTLINE")

            yPos = yPos + 20
            xPos = 0

            for i, portal in ipairs(expData.portals) do
                local known = IsSpellKnown(portal.spellID)

                local btn = CreateFrame("Button", nil, scrollChild, "SecureActionButtonTemplate")
                btn:SetSize(buttonSize, buttonSize)
                btn:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", xPos, -yPos)

                local icon = btn:CreateTexture(nil, "ARTWORK")
                icon:SetAllPoints(true)

                local hoverOverlay = btn:CreateTexture(nil, "HIGHLIGHT")
                hoverOverlay:SetAllPoints(btn)
                hoverOverlay:SetTexture("Interface\\AddOns\\aib\\textures\\aib_button_highlight.blp")
                hoverOverlay:SetBlendMode("ADD")
                hoverOverlay:SetVertexColor(1, 1, 1, 0.25)

                if known then
                    icon:SetTexture(portal.icon or 134400)
                    btn:SetAttribute("type", "spell")
                    btn:SetAttribute("spell", portal.spellID)
                    btn:SetScript("OnEnter", function(self)
                        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                        GameTooltip:AddLine(portal.name, 1,1,1)
                        GameTooltip:Show()
                    end)
                    btn:SetScript("OnLeave", function(self)
                        GameTooltip:Hide()
                    end)
                    AddCooldownOverlay(btn, portal.spellID, icon, portal.name)
                else
                    icon:SetTexture("Interface\\AddOns\\aib\\textures\\aib_lock.blp")
                    icon:SetDesaturated(false)
                    icon:SetVertexColor(1, 1, 1, 0.8)

                    btn:SetAttribute("type", nil)
                    btn:RegisterForClicks()
                    btn:SetScript("OnEnter", function(self)
                        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                        GameTooltip:AddLine(portal.name, 1,1,1)
                        GameTooltip:AddLine("Portal not learned yet.", 1,0,0)
                        GameTooltip:Show()
                    end)
                    btn:SetScript("OnLeave", function(self)
                        GameTooltip:Hide()
                    end)
                end

                local label = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
                label:SetPoint("TOP", btn, "BOTTOM", 0, -2)
                label:SetText(portal.name)
                label:SetTextColor(1, 1, 1, 1)

                xPos = xPos + buttonSize + buttonSpacing
                if ((i % columns) == 0) then
                    xPos = 0
                    yPos = yPos + buttonSize + 25
                end
            end

            if xPos ~= 0 then
                yPos = yPos + buttonSize + 25
            end
            yPos = yPos + 15
            xPos = 0
        end

        local closeBtn = CreateFrame("Button", nil, portalPopup, "UIPanelCloseButton")
        closeBtn:SetSize(24, 24)
        closeBtn:SetPoint("TOPRIGHT", portalPopup, "TOPRIGHT", -5, -5)
        closeBtn:SetScript("OnClick", function() portalPopup:Hide() end)
    end

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

------------------------------------------------------------------------
-- 5) Zusatzframe (Season-Portale + Hearthstone) oberhalb von PvEFrame
------------------------------------------------------------------------

local seasonFrame = CreateFrame("Frame", "AiB_SeasonPortalsFrame", UIParent, "BackdropTemplate")
seasonFrame:ClearAllPoints()
seasonFrame:SetPoint("BOTTOMLEFT", PVEFrame, "TOPLEFT", 0, 0)
seasonFrame:SetPoint("BOTTOMRIGHT", PVEFrame, "TOPRIGHT", 0, 0)
seasonFrame:SetHeight(90)

seasonFrame:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 1,
    insets = { left = 1, right = 1, top = 1, bottom = 1 },
})
seasonFrame:SetBackdropBorderColor(0, 0, 0, 1)
seasonFrame:SetBackdropColor(0, 0, 0, 0.6)

-- Überschrift
local titleText = seasonFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
titleText:SetPoint("TOP", seasonFrame, "TOP", 0, -5)
titleText:SetText("M+ Teleports - The War Within S2")
titleText:SetTextColor(1, 0.8, 0, 1)
titleText:SetFont("Fonts\\FRIZQT__.TTF", 12, "OUTLINE")

seasonFrame.portalButtons = {}

local buttonSize = 30
local spacing = 25
local numPortals = #MDT_PL_Season2
-- plus 1 extra for the hearthstone:
local totalButtons = numPortals + 1
local totalWidth = (totalButtons * (buttonSize + spacing)) - spacing

-- 1) Season-Portale
for i, portal in ipairs(MDT_PL_Season2) do
    local btn = CreateFrame("Button", nil, seasonFrame, "SecureActionButtonTemplate")
    btn:SetSize(buttonSize, buttonSize)

    local xOffset = -totalWidth/2 + (i-1)*(buttonSize + spacing)
    btn:SetPoint("TOP", seasonFrame, "TOP", xOffset, -35)

    btn.portalData = portal
    btn.icon = btn:CreateTexture(nil, "ARTWORK")
    btn.icon:SetAllPoints(true)

    local label = btn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    label:SetPoint("TOP", btn, "BOTTOM", 0, -2)
    label:SetText(portal.name)
    label:SetTextColor(1, 1, 1, 1)

    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:AddLine(self.portalData.name, 1, 1, 1)
        GameTooltip:Show()
    end)
    btn:SetScript("OnLeave", function() GameTooltip:Hide() end)

    table.insert(seasonFrame.portalButtons, btn)
end

-- 2) Hearthstone-Button (mit CD-Overlay)
do
    local hearthBtn = CreateFrame("Button", nil, seasonFrame, "SecureActionButtonTemplate")
    hearthBtn:SetSize(buttonSize, buttonSize)

    local xOffset = -totalWidth/2 + (numPortals)*(buttonSize + spacing)
    hearthBtn:SetPoint("TOP", seasonFrame, "TOP", xOffset, -35)

    local hsIcon = hearthBtn:CreateTexture(nil, "ARTWORK")
    hsIcon:SetAllPoints(true)
    hsIcon:SetTexture("Interface\\Icons\\INV_Misc_Rune_01")

    hearthBtn:SetAttribute("type", "item")
    hearthBtn:SetAttribute("item", "Hearthstone")

    hearthBtn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:AddLine("Hearthstone", 1, 1, 1)
        GameTooltip:Show()
    end)
    hearthBtn:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)

    -- Fügt denselben Cooldown-Overlay für Hearthstone (SpellID=8690)
    AddCooldownOverlay(hearthBtn, 8690, hsIcon, "Hearthstone")

    table.insert(seasonFrame.portalButtons, hearthBtn)
end

-- Update-Funktion (wenn PvEFrame aufgeht -> abfragen, ob Portale bekannt)
local function UpdateSeasonButtons()
    for _, btn in ipairs(seasonFrame.portalButtons) do
        local pData = btn.portalData
        if pData then
            local known = IsSpellKnown(pData.spellID)
            if known then
                btn.icon:SetTexture(pData.icon or 134400)
                btn:SetAttribute("type", "spell")
                btn:SetAttribute("spell", pData.spellID)
                AddCooldownOverlay(btn, pData.spellID, btn.icon, pData.name)
            else
                btn.icon:SetTexture("Interface\\AddOns\\aib\\textures\\aib_lock.blp")
                btn.icon:SetVertexColor(1, 1, 1, 0.8)
                btn:SetAttribute("type", nil)
                btn:RegisterForClicks()
            end
        end
    end
end

seasonFrame:Hide()
PVEFrame:HookScript("OnShow", function()
    seasonFrame:Show()
    UpdateSeasonButtons()
end)

PVEFrame:HookScript("OnHide", function()
    seasonFrame:Hide()
end)
