-- Start Up
if not MDungeonTeleports then
    MDungeonTeleports = {}
end

-- MARK: Visibility Toggle
function KeyFrame_UpdateVisibility(show)
    local KeyF = _G["KeyFrame"]
    if KeyF then
        KeyF:SetShown(show)
    end
end

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(TeleportButton, spellID)
    local cooldownFrame = TeleportButton.cooldownText
    local cooldownOverlay = TeleportButton.cooldownOverlay
    local spellCooldownInfo = C_Spell.GetSpellCooldown(spellID)

    if spellCooldownInfo then
        local startTime = spellCooldownInfo.startTime
        local duration = spellCooldownInfo.duration
        local isEnabled = spellCooldownInfo.isEnabled

        if startTime > 0 and duration > 0 and isEnabled then
            local remaining = max(0, (startTime + duration) - GetTime())

            if remaining > 5 then
                cooldownFrame:SetText(FormatCooldownTime(remaining))
                cooldownOverlay:Show()
            else
                cooldownFrame:SetText("")
                cooldownOverlay:Hide()
            end
        else
            cooldownFrame:SetText("")
            cooldownOverlay:Hide()
        end
    else
        cooldownFrame:SetText("")
        cooldownOverlay:Hide()
    end
end

-- MARK: Frame
local KeyFrame = CreateFrame("Frame", "KeyFrame", PVEFrame)
KeyFrame:SetPoint("TOPRIGHT", PVEFrame, "BOTTOMRIGHT", 0, -1)
KeyFrame:SetSize(110, 30)
KeyFrame:EnableMouse(true)
KeyFrame:Show()

-- KeyFrame Background
local KeyFrameBackground = KeyFrame:CreateTexture(nil, "BACKGROUND")
KeyFrameBackground:SetAllPoints(KeyFrame)
KeyFrameBackground:SetTexture("Interface/AddOns/MDungeonTeleports/media/ui/ui_frames/ui_frames.blp")
KeyFrameBackground:SetTexCoord(0, 0.107421, 0.533203, 0.591796)

local KeyFrameText = KeyFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
KeyFrameText:SetPoint("LEFT", KeyFrame, "LEFT", 30, 0)
KeyFrameText:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 10)
KeyFrameText:SetTextColor(0, 0.7, 1)

-- MARK: Teleport to my key Button
local TeleportButton = CreateFrame("Button", nil, KeyFrame, "SecureActionButtonTemplate")
TeleportButton:SetSize(24, 24)
TeleportButton:SetPoint("LEFT", KeyFrame, "LEFT", 5, 0)

TeleportButton.icon = TeleportButton:CreateTexture(nil, "OVERLAY")
TeleportButton.icon:SetAllPoints()
TeleportButton.icon:SetTexture("Interface\\Icons\\inv_relics_hourglass")

local TeleportButtonBorder = TeleportButton:CreateTexture(nil, "OVERLAY")
TeleportButtonBorder:SetAllPoints(TeleportButton)
TeleportButtonBorder:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_border.blp")
TeleportButtonBorder:SetDrawLayer("OVERLAY", 2)
TeleportButton.TeleportButtonBorder = TeleportButtonBorder

local TeleportButtonHover = TeleportButton:CreateTexture(nil, "HIGHLIGHT")
TeleportButtonHover:SetAllPoints(TeleportButton)
TeleportButtonHover:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_highlight.blp")
TeleportButton.TeleportButtonHover = TeleportButtonHover

-- Cooldown text and overlay
local cooldownText = TeleportButton:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
cooldownText:SetPoint("CENTER", TeleportButton, "CENTER", 0, 0)
cooldownText:SetTextColor(1, 1, 1)
cooldownText:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 12, "OUTLINE")
TeleportButton.cooldownText = cooldownText

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

-- Event handler for cooldown updates
local function OnCooldownEvent(self, event, arg1)
    if event == "SPELL_UPDATE_COOLDOWN" or event == "SPELLS_CHANGED" then
        if self.spellID then
            UpdateCooldownText(self, self.spellID)
        end
    end
end

