local ADDON_NAME, NS = ...
local L = LibStub("AceLocale-3.0"):GetLocale("MDungeonTeleports")
local SecureTabs = LibStub("SecureTabs-2.0")

-- Layout variables
local BUTTON_WIDTH = 208
local BUTTON_HEIGHT = 50
local BUTTONS_PER_ROW = 3
local MAX_ROWS_PER_PAGE = 7  -- Maximum rows that fit without overlapping page buttons
local START_OFFSET_X = 40
local START_OFFSET_Y = -60
local BUTTON_PADDING_X = 0
local BUTTON_PADDING_Y = 16

-- MARK: Teleports Tab for Collections Journal
local TeleportsFrame = CreateFrame("Frame", "MDungeonTeleportsCollectionsTab", CollectionsJournal)
TeleportsFrame:SetAllPoints()
TeleportsFrame:Hide()
TeleportsFrame:SetPropagateMouseMotion(true)
TeleportsFrame:SetPropagateMouseClicks(true)
TeleportsFrame:EnableMouseWheel(true)

-- Background using Blizzard's template
local bgFrame = CreateFrame("Frame", nil, TeleportsFrame, "CollectionsBackgroundTemplate")
bgFrame:SetPoint("TOPLEFT", 3, -20)
bgFrame:SetPoint("BOTTOMRIGHT", -3, 3)

-- Hide background texture if ElvUI is loaded
if C_AddOns.IsAddOnLoaded("ElvUI") then
    bgFrame:Hide()
end

-- Create button pool
TeleportsFrame.buttonPool = {}
TeleportsFrame.headerPool = {}
TeleportsFrame.currentPage = 1
TeleportsFrame.portalData = {}

local function FormatCooldownTime(seconds)
    if seconds >= 3600 then
        local hours = math.floor(seconds / 3600)
        return string.format("%dh", hours)
    elseif seconds >= 60 then
        local minutes = math.floor(seconds / 60)
        return string.format("%dm", minutes)
    else
        return string.format("%ds", math.floor(seconds))
    end
end

local function UpdateCooldownText(button, spellID)
    if InCombatLockdown() then return end
    if not button or not button.cooldownText or not button.cooldownOverlay then return end

    if not spellID or not C_SpellBook.IsSpellInSpellBook(spellID) then
        button.cooldownText:SetText("")
        button.cooldownOverlay:Hide()
        return
    end

    local cd = C_Spell.GetSpellCooldown(spellID)
    if not cd or issecretvalue(cd.startTime) or issecretvalue(cd.duration) then
        button.cooldownText:SetText("")
        button.cooldownOverlay:Hide()
        return
    end

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

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

