local addonName, TOAST = ...

TOAST.commands = {}

-- Single source of truth for the addon version, read from the .toc so it
-- never drifts out of sync with what's actually shipped.
local getAddOnMetadata = C_AddOns and C_AddOns.GetAddOnMetadata or GetAddOnMetadata
TOAST.VERSION = (getAddOnMetadata and getAddOnMetadata(addonName, "Version")) or "?"

-- Blizzard resolves cross-realm targets by a canonical realm slug. Bot data
-- and club records can use display variants such as "Tarren-mill"; keep the
-- correction in one shared formatter for whispers, invites, and copy actions.
local CANONICAL_REALM_SLUGS = {
    tarrenmill = "TarrenMill",
}

function TOAST.FormatCharacterTarget(name, realm)
    if type(name) ~= "string" or name == "" then return nil end
    if type(realm) ~= "string" or realm == "" then return name end
    local slug = realm:gsub("[%s%-']", "")
    if slug == "" then return name end
    slug = CANONICAL_REALM_SLUGS[slug:lower()] or slug
    return name .. "-" .. slug
end

local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function()
    print("|cff33ff99TOAST|r v" .. TOAST.VERSION .. " geladen.")
end)

-- Persists top-level window positions (leaderboard, dashboard, ...) in
-- TOAST_DB so dragging a window sticks across /reload instead of resetting
-- to CENTER every time. Called by each window's header OnDragStop.
function TOAST.SaveWindowPosition(frame, key)
    local point, _, relativePoint, x, y = frame:GetPoint()
    TOAST_DB.windowPos = TOAST_DB.windowPos or {}
    TOAST_DB.windowPos[key] = { point = point, relativePoint = relativePoint, x = x, y = y }
end

function TOAST.RestoreWindowPosition(frame, key)
    local pos = TOAST_DB.windowPos and TOAST_DB.windowPos[key]
    if pos then
        frame:SetPoint(pos.point, UIParent, pos.relativePoint, pos.x, pos.y)
    else
        frame:SetPoint("CENTER")
    end
end

TOAST.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",
}

function TOAST.CanOpenMajorWindow()
    if TOAST.IsUpdateBlocked and TOAST.IsUpdateBlocked() then
        if TOAST.ShowUpdateRequired then TOAST.ShowUpdateRequired() end
        return false
    end
    if InCombatLockdown and InCombatLockdown() then
        print("|cff33ff99TOAST|r: Waters are rough... opening after combat.")
        return false
    end
    return true
end

TOAST.commands[""] = function()
    if TOAST.CheckReleaseStatus and not TOAST.CheckReleaseStatus() then return end
    if TOAST.CheckOnboardingProgress then
        TOAST.CheckOnboardingProgress("dashboard")
        return
    end

    if not TOAST.CanOpenMajorWindow() then return end
    if TOAST.IsInCommunity then
        TOAST.inCommunity = TOAST.IsInCommunity()
    end

    local dismissed = TOAST_DB.dismissedWelcome or {}
    local charName = UnitName("player")

    if not TOAST.inCommunity then
        -- Harde lock: geen community = geen TOAST. Bewust geen dismissed-check
        -- en geen fallback naar het dashboard, anders is de gate te omzeilen.
        if TOAST.ShowCommunityGate then
            TOAST.ShowCommunityGate()
        end
        return
    end

    -- Wel in community
    if TOAST.me then
        -- In roster, herkend → dashboard
        TOAST.commands["dashboard"]()
        return
    end

    if TOAST_DB.me then
        -- Niet in roster maar discord bekend (alt) → dashboard
        TOAST.commands["dashboard"]()
        return
    end

    -- In community maar discord onbekend → discord popup
    if dismissed[charName] ~= true then
        if TOAST.ShowWelcome then
            TOAST.ShowWelcome("discord")
        end
    else
        TOAST.commands["dashboard"]()
    end
end

SLASH_TOAST1 = "/toast"
SlashCmdList["TOAST"] = function(input)
    local command = strtrim(input or ""):lower()
    local releaseCommand = command == "debug" or command == "changelog"
        or command == "test1" or command == "test2" or command == "test3"
    if not releaseCommand and TOAST.IsUpdateBlocked and TOAST.IsUpdateBlocked() then
        if TOAST.ShowUpdateRequired then TOAST.ShowUpdateRequired() end
        return
    end
    if command == "" then
        TOAST.commands[""]()
    elseif TOAST.commands[command] then
        TOAST.commands[command]()
    else
        print("|cff33ff99TOAST|r: onbekend commando. Beschikbaar: /toast lb, /toast keys, /toast debug, /toast changelog")
    end
end
