------------------------------------------------------------------------
-- Season Portals Frame (über PVEFrame/LFG-Tool)
-- Zeigt Season 1 Portale + Hearthstone wenn PVEFrame offen ist
------------------------------------------------------------------------

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 - Midnight S1")
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_Season1 and #MDT_PL_Season1 or 0
-- plus 1 extra for the hearthstone:
local totalButtons = numPortals + 1
local totalWidth = (totalButtons * (buttonSize + spacing)) - spacing

-- 1) Season 1 Portale
if MDT_PL_Season1 then
    for i, portal in ipairs(MDT_PL_Season1) 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
end -- Ende if MDT_PL_Season1

-- 2) Hearthstone-Button (mit CD-Overlay & Toy-Auswahl)
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.icon = hsIcon

    -- Aktiviere den Button explizit
    hearthBtn:Enable()
    hearthBtn:RegisterForClicks("LeftButtonUp", "LeftButtonDown", "RightButtonUp")
    
    -- Toy-Name für Tooltip
    hearthBtn.toyName = "Hearthstone"
    
    -- Initial Setup (wird von HearthstoneToys überschrieben)
    hearthBtn:SetAttribute("type", "item")
    C_Timer.After(0.5, function()
        local itemName = GetItemInfo(6948)
        if itemName then
            hearthBtn:SetAttribute("item", itemName)
        end
    end)

    hearthBtn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:AddLine(self.toyName or "Hearthstone", 1, 1, 1)
        GameTooltip:AddLine("Links-Klick: Benutzen", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Rechts-Klick: Toy auswählen", 0.8, 0.8, 0.8)
        GameTooltip:Show()
    end)
    hearthBtn:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
    
    -- Registriere Button beim Toy-System
    if AiB.HearthstoneToys then
        AiB.HearthstoneToys:RegisterButton(hearthBtn)
    end
    
    -- Update Button wenn Season Frame geöffnet wird
    seasonFrame:HookScript("OnShow", function()
        if AiB.HearthstoneToys and AiB.HearthstoneToys.button then
            C_Timer.After(0.1, function()
                AiB.HearthstoneToys:UpdateButton()
            end)
        end
    end)

    -- Cooldown-Overlay für Hearthstone (SpellID=8690)
    local function AddHearthstoneCooldown(button, spellID)
        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)
            overlay:Hide()
            button.cooldownOverlay = overlay
        end

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

            local start = info.startTime or 0
            local duration = info.duration or 0

            if duration > 0 then
                local remaining = duration - (GetTime() - start)
                if remaining > 0 then
                    self.cooldownOverlay:Show()
                    if remaining >= 3600 then
                        self.cooldownText:SetText(string.format("%dh", math.floor(remaining / 3600)))
                    elseif remaining >= 60 then
                        self.cooldownText:SetText(string.format("%dm", math.floor(remaining / 60)))
                    else
                        self.cooldownText:SetText(string.format("%ds", math.floor(remaining)))
                    end
                    self.cooldownText:Show()
                else
                    self.cooldownOverlay:Hide()
                    self.cooldownText:Hide()
                end
            else
                self.cooldownOverlay:Hide()
                self.cooldownText:Hide()
            end
        end)
    end
    
    AddHearthstoneCooldown(hearthBtn, 8690)

    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)
            
            -- PVE Frame zeigt IMMER alle Portale (unabhängig von hide_unlearned_portals!)
            btn:Show()
            
            if known then
                -- Hole Icon vom Spell (dynamisch)
                local spellTexture = C_Spell.GetSpellTexture(pData.spellID)
                btn.icon:SetTexture(spellTexture or pData.icon or 134400)
                btn:Enable()
                btn:RegisterForClicks("LeftButtonUp", "LeftButtonDown")
                btn:SetAttribute("type", "spell")
                btn:SetAttribute("unit", "player")
                btn:SetAttribute("spell", pData.spellID)
                
                -- Cooldown-Overlay
                local function AddCooldownOverlay(button, spellID)
                    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)
                        overlay:Hide()
                        button.cooldownOverlay = overlay
                    end

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

                        local start = info.startTime or 0
                        local duration = info.duration or 0

                        if duration > 0 then
                            local remaining = duration - (GetTime() - start)
                            if remaining > 0 then
                                self.cooldownOverlay:Show()
                                if remaining >= 3600 then
                                    self.cooldownText:SetText(string.format("%dh", math.floor(remaining / 3600)))
                                elseif remaining >= 60 then
                                    self.cooldownText:SetText(string.format("%dm", math.floor(remaining / 60)))
                                else
                                    self.cooldownText:SetText(string.format("%ds", math.floor(remaining)))
                                end
                                self.cooldownText:Show()
                            else
                                self.cooldownOverlay:Hide()
                                self.cooldownText:Hide()
                            end
                        else
                            self.cooldownOverlay:Hide()
                            self.cooldownText:Hide()
                        end
                    end)
                end
                
                AddCooldownOverlay(btn, pData.spellID)
            else
                -- Nicht bekannt - Zeige Lock-Icon
                btn.icon:SetTexture("Interface\\AddOns\\aib\\textures\\aib_lock.blp")
                btn.icon:SetVertexColor(1, 1, 1, 0.8)
                btn:Disable()
            end
        end
    end
end

seasonFrame:Hide()
-- FIX: PVEFrame wird via ShowUIPanel (secure code) geöffnet.
-- Show()/Hide() direkt im Hook → ADDON_ACTION_BLOCKED.
-- C_Timer.After(0) escapet den protected execution stack.
PVEFrame:HookScript("OnShow", function()
    C_Timer.After(0, function()
        if AiB_Settings and AiB_Settings.season_frame_enabled ~= false then
            seasonFrame:Show()
            UpdateSeasonButtons()

            if AiB.HearthstoneToys and AiB.HearthstoneToys.button then
                C_Timer.After(0.1, function()
                    AiB.HearthstoneToys:UpdateButton()
                end)
            end
        end
    end)
end)

PVEFrame:HookScript("OnHide", function()
    C_Timer.After(0, function()
        seasonFrame:Hide()
    end)
end)