-- Function to create a teleport button
local function CreateTeleportButton(parent, index)
    local button = CreateFrame("CheckButton", nil, parent, "SecureActionButtonTemplate")
    button:SetSize(BUTTON_WIDTH, BUTTON_HEIGHT)
    button:RegisterForClicks("AnyUp", "AnyDown")
    button:SetAttribute("type", "spell")
    
    -- Constrain hit rect to icon area only (left side, 56px width including border)
    button:SetHitRectInsets(0, BUTTON_WIDTH - 56, 0, 0)
    
    -- Icon
    local iconTexture = button:CreateTexture(nil, "BORDER")
    iconTexture:SetSize(46, 46)
    iconTexture:SetPoint("LEFT", 4, 0)
    iconTexture:SetTexCoord(0.07, 0.93, 0.07, 0.93)
    button.iconTexture = iconTexture
    
    -- Uncollected icon overlay
    local iconTextureUncollected = button:CreateTexture(nil, "BORDER")
    iconTextureUncollected:SetSize(46, 46)
    iconTextureUncollected:SetPoint("LEFT", 4, 0)
    iconTextureUncollected:SetTexCoord(0.07, 0.93, 0.07, 0.93)
    iconTextureUncollected:SetDesaturated(true)
    iconTextureUncollected:Hide()
    button.iconTextureUncollected = iconTextureUncollected
    
    -- Slot frame for collected (background border)
    local slotFrameCollected = button:CreateTexture(nil, "ARTWORK", nil, -1)
    slotFrameCollected:SetSize(56, 56)
    slotFrameCollected:SetPoint("CENTER", iconTexture, "CENTER", 0, 0)
    slotFrameCollected:SetAtlas("collections-itemborder-collected")
    button.slotFrameCollected = slotFrameCollected
    
    -- Slot frame for uncollected
    local slotFrameUncollected = button:CreateTexture(nil, "ARTWORK", nil, -1)
    slotFrameUncollected:SetSize(56, 56)
    slotFrameUncollected:SetPoint("CENTER", iconTexture, "CENTER", 0, 0)
    slotFrameUncollected:SetAtlas("collections-itemborder-uncollected")
    slotFrameUncollected:Hide()
    button.slotFrameUncollected = slotFrameUncollected
    
    -- Inner glow for uncollected
    local slotFrameUncollectedInnerGlow = button:CreateTexture(nil, "ARTWORK")
    slotFrameUncollectedInnerGlow:SetSize(56, 56)
    slotFrameUncollectedInnerGlow:SetPoint("CENTER", slotFrameUncollected)
    slotFrameUncollectedInnerGlow:SetAtlas("collections-itemborder-glow")
    slotFrameUncollectedInnerGlow:SetBlendMode("ADD")
    slotFrameUncollectedInnerGlow:Hide()
    button.slotFrameUncollectedInnerGlow = slotFrameUncollectedInnerGlow
    
    -- Name text
    local name = button:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    name:SetSize(140, 0)
    name:SetPoint("LEFT", 65, 1)
    name:SetJustifyH("LEFT")
    name:SetMaxLines(2)
    button.name = name
    
    -- Highlight texture (only around icon, not text)
    local highlight = button:CreateTexture(nil, "HIGHLIGHT")
    highlight:SetTexture("Interface\\Buttons\\ButtonHilight-Square")
    highlight:SetBlendMode("ADD")
    highlight:SetSize(46, 46)
    highlight:SetPoint("CENTER", iconTexture, "CENTER", 0, 0)
    button:SetHighlightTexture(highlight)

    local cooldownOverlay = button:CreateTexture(nil, "ARTWORK")
    cooldownOverlay:SetAllPoints(iconTexture)
    cooldownOverlay:SetTexture("Interface\\Tooltips\\UI-Tooltip-Background")
    cooldownOverlay:SetVertexColor(0, 0, 0, 0.6)
    cooldownOverlay:Hide()
    button.cooldownOverlay = cooldownOverlay

    local cooldownText = button:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    cooldownText:SetPoint("CENTER", iconTexture, "CENTER", 1, 0)
    cooldownText:SetTextColor(1, 1, 1)
    cooldownText:SetFont(cooldownText:GetFont(), 17, "OUTLINE")
    button.cooldownText = cooldownText
    
    -- Selected texture
    local selectedTexture = button:CreateTexture(nil, "OVERLAY", nil, 1)
    selectedTexture:SetAtlas("PetList-ButtonSelect")
    selectedTexture:SetAllPoints(button)
    selectedTexture:Hide()
    button.selectedTexture = selectedTexture
    
    -- Spell attribute will be set when button is updated
    -- Secure buttons handle casting automatically
    
    -- Tooltip handler
    button:SetScript("OnEnter", function(self)
        if self.spellID then
            GameTooltip:SetOwner(self, "ANCHOR_NONE")
            GameTooltip:SetPoint("BOTTOMLEFT", self.slotFrameCollected, "TOPRIGHT", -2, -2)
            GameTooltip:SetSpellByID(self.spellID)
            GameTooltip:Show()
        end
    end)
    
    button:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
    
    return button
end

-- Function to get or create a button from the pool
local function GetButton(index)
    if not TeleportsFrame.buttonPool[index] then
        TeleportsFrame.buttonPool[index] = CreateTeleportButton(TeleportsFrame, index)
    end
    return TeleportsFrame.buttonPool[index]
