-- ============================================================
-- Komo Hold'Em — Core
-- Addon namespace, saved variables, slash commands, events
-- ============================================================
local ADDON_NAME, KH = ...
_G.KomoHoldEm = KH

KH.VERSION = "1.0.9"
KH.PREFIX  = "KomoHoldEm" -- addon message prefix (max 16 chars)

-- Brand palette (shared by all UI files)
KH.COLORS = {
    GOLD        = { 0.980, 0.851, 0.565 },  -- #FAD990 main accent
    GOLD_DEEP   = { 0.722, 0.537, 0.165 },  -- #B8892A
    TEXT        = { 0.910, 0.894, 0.847 },  -- #E8E4D8
    TEXT_DIM    = { 0.776, 0.800, 0.839 },  -- #C6CCD6
    WHITE       = { 1, 1, 1 },
    GREEN       = { 0.498, 0.851, 0.604 },  -- #7FD99A
    GREEN_DEEP  = { 0.180, 0.490, 0.298 },  -- #2E7D4C
    RED         = { 0.941, 0.541, 0.502 },  -- #F08A80
    RED_DEEP    = { 0.659, 0.227, 0.188 },  -- #A83A30
    BLUE        = { 0.490, 0.706, 0.941 },  -- #7DB4F0
    TURQUOISE   = { 0.373, 0.827, 0.878 },  -- #5FD3E0
}

-- ------------------------------------------------------------
-- Saved variables (per character) + sanitization
-- Lesson carried over from the Loremaster Tracker: never trust
-- stored geometry — a fullscreen change can strand windows
-- off-screen. Clamp everything on load.
-- ------------------------------------------------------------
local DB_DEFAULTS = {
    settings = {
        theme        = "midnight",   -- midnight | alliance | horde
        scale        = 1.0,          -- 0.8 | 1.0 | 1.2
        sounds       = true,
        turnAlert    = true,
        minimap      = true,
    },
    window = {
        -- launcher position (CENTER-relative offsets)
        x = 0, y = 0,
        tableX = 0, tableY = 0,
        minimapAngle = 200,
    },
    ledger      = {},   -- settle-up entries: { id, when, stakes, results = { [player]=net }, transfers = { {from,to,amt,paid} } }
    leaderboard = {},   -- aggregate: [player] = { gold = n, chips = n, tables = n, handsWon = n }
    guildBoard  = {},   -- last synced guild aggregates
}

local function deepCopyDefaults(src, dst)
    for k, v in pairs(src) do
        if type(v) == "table" then
            if type(dst[k]) ~= "table" then dst[k] = {} end
            deepCopyDefaults(v, dst[k])
        elseif dst[k] == nil then
            dst[k] = v
        end
    end
end

local function sanitizeNumber(v, min, max, default)
    if type(v) ~= "number" or v ~= v or v < min or v > max then
        return default
    end
    return v
end

function KH:SanitizeDB()
    local s = self.db.settings
    if s.theme ~= "midnight" and s.theme ~= "alliance" and s.theme ~= "horde" then
        s.theme = "midnight"
    end
    s.scale = sanitizeNumber(s.scale, 0.5, 2.0, 1.0)

    local w = self.db.window
    local sw, sh = GetScreenWidth(), GetScreenHeight()
    w.x      = sanitizeNumber(w.x,      -sw / 2, sw / 2, 0)
    w.y      = sanitizeNumber(w.y,      -sh / 2, sh / 2, 0)
    w.tableX = sanitizeNumber(w.tableX, -sw / 2, sw / 2, 0)
    w.tableY = sanitizeNumber(w.tableY, -sh / 2, sh / 2, 0)
end

-- ------------------------------------------------------------
-- Event bootstrap
-- ------------------------------------------------------------
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_LOGIN")

eventFrame:SetScript("OnEvent", function(_, event, arg1)
    if event == "ADDON_LOADED" and arg1 == ADDON_NAME then
        KomoHoldEmDB = KomoHoldEmDB or {}
        KH.db = KomoHoldEmDB
        deepCopyDefaults(DB_DEFAULTS, KH.db)
        KH:SanitizeDB()
    elseif event == "PLAYER_LOGIN" then
        KH.playerName  = UnitName("player")
        KH.playerFull  = KH.playerName .. "-" .. GetNormalizedRealmName()
        KH.Comms:Init()
        KH.Ledger:Init()
        KH.Lobby:Init()
        KH.Host:Init()
        KH.Client:Init()
        KH.Minimap:Refresh()
        KH:Print("v" .. KH.VERSION .. " loaded. |cfffad990/kh|r to open.")
    end
end)

-- ------------------------------------------------------------
-- Chat output
-- ------------------------------------------------------------
-- realm-format tolerant self check: senders may arrive as "Name",
-- "Name-Realm", or "Name-NormalizedRealm" depending on path
function KH:IsMe(sender)
    if not sender then return false end
    local name, realm = strsplit("-", sender)
    if name ~= KH.playerName then return false end
    if not realm or realm == "" then return true end
    local norm = GetNormalizedRealmName() or ""
    local mine = (GetRealmName() or ""):gsub("[%s%-']", "")
    realm = realm:gsub("[%s%-']", "")
    return realm == norm or realm == mine
end

function KH:Print(msg)
    DEFAULT_CHAT_FRAME:AddMessage("|cfffad990Komo Hold'Em:|r " .. tostring(msg))
end

function KH:Debug(msg)
    if self.debugMode then
        DEFAULT_CHAT_FRAME:AddMessage("|cff5fd3e0KH-debug:|r " .. tostring(msg))
    end
end

-- ------------------------------------------------------------
-- Slash commands
-- ------------------------------------------------------------
SLASH_KOMOHOLDEM1 = "/kh"
SLASH_KOMOHOLDEM2 = "/komoholdem"

SlashCmdList.KOMOHOLDEM = function(input)
    local cmd, rest = input:match("^(%S*)%s*(.-)$")
    cmd = cmd:lower()

    if cmd == "" then
        KH.Launcher:Toggle()
    elseif cmd == "host" then
        KH.Launcher:Show("host")
    elseif cmd == "join" then
        KH.Launcher:Show("home")
    elseif cmd == "theme" then
        rest = rest:lower()
        if rest == "midnight" or rest == "alliance" or rest == "horde" then
            KH.db.settings.theme = rest
            KH:Print("Theme set to " .. rest .. ".")
            if KH.Table and KH.Table.ApplyTheme then KH.Table:ApplyTheme() end
        else
            KH:Print("Themes: midnight, alliance, horde")
        end
    elseif cmd == "soundtest" then
        KH.Sounds:RunTest()
    elseif cmd == "demo" then
        KH.Client:Demo()
    elseif cmd == "minimap" then
        KH.Minimap:Toggle()
    elseif cmd == "close" then
        KH.Lobby:CloseTable()
        if KH.Launcher and KH.Launcher.frame and KH.Launcher.frame:IsShown() then
            KH.Launcher:ShowHome()
        end
    elseif cmd == "leave" then
        if KH.Lobby.mine then
            KH.Lobby:CloseTable()
            if KH.Launcher and KH.Launcher.frame and KH.Launcher.frame:IsShown() then
                KH.Launcher:ShowHome()
            end
        else
            KH.Client:LeaveTable()
        end
    elseif cmd == "debug" then
        KH.debugMode = not KH.debugMode
        KH:Print("Debug " .. (KH.debugMode and "ON" or "OFF"))
    else
        KH:Print("Commands: /kh · /kh host · /kh join · /kh close · /kh leave · /kh demo · /kh minimap · /kh theme <name> · /kh soundtest")
    end
end
