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 "?"

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

TOAST.commands[""] = function()
    if TOAST.IsInCommunity then
        TOAST.inCommunity = TOAST.IsInCommunity()
    end

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

    if not TOAST.inCommunity then
        -- Niet in community = altijd popup
        if dismissed[charName] ~= true then
            local discordKnown = TOAST_DB.me ~= nil
            if discordKnown then
                -- Community link alleen
                if TOAST.ShowWelcome then
                    TOAST.ShowWelcome("community")
                end
            else
                -- Community + Discord link
                if TOAST.ShowWelcome then
                    TOAST.ShowWelcome("both")
                end
            end
        else
            TOAST.commands["dashboard"]()  -- dismissed, door naar dashboard
        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)
    if strtrim(input) == "" then
        TOAST.commands[""]()
    else
        print("|cff33ff99TOAST|r: /toast heeft geen subcommands meer.")
    end
end