end

-- Function to get or create a header from the pool
local function GetHeader(index)
    if not TeleportsFrame.headerPool[index] then
        local header = CreateFrame("Frame", nil, TeleportsFrame)
        header:SetSize(625, 24)
        
        -- Background texture
        local bg = header:CreateTexture(nil, "BACKGROUND")
        bg:SetAtlas("collections-slotheader", true)
        bg:SetPoint("CENTER")
        header.bg = bg
        
        -- Text using Fancy16Font style
        local text = header:CreateFontString(nil, "OVERLAY", "Fancy16Font")
        text:SetPoint("CENTER")
        text:SetJustifyH("CENTER")
        text:SetJustifyV("MIDDLE")
        text:SetTextColor(0.47, 0.44, 0.28)
        text:SetShadowOffset(1, -1)
        text:SetShadowColor(0, 0, 0)
        header.text = text
        
        TeleportsFrame.headerPool[index] = header
    end
    return TeleportsFrame.headerPool[index]
end

-- Function to build portal data from tables
local function BuildPortalData()
    TeleportsFrame.portalData = {}
    
    -- Add all portal tables with their expansion names
    local portalTables = {
        {name = L["EXP_MID"], data = MDT_PL_MID},
        {name = L["EXP_TWW"], data = MDT_PL_TWW},
        {name = L["EXP_TWW_RAIDS"], data = MDT_PLR_TWW},
        {name = L["EXP_DF"], data = MDT_PL_DF},
        {name = L["EXP_DF_RAIDS"], data = MDT_PLR_DF},
        {name = L["EXP_SL"], data = MDT_PL_SL},
        {name = L["EXP_SL_RAIDS"], data = MDT_PLR_SL},
        {name = L["EXP_BFA"], data = MDT_PL_BFA},
        {name = L["EXP_LEG"], data = MDT_PL_Legion},
        {name = L["EXP_WOD"], data = MDT_PL_WOD},
        {name = L["EXP_MOP"], data = MDT_PL_MOP},
        {name = L["EXP_CATA"], data = MDT_PL_CATA},
        {name = L["EXP_WRATH"], data = MDT_PL_WRATH}
    }
    
    for _, expansionTable in ipairs(portalTables) do
        if expansionTable.data then
            local hasData = false
            for _ in pairs(expansionTable.data) do
                hasData = true
                break
            end
            
            if hasData then
                -- Add header entry
                table.insert(TeleportsFrame.portalData, {isHeader = true, name = expansionTable.name})
                -- Add portals
                for _, portal in ipairs(expansionTable.data) do
                    table.insert(TeleportsFrame.portalData, portal)
                end
            end
        end
    end
end

