local MonkeyGames = LibStub("AceAddon-3.0"):GetAddon("MonkeyGames")
local L = MonkeyGames.L
local Theme = MonkeyGames.Theme
local Widgets = MonkeyGames.Widgets

local GameBrowser = {}
MonkeyGames.GameBrowser = GameBrowser

local WINDOW_WIDTH = 460
local WINDOW_HEIGHT = 560
local GAME_BUTTON_HEIGHT = 50

function GameBrowser:Toggle()
    if self.window and self.window:IsShown() then
        self.window:Hide()
    else
        if not self.window then
            self:CreateWindow()
        end
        self.window:Show()
    end
end

function GameBrowser:CreateWindow()
    local window = Widgets:CreateWindow("MonkeyGamesMainWindow", WINDOW_WIDTH, WINDOW_HEIGHT)
    self.window = window

    -- Register for Escape-to-close
    table.insert(UISpecialFrames, "MonkeyGamesMainWindow")

    -- Header bar
    self.header = Widgets:CreateHeaderBar(window, L["MonkeyGames"])

    -- Browser view container (game list + options)
    self.browserView = CreateFrame("Frame", nil, window)
    self.browserView:SetPoint("TOPLEFT", window, "TOPLEFT", 8, -38)
    self.browserView:SetPoint("BOTTOMRIGHT", window, "BOTTOMRIGHT", -8, 8)

    -- Game view container (board + controls, hidden by default)
    self.gameView = CreateFrame("Frame", nil, window)
    self.gameView:SetPoint("TOPLEFT", window, "TOPLEFT", 0, -34)
    self.gameView:SetPoint("BOTTOMRIGHT", window, "BOTTOMRIGHT", 0, 0)
    self.gameView:Hide()

    self:BuildBrowserContent()
    Widgets:RestoreWindowPosition(window)
end

function GameBrowser:BuildBrowserContent()
    local parent = self.browserView

    -- "Select a Game" header
    local header = Widgets:CreateLabel(parent, L["Select a Game"], Theme.FONT_SIZE_TITLE, Theme.TEXT_ACCENT)
    header:SetPoint("TOPLEFT", parent, "TOPLEFT", 4, -4)

    -- Game list
    local yOffset = -28
    local games = MonkeyGames.GameRegistry:GetAllGames()

    self.gameButtons = {}

    for i, gameDef in ipairs(games) do
        local btn = self:CreateGameButton(parent, gameDef, yOffset)
        yOffset = yOffset - (GAME_BUTTON_HEIGHT + 4)
        self.gameButtons[i] = btn
    end

    -- Separator
    local sep = parent:CreateTexture(nil, "ARTWORK")
    sep:SetTexture(Theme.TEX_WHITE8X8)
    sep:SetHeight(1)
    sep:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, yOffset - 4)
    sep:SetPoint("TOPRIGHT", parent, "TOPRIGHT", 0, yOffset - 4)
    sep:SetVertexColor(Theme.BORDER_COLOR[1], Theme.BORDER_COLOR[2], Theme.BORDER_COLOR[3], 0.3)
    yOffset = yOffset - 12

    -- Options panel (shown below game list)
    self.optionsPanel = CreateFrame("Frame", nil, parent)
    self.optionsPanel:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, yOffset)
    self.optionsPanel:SetPoint("TOPRIGHT", parent, "TOPRIGHT", 0, yOffset)
    self.optionsPanel:SetHeight(260)
    self.optionsPanel:Hide()

    -- Stats panel at the bottom
    self.statsPanel = CreateFrame("Frame", nil, parent)
    self.statsPanel:SetPoint("BOTTOMLEFT", parent, "BOTTOMLEFT", 0, 0)
    self.statsPanel:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", 0, 0)
    self.statsPanel:SetHeight(60)
    self:BuildStatsPanel()
end

