local addonName, TOAST = ...

local DUNGEON_SHORT = {
    ["Algeth'ar Academy"]       = "AA",
    ["Seat of the Triumvirate"] = "SOTT",
    ["Skyreach"]                = "SKY",
    ["Pit of Saron"]            = "PIT",
    ["Windrunner Spire"]        = "SPIRE",
    ["Maisara Caverns"]         = "CAVERN",
    ["Nexus-Point Xenas"]       = "XENAS",
    ["Magisters' Terrace"]      = "MT",
}

local GOLD = "|cffFFD100"

local kf
local keyText

local function UpdateKeyDisplay()
    if not kf then return end
    local mapID = C_MythicPlus.GetOwnedKeystoneChallengeMapID()
    if not mapID or mapID == 0 then
        keyText:SetText(GOLD .. "No keystone|r")
        return
    end
    local level = C_MythicPlus.GetOwnedKeystoneLevel()
    local name  = C_ChallengeMode.GetMapUIInfo(mapID)
    local short = DUNGEON_SHORT[name] or name
    keyText:SetText(GOLD .. "+" .. level .. " " .. short .. "|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", "GameFontNormalHuge")
    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