-- MARK: Key Data
local keystoneTrackerData = {
    ["Ara-Kara, City of Echoes"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_arak-ara", spellID = 445417, name = "ARAK"},
    ["City of Threads"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_cityofthreads", spellID = 445416, name = "COT"},
    ["The Dawnbreaker"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_dawnbreaker", spellID = 445414, name = "DAWN"},
    ["The Stonevault"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_stonevault", spellID = 445269, name = "SV"},
    ["Mists of Tirna Scithe"] = {icon = "Interface\\Icons\\achievement_dungeon_mistsoftirnascithe", spellID = 354464, name = "MISTS"},
    ["The Necrotic Wake"] = {icon = "Interface\\Icons\\achievement_dungeon_theneroticwake", spellID = 354462, name = "NW"},
    ["Siege of Boralus"] = {icon = "Interface\\Icons\\achievement_dungeon_siegeofboralus", spellID = 445418, name = "SIEGE"},
    ["Grim Batol"] = {icon = "Interface\\Icons\\achievement_dungeon_grimbatol", spellID = 445424, name = "GB"},
    ["Cinderbrew Meadery"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_cinderbrewmeadery", spellID = 445440, name = "CM"}, 
    ["Darkflame Cleft"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_darkflamecleft", spellID = 445441, name = "DC"}, 
    ["Priory of the Sacred Flame"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_prioryofthesacredflame", spellID = 445444, name = "PSF"}, 
    ["The Rookery"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_rookery", spellID = 445443, name = "ROOK"},
    ["The MOTHERLODE!!"] = {icon = "Interface\\Icons\\achievement_dungeon_kezan", spellID = motherID, name = "ML"},
    ["Operation: Floodgate"] = {icon = "Interface\\Icons\\inv_achievement_dungeon_waterworks", spellID = 1216786, name = "FLD"},
    ["Theatre of Pain"] = {icon = "Interface\\Icons\\achievement_dungeon_theatreofpain", spellID = 354463, name = "TOP"},
    ["Operation: Mechagon - Workshop"] = {icon = "Interface\\Icons\\achievement_boss_mechagon", spellID = 373274, name = "WORK"} 
}

-- MARK: Look for Key in Bag
local function FindKeystone()
    local keystoneDungeon, keystoneLevel, keystoneItemLink = nil, nil, nil
    local tooltipScanner = CreateFrame("GameTooltip", "KeystoneScanner", nil, "GameTooltipTemplate")
    tooltipScanner:SetOwner(UIParent, "ANCHOR_NONE")

    for bag = 0, 4 do
        local numSlots = C_Container.GetContainerNumSlots(bag)
        for slot = 1, numSlots do
            local itemID = C_Container.GetContainerItemID(bag, slot)
            if itemID == 180653 then
                local itemInfo = C_Container.GetContainerItemInfo(bag, slot)
                keystoneItemLink = itemInfo and itemInfo.hyperlink 
                
                tooltipScanner:SetBagItem(bag, slot)
                
                for i = 1, tooltipScanner:NumLines() do
                    local lineText = _G["KeystoneScannerTextLeft" .. i]:GetText()
                    if lineText then
                        local dungeonMatch = lineText:match("^Keystone:%s*(.+)$")
                        if dungeonMatch then
                            keystoneDungeon = dungeonMatch
                        end
                        local levelMatch = lineText:match("^Mythic Level (%d+)$")
                        if levelMatch then
                            keystoneLevel = tonumber(levelMatch)
                        end
                    end
                end
                
                tooltipScanner:Hide()
                if keystoneDungeon and keystoneLevel then
                    return keystoneDungeon, keystoneLevel, keystoneItemLink
                end
            end
        end
    end
    
    tooltipScanner:Hide()
    return nil, nil, nil
end

-- MARK: Update Keystone and Cooldown Info
local function UpdateKeystoneInfo()
    local keystoneDungeon, keystoneLevel, keystoneItemLink = FindKeystone()
    
    if keystoneDungeon and keystoneLevel then
        local dungeonInfo = keystoneTrackerData[keystoneDungeon]
        if dungeonInfo then
            KeyFrameText:SetText(" " .. keystoneLevel .. " " .. dungeonInfo.name)

            if IsSpellKnown(dungeonInfo.spellID) then
                TeleportButton.icon:SetTexture(dungeonInfo.icon)
                TeleportButton.spellID = dungeonInfo.spellID
                TeleportButton:SetAttribute("type", "spell")
                TeleportButton:SetAttribute("spell", dungeonInfo.spellID)
            else
                TeleportButton.icon:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\lock.blp")
                TeleportButton.spellID = nil
                TeleportButton:SetAttribute("type", nil)
                TeleportButton:SetAttribute("spell", nil)
                KeyFrameText:SetTextColor(1, 0, 0)
            end
        end
    else
        KeyFrameText:SetText(" No Key ")
        TeleportButton.icon:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\lock.blp")
        TeleportButton.spellID = nil
        TeleportButton:SetAttribute("type", nil)
        TeleportButton:SetAttribute("spell", nil)
    end
end

-- Event for updating keystone info when the bag changes
KeyFrame:RegisterEvent("BAG_UPDATE")
KeyFrame:SetScript("OnEvent", function(self, event)
    UpdateKeystoneInfo()
end)

UpdateKeystoneInfo()

-- Register cooldown events
TeleportButton:RegisterEvent("SPELL_UPDATE_COOLDOWN")
TeleportButton:RegisterEvent("SPELLS_CHANGED")
TeleportButton:SetScript("OnEvent", OnCooldownEvent)
TeleportButton:RegisterForClicks("AnyUp", "AnyDown")

-- MARK: !keys button
local PartyChatButton = CreateFrame("Button", nil, KeyFrame, "SecureActionButtonTemplate")
PartyChatButton:SetSize(24, 24)
PartyChatButton:SetPoint("RIGHT", KeyFrame, "RIGHT", -5, 0)

PartyChatButton.icon = PartyChatButton:CreateTexture(nil, "OVERLAY")
PartyChatButton.icon:SetAllPoints()
PartyChatButton.icon:SetTexture("Interface\\Icons\\INV__Blacksmithing_Skeletonkey")

local PartyChatButtonBorder = PartyChatButton:CreateTexture(nil, "OVERLAY")
PartyChatButtonBorder:SetAllPoints(PartyChatButton)
PartyChatButtonBorder:SetDrawLayer("OVERLAY", 2)
PartyChatButton.PartyChatButtonBorder = PartyChatButtonBorder

local PartyChatButtonHover = PartyChatButton:CreateTexture(nil, "HIGHLIGHT")
PartyChatButtonHover:SetAllPoints(PartyChatButton)
PartyChatButtonHover:SetTexture("Interface/AddOns/MDungeonTeleports/media/ui/ui_default/button_highlight.blp")
PartyChatButton.PartyChatButtonHover = PartyChatButtonHover

PartyChatButton:RegisterForClicks("AnyDown")

-- Add a tooltip
PartyChatButton:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_BOTTOM")
    GameTooltip:SetText("!keys", 1, 1, 1)
    GameTooltip:Show()
end)

PartyChatButton:SetScript("OnLeave", function(self)
    GameTooltip:Hide()
end)

PartyChatButton:SetScript("OnClick", function()
    SendChatMessage("!keys", "PARTY")
end)

-- MARK: Respond to !keys
local function OnEvent(self, event, text, sender, ...)
    if MDungeonTeleports.isRespondChecked then
        if event == "CHAT_MSG_PARTY" or event == "CHAT_MSG_PARTY_LEADER" then
            if text:lower() == "!keys" then
                local keystoneDungeon, keystoneLevel, keystoneItemLink = FindKeystone()
                if keystoneItemLink then
                    SendChatMessage("M+DT: " .. keystoneItemLink, "PARTY")
                else
                    SendChatMessage("M+DT: No Keystone.", "PARTY")
                end
            end
        end
    end
end

-- Look for !keys event
local frame = CreateFrame("Frame")
frame:RegisterEvent("CHAT_MSG_PARTY")
frame:RegisterEvent("CHAT_MSG_PARTY_LEADER")
frame:SetScript("OnEvent", OnEvent)

-- Event handler
local function OnEvent(self, event)
    if event == "SPELL_UPDATE_COOLDOWN" or event == "SPELLS_CHANGED" then
        UpdateCooldownText(self, self.spellID)
    end
end

UpdateKeystoneInfo()