function GameBrowser:CreateGameButton(parent, gameDef, yOffset)
    local btn = CreateFrame("Button", nil, parent, BackdropTemplateMixin and "BackdropTemplate")
    btn:SetHeight(GAME_BUTTON_HEIGHT)
    btn:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, yOffset)
    btn:SetPoint("TOPRIGHT", parent, "TOPRIGHT", 0, yOffset)

    Widgets:ApplySectionBackdrop(btn)

    -- Game icon
    local icon = btn:CreateTexture(nil, "ARTWORK")
    icon:SetSize(32, 32)
    icon:SetPoint("LEFT", btn, "LEFT", 10, 0)
    if gameDef.icon then
        icon:SetTexture(gameDef.icon)
    else
        icon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
    end

    -- Game name
    local nameText = btn:CreateFontString(nil, "OVERLAY")
    nameText:SetFont(Theme.BASE_FONT, Theme.FONT_SIZE_TITLE, "")
    nameText:SetPoint("TOPLEFT", icon, "TOPRIGHT", 8, -2)
    nameText:SetText(gameDef.name)
    nameText:SetTextColor(unpack(Theme.TEXT_ACCENT))

    -- Description
    local descText = btn:CreateFontString(nil, "OVERLAY")
    descText:SetFont(Theme.BASE_FONT, Theme.FONT_SIZE_SMALL, "")
    descText:SetPoint("TOPLEFT", nameText, "BOTTOMLEFT", 0, -2)
    descText:SetPoint("RIGHT", btn, "RIGHT", -10, 0)
    descText:SetText(gameDef.description)
    descText:SetTextColor(unpack(Theme.TEXT_DIM))
    descText:SetJustifyH("LEFT")
    descText:SetWordWrap(true)

    -- Hover effects
    btn:SetScript("OnEnter", function(self)
        self:SetBackdropColor(Theme.BUTTON_BG_HOVER[1], Theme.BUTTON_BG_HOVER[2], Theme.BUTTON_BG_HOVER[3], 0.5)
        nameText:SetTextColor(1, 1, 1, 1)
    end)
    btn:SetScript("OnLeave", function(self)
        self:SetBackdropColor(Theme.BG_COLOR[1], Theme.BG_COLOR[2], Theme.BG_COLOR[3], 0.6)
        nameText:SetTextColor(unpack(Theme.TEXT_ACCENT))
    end)

    -- Click to select game and show options
    btn:SetScript("OnClick", function()
        self:SelectGame(gameDef)
    end)

    btn.gameDef = gameDef
    return btn
end

function GameBrowser:SelectGame(gameDef)
    self.selectedGame = gameDef
    self:BuildOptionsPanel(gameDef)
    self.optionsPanel:Show()
end