-- Function to layout buttons for current page
local function LayoutCurrentPage()
    if InCombatLockdown() then return end
    -- Calculate page boundaries dynamically
    local currentPageIndex = 1
    local itemsInCurrentPage = 0
    local rowsInCurrentPage = 0
    local colInRow = 0
    
    -- Find the start and end index for current page
    local startIndex = nil
    local endIndex = nil
    
    for i = 1, #TeleportsFrame.portalData do
        local portal = TeleportsFrame.portalData[i]
        
        if portal.isHeader then
            -- If we're mid-row, finish the current row first
            if colInRow > 0 then
                rowsInCurrentPage = rowsInCurrentPage + 1
                colInRow = 0
            end
            
            -- Check if adding this header would exceed page limit
            -- Header takes 1 row, and we need at least 1 more row for content after it
            if rowsInCurrentPage + 2 > MAX_ROWS_PER_PAGE and itemsInCurrentPage > 0 then
                -- Start a new page
                currentPageIndex = currentPageIndex + 1
                rowsInCurrentPage = 0
                colInRow = 0
                itemsInCurrentPage = 0
            end
            
            -- Add the header
            rowsInCurrentPage = rowsInCurrentPage + 1
            itemsInCurrentPage = itemsInCurrentPage + 1
        else
            -- Check if we need to move to next row
            if colInRow >= BUTTONS_PER_ROW then
                rowsInCurrentPage = rowsInCurrentPage + 1
                colInRow = 0
            end
            
            -- Check if adding this button would exceed page limit
            if rowsInCurrentPage >= MAX_ROWS_PER_PAGE and itemsInCurrentPage > 0 then
                -- Start a new page
                currentPageIndex = currentPageIndex + 1
                rowsInCurrentPage = 0
                colInRow = 0
                itemsInCurrentPage = 0
            end
            
            colInRow = colInRow + 1
            itemsInCurrentPage = itemsInCurrentPage + 1
        end
        
        -- Mark boundaries for requested page
        if currentPageIndex == TeleportsFrame.currentPage and not startIndex then
            startIndex = i
        end
        if currentPageIndex == TeleportsFrame.currentPage then
            endIndex = i
        end
        if currentPageIndex > TeleportsFrame.currentPage then
            break
        end
    end
    
    -- Safety check
    if not startIndex then startIndex = 1 end
    if not endIndex then endIndex = #TeleportsFrame.portalData end
    
    -- Hide all buttons and headers first
    for _, button in pairs(TeleportsFrame.buttonPool) do
        button:Hide()
    end
    for _, header in pairs(TeleportsFrame.headerPool) do
        header:Hide()
    end
    
    -- Layout visible items
    local buttonIndex = 1
    local headerIndex = 1
    local row = 0
    local col = 0
    
    for i = startIndex, endIndex do
        local portal = TeleportsFrame.portalData[i]
        
        -- Handle header entries
        if portal.isHeader then
            -- Headers take up a full row
            if col > 0 then
                -- Move to next row if we're not at the start of a row
                row = row + 1
                col = 0
            end
            
            local header = GetHeader(headerIndex)
            header.text:SetText(portal.name)
            
            local y = START_OFFSET_Y - row * (BUTTON_HEIGHT + BUTTON_PADDING_Y)
            header:SetPoint("TOP", TeleportsFrame, "TOP", 0, y)
            header:Show()
            headerIndex = headerIndex + 1
            
            -- Move to next row for buttons
            row = row + 1
            col = 0
        else
            -- Handle regular button entries
            local button = GetButton(buttonIndex)
            
            -- Set button data
            button.iconTexture:SetTexture(portal.icon)
            button.iconTextureUncollected:SetTexture(portal.icon)
            button.iconTextureUncollected:SetDesaturated(true)
            button.name:SetText(portal.fullname or portal.name)
            button.spellID = portal.spellID
            button:SetAttribute("spell", portal.spellID)
            
            -- Check if player has the spell
            local hasSpell = C_SpellBook.IsSpellInSpellBook(portal.spellID)
            if hasSpell then
                button.iconTexture:Show()
                button.iconTextureUncollected:Hide()
                button.name:SetTextColor(1, 0.82, 0, 1)
                button.name:SetShadowColor(0, 0, 0, 1)
                button.slotFrameCollected:Show()
                button.slotFrameUncollected:Hide()
                button.slotFrameUncollectedInnerGlow:Hide()
            else
                button.iconTexture:Hide()
                button.iconTextureUncollected:Show()
                button.name:SetTextColor(0.33, 0.27, 0.20, 1)
                button.name:SetShadowColor(0, 0, 0, 0.33)
                button.slotFrameCollected:Hide()
                button.slotFrameUncollected:Show()
                button.slotFrameUncollectedInnerGlow:Show()
            end

            UpdateCooldownText(button, portal.spellID)
            
            -- Position button in grid
            local x = START_OFFSET_X + col * (BUTTON_WIDTH + BUTTON_PADDING_X)
            local y = START_OFFSET_Y - row * (BUTTON_HEIGHT + BUTTON_PADDING_Y)
            
            button:SetPoint("TOPLEFT", TeleportsFrame, "TOPLEFT", x, y)
            button:Show()
            
            buttonIndex = buttonIndex + 1
            col = col + 1
            
            -- Move to next row if we've filled the current row
            if col >= BUTTONS_PER_ROW then
                row = row + 1
                col = 0
            end
        end
    end
