local addonName, TOAST = ...

local GOLD = "|cffFFD100"

local kf
local keyText

local function UpdateKeyDisplay()
    if not kf then return end
    if InCombatLockdown() then return end
    if type(C_MythicPlus) ~= "table"
       or type(C_MythicPlus.GetOwnedKeystoneChallengeMapID) ~= "function"
       or type(C_MythicPlus.GetOwnedKeystoneLevel) ~= "function" then
        keyText:SetText(GOLD .. "Keystone unavailable|r")
        return
    end

    local mapOK, mapID = pcall(C_MythicPlus.GetOwnedKeystoneChallengeMapID)
    if not mapOK or type(mapID) ~= "number" or mapID <= 0 then
        keyText:SetText(GOLD .. "No keystone|r")
        return
    end
    local levelOK, level = pcall(C_MythicPlus.GetOwnedKeystoneLevel)
    if not levelOK or type(level) ~= "number" or level <= 0 then
        keyText:SetText(GOLD .. "Keystone unavailable|r")
        return
    end

    local short = TOAST.GetDungeonShort and TOAST.GetDungeonShort(mapID) or ""
    keyText:SetText(GOLD .. "+" .. level .. (short ~= "" and (" " .. short) or "") .. "|r")
end

local function BuildKeyFrame()
    kf = CreateFrame("Frame", "TOASTKeys", UIParent, "BackdropTemplate")
    Mixin(kf, BackdropTemplateMixin)
    kf:SetBackdrop({
        bgFile   = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        edgeSize = 26,
        insets   = { left=9, right=9, top=9, bottom=9 },
    })
    kf:SetBackdropColor(1, 1, 1, 1)
    kf:SetBackdropBorderColor(1, 1, 1, 1)
    kf:SetSize(220, 60)
    kf:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", -200, -200)
    kf:SetMovable(true)
    kf:SetClampedToScreen(true)
    kf:SetFrameStrata("HIGH")
    kf:EnableMouse(true)
    kf:RegisterForDrag("LeftButton")
    kf:SetScript("OnDragStart", function() kf:StartMoving() end)
    kf:SetScript("OnDragStop",  function() kf:StopMovingOrSizing() end)
    kf:Hide()

    keyText = kf:CreateFontString(nil, "OVERLAY", "TOASTFontNormalHuge")
    keyText:SetPoint("CENTER", kf, "CENTER", 0, 0)

    UpdateKeyDisplay()
end

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("CHALLENGE_MODE_MAPS_UPDATE")
ev:SetScript("OnEvent", function()
    UpdateKeyDisplay()
end)

function TOAST.ToggleKeysHUD()
    if not kf then BuildKeyFrame() end
    if kf:IsShown() then kf:Hide() else kf:Show() end
end
