-- Init.lua - bootstrap, slash commands, events.
local ADDON, ns = ...

local didSetup = false

-- Full setup. Safe to call once we are logged in (or once ADDON_LOADED has
-- delivered our SavedVariables).
local function Setup()
    if didSetup then return end
    didSetup = true
    -- Seed the RNG. Isolated in pcall so a missing API (some clients lack
    -- GetTime at this point) can never block UI / Comm initialisation below.
    pcall(function()
        local seed = (time and time()) or 0
        if GetTime then seed = seed + math.floor((GetTime() * 1000)) % 100000 end
        math.randomseed(seed)
        for _ = 1, 5 do math.random() end
    end)
    ns.InitDB()
    ns.UI.Build()
    ns.Comm.Register()
    ns.Print("v" .. ns.VERSION .. " loaded. Type |cffffd700/bj|r to open the table.")
end

local boot = CreateFrame("Frame")
boot:RegisterEvent("ADDON_LOADED")
boot:RegisterEvent("PLAYER_LOGIN")
boot:SetScript("OnEvent", function(_, event, arg1)
    if event == "ADDON_LOADED" and arg1 == ADDON then
        -- SavedVariables are available now; make the DB ready immediately.
        ns.InitDB()
        -- If we somehow loaded after PLAYER_LOGIN already fired, finish setup.
        if IsLoggedIn() then Setup() end
    elseif event == "PLAYER_LOGIN" then
        Setup()
    end
end)

SLASH_BLACKJACK1 = "/bj"
SLASH_BLACKJACK2 = "/blackjack"
SlashCmdList["BLACKJACK"] = function(msg)
    if not ns.db then ns.InitDB() end
    msg = (msg or ""):lower():gsub("^%s+", ""):gsub("%s+$", "")
    if msg == "host" or msg == "open" then
        ns.UI.Show()
        ns.Engine.OpenTable()
    elseif msg == "close" then
        ns.Engine.CloseTable()
    elseif msg == "reset" then
        ns.db.stats = { wagered = 0, won = 0, lost = 0, hands = 0 }
        ns.Print("Session statistics reset.")
        ns.UI.Render(ns.Engine.state)
    elseif msg == "stats" then
        local s = ns.db.stats
        ns.Print(("Hands: %d | Wagered: %dg | Won: %dg | Lost: %dg")
            :format(s.hands, s.wagered, s.won, s.lost))
    else
        ns.UI.Toggle()
    end
end