end

local cooldownEventFrame = CreateFrame("Frame")
cooldownEventFrame:RegisterEvent("SPELLS_CHANGED")
cooldownEventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
cooldownEventFrame:RegisterEvent("CHALLENGE_MODE_COMPLETED")
cooldownEventFrame:SetScript("OnEvent", function()
    if TeleportsFrame and TeleportsFrame:IsShown() then
        for _, button in pairs(TeleportsFrame.buttonPool) do
            if button:IsShown() then
                UpdateCooldownText(button, button.spellID)
            end
        end
    end
end)

TeleportsFrame.cooldownTicker = C_Timer.NewTicker(1, function()
    if TeleportsFrame and TeleportsFrame:IsShown() then
        for _, button in pairs(TeleportsFrame.buttonPool) do
            if button:IsShown() then
                UpdateCooldownText(button, button.spellID)
            end
        end
    end
end)

-- Function to update page display
local function UpdatePage(newPage)
    TeleportsFrame.currentPage = newPage
    LayoutCurrentPage()
    
    if TeleportsFrame.PagingFrame then
        TeleportsFrame.PagingFrame:SetCurrentPage(newPage)
    end
end

-- Mouse wheel scrolling through pages
TeleportsFrame:SetScript("OnMouseWheel", function(self, delta)
    local maxPages = TeleportsFrame.PagingFrame and TeleportsFrame.PagingFrame.maxPages or 1
    
    if delta > 0 then
        -- Scroll up - go to previous page
        if TeleportsFrame.currentPage > 1 then
            PlaySound(SOUNDKIT.IG_ABILITY_PAGE_TURN)
            UpdatePage(TeleportsFrame.currentPage - 1)
        end
    else
        -- Scroll down - go to next page
        if TeleportsFrame.currentPage < maxPages then
            PlaySound(SOUNDKIT.IG_ABILITY_PAGE_TURN)
            UpdatePage(TeleportsFrame.currentPage + 1)
        end
    end
end)

-- Create paging frame manually
TeleportsFrame.PagingFrame = CreateFrame("Frame", nil, TeleportsFrame)
TeleportsFrame.PagingFrame:SetSize(200, 30)
TeleportsFrame.PagingFrame:SetPoint("BOTTOM", 21, 43)
TeleportsFrame.PagingFrame:EnableMouse(false)  -- Don't block mouse events for BlizzMove compatibility

-- Page text
TeleportsFrame.PagingFrame.PageText = TeleportsFrame.PagingFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
TeleportsFrame.PagingFrame.PageText:SetPoint("LEFT", 5, 0)
local fontPath, _, fontFlags = TeleportsFrame.PagingFrame.PageText:GetFont()
TeleportsFrame.PagingFrame.PageText:SetFont(fontPath, 12, fontFlags)

-- Previous page button
TeleportsFrame.PagingFrame.PrevPageButton = CreateFrame("Button", nil, TeleportsFrame.PagingFrame)
TeleportsFrame.PagingFrame.PrevPageButton:SetSize(32, 32)
TeleportsFrame.PagingFrame.PrevPageButton:SetPoint("LEFT", TeleportsFrame.PagingFrame.PageText, "RIGHT", 5, 0)
TeleportsFrame.PagingFrame.PrevPageButton:SetNormalTexture("Interface\\Buttons\\UI-SpellbookIcon-PrevPage-Up")
TeleportsFrame.PagingFrame.PrevPageButton:SetPushedTexture("Interface\\Buttons\\UI-SpellbookIcon-PrevPage-Down")
TeleportsFrame.PagingFrame.PrevPageButton:SetDisabledTexture("Interface\\Buttons\\UI-SpellbookIcon-PrevPage-Disabled")
TeleportsFrame.PagingFrame.PrevPageButton:SetHighlightTexture("Interface\\Buttons\\UI-Common-MouseHilight")
TeleportsFrame.PagingFrame.PrevPageButton:SetScript("OnClick", function()
    if TeleportsFrame.currentPage > 1 then
        PlaySound(SOUNDKIT.IG_ABILITY_PAGE_TURN)
        UpdatePage(TeleportsFrame.currentPage - 1)
    end
end)

