local MonkeyGames = LibStub("AceAddon-3.0"):NewAddon("MonkeyGames", "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0", "AceComm-3.0", "AceSerializer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("MonkeyGames")

-- Expose addon globally for modules
_G.MonkeyGames = MonkeyGames
MonkeyGames.L = L

local defaults = {
    profile = {
        Theme = {
            opacity = 0.9,
        },
        Window = {
            x = 0,
            y = 0,
            width = 460,
            height = 560,
            locked = false,
        },
        AI = {
            defaultDifficulty = 2, -- 1=Easy, 2=Medium, 3=Hard
        },
    },
    char = {
        ActiveGame = nil,
        GameHistory = {},
        Stats = {
            Chess = { wins = 0, losses = 0, draws = 0 },
            Blackjack = { wins = 0, losses = 0, draws = 0 },
            Checkers = { wins = 0, losses = 0, draws = 0 },
            SnakesAndLadders = { wins = 0, losses = 0, draws = 0 },
        },
        ShowingBrowser = false,
    },
}

function MonkeyGames:ChatPrint(str)
    DEFAULT_CHAT_FRAME:AddMessage("[MonkeyGames] " .. tostring(str), 0.25, 1.0, 0.25)
end

function MonkeyGames:ErrorPrint(str)
    DEFAULT_CHAT_FRAME:AddMessage("[MonkeyGames Error] " .. tostring(str), 1.0, 0.5, 0.5)
end

function MonkeyGames:DebugPrint(str)
    if self.debugMode then
        DEFAULT_CHAT_FRAME:AddMessage("[MonkeyGames Debug] " .. tostring(str), 0.75, 1.0, 0.25)
    end
end

function MonkeyGames:OnInitialize()
    self.db = LibStub("AceDB-3.0"):New("MonkeyGamesDB", defaults, true)
    self:RegisterChatCommand("hg", "SlashCommand")
    self:RegisterChatCommand("hearthgames", "SlashCommand")
end

function MonkeyGames:OnEnable()
    self.NetworkManager:Initialize()
    self.GameManager:Initialize()

    -- Resume a saved game if one exists
    if self.db.char.ActiveGame then
        self.GameManager:ResumeGame(self.db.char.ActiveGame)
    end
end

function MonkeyGames:OnDisable()
    -- Save active game state for resume
    if self.GameManager and self.GameManager.activeGame then
        self.db.char.ActiveGame = self.GameManager:SerializeGameState()
    end
end

function MonkeyGames:SlashCommand(input)
    input = (input or ""):trim():lower()
    if input == "" then
        self.GameBrowser:Toggle()
    elseif input == "resign" then
        self.GameManager:Resign()
    elseif input == "draw" then
        self.NetworkManager:SendDrawOffer()
    elseif input == "debug" then
        self.debugMode = not self.debugMode
        self:ChatPrint("Debug mode: " .. (self.debugMode and "ON" or "OFF"))
    else
        self:ChatPrint("Usage: /hg - Open game browser")
        self:ChatPrint("  /hg resign - Resign current game")
        self:ChatPrint("  /hg draw - Offer a draw")
    end
end