function GameBrowser:BuildOptionsPanel(gameDef)
    local panel = self.optionsPanel

    -- Clear existing children
    for _, child in ipairs({ panel:GetChildren() }) do
        child:Hide()
        child:SetParent(nil)
    end

    local yOff = 0

    -- Game title
    local title = Widgets:CreateLabel(panel, gameDef.name, Theme.FONT_SIZE_TITLE, Theme.TEXT_GOLD)
    title:SetPoint("TOPLEFT", panel, "TOPLEFT", 4, yOff)
    yOff = yOff - 22

    -- --- Play vs AI section ---
    local aiHeader = Widgets:CreateLabel(panel, L["Play vs AI"], Theme.FONT_SIZE_BODY, Theme.TEXT_GREEN)
    aiHeader:SetPoint("TOPLEFT", panel, "TOPLEFT", 4, yOff)
    yOff = yOff - 20

    -- Color selection
    local colorLabel = Widgets:CreateLabel(panel, L["Play as:"], Theme.FONT_SIZE_SMALL, Theme.TEXT_LABEL)
    colorLabel:SetPoint("TOPLEFT", panel, "TOPLEFT", 8, yOff)

    self.selectedColor = "white"
    local colorBtnW = 60
    local colorBtnH = 20

    local whiteBtn = Widgets:CreateButton(panel, L["White"], colorBtnW, colorBtnH)
    whiteBtn:SetPoint("LEFT", colorLabel, "RIGHT", 8, 0)
    whiteBtn.text:SetTextColor(unpack(Theme.TEXT_GOLD))

    local blackBtn = Widgets:CreateButton(panel, L["Black"], colorBtnW, colorBtnH)
    blackBtn:SetPoint("LEFT", whiteBtn, "RIGHT", 4, 0)

    local randomBtn = Widgets:CreateButton(panel, L["Random"], colorBtnW, colorBtnH)
    randomBtn:SetPoint("LEFT", blackBtn, "RIGHT", 4, 0)

    local function UpdateColorButtons()
        whiteBtn.text:SetTextColor(self.selectedColor == "white" and Theme.TEXT_GOLD[1] or Theme.TEXT_DIM[1], self.selectedColor == "white" and Theme.TEXT_GOLD[2] or Theme.TEXT_DIM[2], self.selectedColor == "white" and Theme.TEXT_GOLD[3] or Theme.TEXT_DIM[3], 1)
        blackBtn.text:SetTextColor(self.selectedColor == "black" and Theme.TEXT_GOLD[1] or Theme.TEXT_DIM[1], self.selectedColor == "black" and Theme.TEXT_GOLD[2] or Theme.TEXT_DIM[2], self.selectedColor == "black" and Theme.TEXT_GOLD[3] or Theme.TEXT_DIM[3], 1)
        randomBtn.text:SetTextColor(self.selectedColor == "random" and Theme.TEXT_GOLD[1] or Theme.TEXT_DIM[1], self.selectedColor == "random" and Theme.TEXT_GOLD[2] or Theme.TEXT_DIM[2], self.selectedColor == "random" and Theme.TEXT_GOLD[3] or Theme.TEXT_DIM[3], 1)
    end

    whiteBtn:SetScript("OnClick", function() self.selectedColor = "white"; UpdateColorButtons() end)
    blackBtn:SetScript("OnClick", function() self.selectedColor = "black"; UpdateColorButtons() end)
    randomBtn:SetScript("OnClick", function() self.selectedColor = "random"; UpdateColorButtons() end)

    yOff = yOff - 26

    -- Difficulty selection
    local diffLabel = Widgets:CreateLabel(panel, L["Difficulty: "], Theme.FONT_SIZE_SMALL, Theme.TEXT_LABEL)
    diffLabel:SetPoint("TOPLEFT", panel, "TOPLEFT", 8, yOff)

    self.selectedDifficulty = MonkeyGames.db.profile.AI.defaultDifficulty

    local diffNames = { L["Easy"], L["Medium"], L["Hard"] }
    local diffBtns = {}

    for i = 1, 3 do
        diffBtns[i] = Widgets:CreateButton(panel, diffNames[i], 60, 20)
        if i == 1 then
            diffBtns[i]:SetPoint("LEFT", diffLabel, "RIGHT", 8, 0)
        else
            diffBtns[i]:SetPoint("LEFT", diffBtns[i - 1], "RIGHT", 4, 0)
        end
    end

    local function UpdateDiffButtons()
        for i = 1, 3 do
            local active = (self.selectedDifficulty == i)
            diffBtns[i].text:SetTextColor(
                active and Theme.TEXT_GOLD[1] or Theme.TEXT_DIM[1],
                active and Theme.TEXT_GOLD[2] or Theme.TEXT_DIM[2],
                active and Theme.TEXT_GOLD[3] or Theme.TEXT_DIM[3], 1
            )
        end
    end

    for i = 1, 3 do
        diffBtns[i]:SetScript("OnClick", function()
            self.selectedDifficulty = i
            UpdateDiffButtons()
        end)
    end
    UpdateDiffButtons()

    yOff = yOff - 30

    -- Play button
    local playBtn = Widgets:CreateButton(panel, L["Play vs AI"], 140, 28)
    playBtn:SetPoint("TOPLEFT", panel, "TOPLEFT", 8, yOff)
    playBtn.text:SetTextColor(unpack(Theme.TEXT_GREEN))
    playBtn:SetScript("OnClick", function()
        local color = self.selectedColor
        if color == "random" then
            color = (math.random(2) == 1) and "white" or "black"
        end
        MonkeyGames.GameManager:StartNewGame(gameDef.name, "ai", {
            difficulty = self.selectedDifficulty,
            localColor = color,
        })
    end)

    yOff = yOff - 40

    -- --- Challenge Player section ---
    local mpHeader = Widgets:CreateLabel(panel, L["Challenge Player"], Theme.FONT_SIZE_BODY, Theme.TEXT_GREEN)
    mpHeader:SetPoint("TOPLEFT", panel, "TOPLEFT", 4, yOff)
    yOff = yOff - 20

    -- Target name input
    local editBox = CreateFrame("EditBox", nil, panel, BackdropTemplateMixin and "BackdropTemplate")
    editBox:SetSize(180, 24)
    editBox:SetPoint("TOPLEFT", panel, "TOPLEFT", 8, yOff)
    editBox:SetAutoFocus(false)
    editBox:SetFontObject(GameFontHighlight)
    editBox:SetMaxLetters(50)

    editBox.backdropInfo = {
        bgFile = Theme.TEX_WHITE8X8,
        edgeFile = Theme.TEX_BORDER_TOOLTIP,
        edgeSize = 8,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    }
    editBox:ApplyBackdrop()
    editBox:SetBackdropColor(0.05, 0.05, 0.12, 0.8)
    editBox:SetBackdropBorderColor(unpack(Theme.BORDER_COLOR))
    editBox:SetTextInsets(6, 6, 0, 0)

    -- Placeholder text
    editBox.placeholder = editBox:CreateFontString(nil, "OVERLAY")
    editBox.placeholder:SetFont(Theme.BASE_FONT, Theme.FONT_SIZE_SMALL, "")
    editBox.placeholder:SetPoint("LEFT", 6, 0)
    editBox.placeholder:SetText(L["Enter player name..."])
    editBox.placeholder:SetTextColor(unpack(Theme.TEXT_DIM))

    editBox:SetScript("OnTextChanged", function(self)
        self.placeholder:SetShown(self:GetText() == "")
    end)
    editBox:SetScript("OnEscapePressed", function(self)
        self:ClearFocus()
    end)
    editBox:SetScript("OnEnterPressed", function(self)
        local target = self:GetText():trim()
        if target ~= "" then
            MonkeyGames.NetworkManager:SendInvite(target, gameDef.name)
        end
        self:ClearFocus()
    end)

    -- Send challenge button
    local challengeBtn = Widgets:CreateButton(panel, L["Send Challenge"], 110, 24)
    challengeBtn:SetPoint("LEFT", editBox, "RIGHT", 6, 0)
    challengeBtn:SetScript("OnClick", function()
        local target = editBox:GetText():trim()
        if target ~= "" then
            MonkeyGames.NetworkManager:SendInvite(target, gameDef.name)
        end
    end)