-- Next page button
TeleportsFrame.PagingFrame.NextPageButton = CreateFrame("Button", nil, TeleportsFrame.PagingFrame)
TeleportsFrame.PagingFrame.NextPageButton:SetSize(32, 32)
TeleportsFrame.PagingFrame.NextPageButton:SetPoint("LEFT", TeleportsFrame.PagingFrame.PrevPageButton, "RIGHT", 5, 0)
TeleportsFrame.PagingFrame.NextPageButton:SetNormalTexture("Interface\\Buttons\\UI-SpellbookIcon-NextPage-Up")
TeleportsFrame.PagingFrame.NextPageButton:SetPushedTexture("Interface\\Buttons\\UI-SpellbookIcon-NextPage-Down")
TeleportsFrame.PagingFrame.NextPageButton:SetDisabledTexture("Interface\\Buttons\\UI-SpellbookIcon-NextPage-Disabled")
TeleportsFrame.PagingFrame.NextPageButton:SetHighlightTexture("Interface\\Buttons\\UI-Common-MouseHilight")
TeleportsFrame.PagingFrame.NextPageButton:SetScript("OnClick", function()
    local maxPages = TeleportsFrame.PagingFrame.maxPages or 1
    if TeleportsFrame.currentPage < maxPages then
        PlaySound(SOUNDKIT.IG_ABILITY_PAGE_TURN)
        UpdatePage(TeleportsFrame.currentPage + 1)
    end
end)

-- Helper functions for paging frame
TeleportsFrame.PagingFrame.SetMaxPages = function(self, maxPages)
    self.maxPages = maxPages
    self:UpdateButtons()
end

TeleportsFrame.PagingFrame.SetCurrentPage = function(self, page)
    self.PageText:SetText(L["PAGE"] .. " " .. page .. " / " .. (self.maxPages or 1))
    self:UpdateButtons()
end

TeleportsFrame.PagingFrame.UpdateButtons = function(self)
    self.PrevPageButton:SetEnabled(TeleportsFrame.currentPage > 1)
    self.NextPageButton:SetEnabled(TeleportsFrame.currentPage < (self.maxPages or 1))
end

TeleportsFrame.PagingFrame.maxPages = 1

-- Store original portrait texture and title text
local originalPortraitTexture = nil
local originalTitleText = nil

-- Store tab reference
local teleportsTab = nil

-- Function to calculate total pages based on layout
local function CalculateTotalPages()
    local currentPage = 1
    local rowsInCurrentPage = 0
    local colInRow = 0
    
    for i = 1, #TeleportsFrame.portalData do
        local portal = TeleportsFrame.portalData[i]
        
        if portal.isHeader then
            -- If we're mid-row, finish the current row first
            if colInRow > 0 then
                rowsInCurrentPage = rowsInCurrentPage + 1
                colInRow = 0
            end
            
            -- Check if adding this header would exceed page limit
            if rowsInCurrentPage + 2 > MAX_ROWS_PER_PAGE and rowsInCurrentPage > 0 then
                currentPage = currentPage + 1
                rowsInCurrentPage = 0
                colInRow = 0
            end
            
            rowsInCurrentPage = rowsInCurrentPage + 1
        else
            -- Check if we need to move to next row
            if colInRow >= BUTTONS_PER_ROW then
                rowsInCurrentPage = rowsInCurrentPage + 1
                colInRow = 0
            end
            
            -- Check if adding this button would exceed page limit
            if rowsInCurrentPage >= MAX_ROWS_PER_PAGE and rowsInCurrentPage > 0 then
                currentPage = currentPage + 1
                rowsInCurrentPage = 0
                colInRow = 0
            end
            
            colInRow = colInRow + 1
        end
    end
    
    return currentPage
