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 name
    if type(C_ChallengeMode) == "table" and type(C_ChallengeMode.GetMapUIInfo) == "function" then
        local nameOK, value = pcall(C_ChallengeMode.GetMapUIInfo, mapID)
        if nameOK and type(value) == "string" then name = value end
    end
    local short = TOAST.DUNGEON_SHORT[name] or name
    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)

TOAST.commands["keys"] = function()
    if not kf then BuildKeyFrame() end
    if kf:IsShown() then kf:Hide() else kf:Show() end
end