end

function GameBrowser:BuildStatsPanel()
    local panel = self.statsPanel

    local title = Widgets:CreateLabel(panel, L["Stats"], Theme.FONT_SIZE_BODY, Theme.TEXT_LABEL)
    title:SetPoint("TOPLEFT", panel, "TOPLEFT", 4, -4)

    self.statsWins = Widgets:CreateLabel(panel, "", Theme.FONT_SIZE_SMALL, Theme.TEXT_GREEN)
    self.statsWins:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)

    self.statsLosses = Widgets:CreateLabel(panel, "", Theme.FONT_SIZE_SMALL, Theme.TEXT_ERROR)
    self.statsLosses:SetPoint("LEFT", self.statsWins, "RIGHT", 12, 0)

    self.statsDraws = Widgets:CreateLabel(panel, "", Theme.FONT_SIZE_SMALL, Theme.TEXT_GOLD)
    self.statsDraws:SetPoint("LEFT", self.statsLosses, "RIGHT", 12, 0)

    self:RefreshStats()
end

function GameBrowser:RefreshStats()
    if not self.statsWins then return end

    local gameName = self.selectedGame and self.selectedGame.dbKey or "Chess"
    local stats = MonkeyGames.db.char.Stats[gameName]
    if not stats then
        stats = { wins = 0, losses = 0, draws = 0 }
    end

    self.statsWins:SetText(L["Wins: "] .. stats.wins)
    self.statsLosses:SetText(L["Losses: "] .. stats.losses)
    self.statsDraws:SetText(L["Draws: "] .. stats.draws)
end

--- Show the game UI (board + controls) and hide the browser.
function GameBrowser:ShowGameView(gameName)
    if not self.window then
        self:CreateWindow()
    end

    self.browserView:Hide()
    self.gameView:Show()
    self.window:Show()

    -- Clean up old game UI
    if MonkeyGames.activeGameUI and MonkeyGames.activeGameUI.Destroy then
        MonkeyGames.activeGameUI:Destroy()
    end
    if MonkeyGames.activeGameControls then
        MonkeyGames.GameControls:Destroy()
    end

    -- Create the game-specific UI
    local gameDef = MonkeyGames.GameRegistry:GetGame(gameName)
    if gameDef and gameDef.createUIFunc then
        gameDef.createUIFunc(self.gameView)
    end

    -- Create controls bar
    MonkeyGames.GameControls:Create(self.gameView)
end

--- Switch back to the browser view.
function GameBrowser:ShowBrowserView()
    if MonkeyGames.activeGameUI and MonkeyGames.activeGameUI.Destroy then
        MonkeyGames.activeGameUI:Destroy()
    end
    if MonkeyGames.activeGameControls then
        MonkeyGames.GameControls:Destroy()
    end

    self.gameView:Hide()
    self.browserView:Show()
    self:RefreshStats()
end