end

-- Initialize tab when CollectionsJournal is loaded
local function InitializeTab()
    if not CollectionsJournal then
        return
    end
    
    -- Check if teleports tab should be shown
    if not MDungeonTeleports or MDungeonTeleports.teleportsTab ~= true then
        return
    end
    
    -- Build portal data and setup pages
    BuildPortalData()
    local totalPages = CalculateTotalPages()
    TeleportsFrame.PagingFrame:SetMaxPages(math.max(totalPages, 1))
    
    teleportsTab = SecureTabs:Add(CollectionsJournal, TeleportsFrame, L["TELEPORTS_TITLE"])
    
    -- Apply ElvUI skinning to the tab if ElvUI is loaded
    if C_AddOns.IsAddOnLoaded("ElvUI") then
        local E = unpack(ElvUI)
        if E then
            local S = E:GetModule('Skins')
            if S and S.HandleTab then
                S:HandleTab(teleportsTab)
                
                -- Skin all existing Collections Journal tabs so they match
                for i = 1, CollectionsJournal.numTabs or 0 do
                    local tab = _G["CollectionsJournalTab" .. i]
                    if tab and not tab.elvuiSkinned then
                        S:HandleTab(tab)
                        tab.elvuiSkinned = true
                    end
                end
                
                -- Skin the cover tab that appears over the previously selected tab
                local coverTab = SecureTabs.covers[CollectionsJournal]
                if coverTab and not coverTab.elvuiSkinned then
                    S:HandleTab(coverTab)
                    coverTab.elvuiSkinned = true
                end
            end
        end
    end
    
    -- Hook into TeleportsFrame show to update content and UI
    TeleportsFrame:HookScript("OnShow", function()
        -- Update the display to ensure content is loaded
        UpdatePage(TeleportsFrame.currentPage)
        
        -- Hide the underlying covered tab's text to prevent it showing through
        if CollectionsJournal.selectedTab then
            local origTab = _G["CollectionsJournalTab" .. CollectionsJournal.selectedTab]
            if origTab then
                local textFS = origTab.Text or origTab:GetFontString()
                if textFS then
                    textFS:SetAlpha(0)
                end
            end
        end
        
        -- Hide other collection tabs' content frames to prevent overlap
        if MountJournal then
            MountJournal:Hide()
            -- Hide MountJournal buttons that would overlap with our UI
            if MountJournal.ToggleDynamicFlightFlyoutButton then
                MountJournal.ToggleDynamicFlightFlyoutButton:Hide()
            end
            if MountJournal.SummonRandomFavoriteSpellFrame then
                MountJournal.SummonRandomFavoriteSpellFrame:Hide()
            end
        end
        if PetJournal then
            PetJournal:Hide()
        end
        if ToyBox then
            ToyBox:Hide()
        end
        if HeirloomsJournal then
            HeirloomsJournal:Hide()
        end
        if WardrobeCollectionFrame then
            WardrobeCollectionFrame:Hide()
        end
        if WarbandSceneJournal then
            WarbandSceneJournal:Hide()
        end
        
        -- Store the original values on first selection
        if not originalPortraitTexture and CollectionsJournalPortrait then
            originalPortraitTexture = CollectionsJournalPortrait:GetTexture()
        end
        if not originalTitleText and CollectionsJournalTitleText then
            originalTitleText = CollectionsJournalTitleText:GetText()
        end
        
        -- Change the portrait icon
        if CollectionsJournalPortrait then
            CollectionsJournalPortrait:SetTexture("Interface\\Icons\\inv_misc_shadowegg")
        end
        
        -- Change the title text
        if CollectionsJournalTitleText then
            CollectionsJournalTitleText:SetText(L["TELEPORTS_TITLE"])
        end
    end)
    
    -- Hook into TeleportsFrame hide to restore original UI
    TeleportsFrame:HookScript("OnHide", function()
        -- Restore the covered tab's text when switching away from Teleports
        if CollectionsJournal.selectedTab then
            local origTab = _G["CollectionsJournalTab" .. CollectionsJournal.selectedTab]
            if origTab then
                local textFS = origTab.Text or origTab:GetFontString()
                if textFS then
                    textFS:SetAlpha(1)
                end
            end
        end
        
        -- Restore the original portrait icon
        if CollectionsJournalPortrait and originalPortraitTexture then
            CollectionsJournalPortrait:SetTexture(originalPortraitTexture)
        end
        -- Restore the original title text
        if CollectionsJournalTitleText and originalTitleText then
            CollectionsJournalTitleText:SetText(originalTitleText)
        end
        
        -- Show other collection frames again based on which tab is selected
        if CollectionsJournal and CollectionsJournal.selectedTab then
            if CollectionsJournal.selectedTab == 1 and MountJournal then
                MountJournal:Show()
                -- Show MountJournal buttons again
                if MountJournal.ToggleDynamicFlightFlyoutButton then
                    MountJournal.ToggleDynamicFlightFlyoutButton:Show()
                end
                if MountJournal.SummonRandomFavoriteSpellFrame then
                    MountJournal.SummonRandomFavoriteSpellFrame:Show()
                end
            elseif CollectionsJournal.selectedTab == 2 and PetJournal then
                PetJournal:Show()
            elseif CollectionsJournal.selectedTab == 3 and ToyBox then
                ToyBox:Show()
            elseif CollectionsJournal.selectedTab == 4 and HeirloomsJournal then
                HeirloomsJournal:Show()
            elseif CollectionsJournal.selectedTab == 5 and WardrobeCollectionFrame then
                WardrobeCollectionFrame:Show()
            elseif CollectionsJournal.selectedTab == 6 and WarbandSceneJournal then
                WarbandSceneJournal:Show()
            end
        end
    end)
    
    teleportsTab.OnSelect = function()
        -- Load collections addon if not already loaded
        C_AddOns.LoadAddOn("Blizzard_Collections")
        
        -- When the tab is selected, show our custom frame
        if TeleportsFrame then
            TeleportsFrame:Show()
        end
    end
    
    -- Hook CollectionsJournal OnShow to handle reopening with Teleports tab selected
    CollectionsJournal:HookScript("OnShow", function()
        -- If TeleportsFrame is visible, ensure other frames are hidden
        if TeleportsFrame and TeleportsFrame:IsShown() then
            if MountJournal then
                MountJournal:Hide()
            end
            if PetJournal then
                PetJournal:Hide()
            end
            if ToyBox then
                ToyBox:Hide()
            end
            if HeirloomsJournal then
                HeirloomsJournal:Hide()
            end
            if WardrobeCollectionFrame then
                WardrobeCollectionFrame:Hide()
            end
            if WarbandSceneJournal then
                WarbandSceneJournal:Hide()
            end
        end
    end)
end

-- Wait for CollectionsJournal to be available
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(self, event, addonName)
    if addonName == "Blizzard_Collections" then
        InitializeTab()
        frame:UnregisterEvent("ADDON_LOADED")
    end
end)

-- If Collections is already loaded, initialize immediately
if C_AddOns.IsAddOnLoaded("Blizzard_Collections") and CollectionsJournal then
    InitializeTab()
end

-- Global function to show/hide the tab dynamically
function MDTUpdateTeleportsTab(visible)
    if not CollectionsJournal then
        return
    end
    
    if visible then
        -- If tab doesn't exist yet, initialize it
        if not teleportsTab then
            InitializeTab()
        end
        -- Show the tab if it exists
        if teleportsTab and teleportsTab.Show then
            teleportsTab:Show()
        end
    else
        -- Hide the tab if it exists
        if teleportsTab and teleportsTab.Hide then
            teleportsTab:Hide()
        end
    end
end
