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

local GameControls = {}
MonkeyGames.GameControls = GameControls

--- Create the game control bar (status text + action buttons).
-- @param parent  Parent frame to anchor to
-- @return controls  The control bar object
function GameControls:Create(parent)
    local controls = CreateFrame("Frame", nil, parent)
    controls:SetHeight(70)
    controls:SetPoint("BOTTOMLEFT", parent, "BOTTOMLEFT", 8, 8)
    controls:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", -8, 8)

    -- Status text (turn indicator, check, game result)
    controls.statusText = controls:CreateFontString(nil, "OVERLAY")
    controls.statusText:SetFont(Theme.BASE_FONT, Theme.FONT_SIZE_BODY, "")
    controls.statusText:SetPoint("TOP", controls, "TOP", 0, -2)
    controls.statusText:SetTextColor(unpack(Theme.TEXT_ACCENT))
    controls.statusText:SetText(L["Waiting..."])

    -- Move counter
    controls.moveText = controls:CreateFontString(nil, "OVERLAY")
    controls.moveText:SetFont(Theme.BASE_FONT, Theme.FONT_SIZE_SMALL, "")
    controls.moveText:SetPoint("TOP", controls.statusText, "BOTTOM", 0, -2)
    controls.moveText:SetTextColor(unpack(Theme.TEXT_DIM))
    controls.moveText:SetText("")

    -- Button row
    local btnY = -32
    local btnW = 80
    local btnH = 22
    local btnSpacing = 6

    -- Resign button
    controls.resignBtn = Widgets:CreateButton(controls, L["Resign"], btnW, btnH)
    controls.resignBtn:SetPoint("BOTTOMLEFT", controls, "BOTTOMLEFT", 0, 0)
    controls.resignBtn:SetScript("OnClick", function()
        if MonkeyGames.GameManager:IsPlaying() then
            StaticPopupDialogs["MONKEYGAMES_RESIGN_CONFIRM"] = {
                text = "Are you sure you want to resign?",
                button1 = "Yes",
                button2 = "No",
                OnAccept = function()
                    MonkeyGames.GameManager:Resign()
                end,
                timeout = 0,
                whileDead = true,
                hideOnEscape = true,
            }
            StaticPopup_Show("MONKEYGAMES_RESIGN_CONFIRM")
        end
    end)

    -- Draw button (multiplayer only)
    controls.drawBtn = Widgets:CreateButton(controls, L["Offer Draw"], btnW, btnH)
    controls.drawBtn:SetPoint("LEFT", controls.resignBtn, "RIGHT", btnSpacing, 0)
    controls.drawBtn:SetScript("OnClick", function()
        MonkeyGames.NetworkManager:SendDrawOffer()
    end)

    -- New Game button (shown after game over)
    controls.newGameBtn = Widgets:CreateButton(controls, L["New Game"], btnW, btnH)
    controls.newGameBtn:SetPoint("LEFT", controls.drawBtn, "RIGHT", btnSpacing, 0)
    controls.newGameBtn:SetScript("OnClick", function()
        local gm = MonkeyGames.GameManager
        if gm.activeGameDef then
            local gameName = gm.activeGameDef.name
            local mode = gm.gameMode
            local opts = {
                difficulty = gm.aiDifficulty,
                localColor = gm.localColor,
                opponentName = gm.opponentName,
            }
            gm:Reset()
            gm:StartNewGame(gameName, mode, opts)
        end
    end)
    controls.newGameBtn:Hide()

    -- Back button
    controls.backBtn = Widgets:CreateButton(controls, L["Back"], 60, btnH)
    controls.backBtn:SetPoint("BOTTOMRIGHT", controls, "BOTTOMRIGHT", 0, 0)
    controls.backBtn:SetScript("OnClick", function()
        MonkeyGames.GameManager:Reset()
        MonkeyGames.GameBrowser:ShowBrowserView()
    end)

    controls.UpdateStatus = function(self)
        GameControls:UpdateStatus()
    end

    MonkeyGames.activeGameControls = controls
    self.frame = controls
    self:UpdateStatus()

    return controls
end

function GameControls:UpdateStatus()
    local controls = self.frame
    if not controls then return end

    local gm = MonkeyGames.GameManager

    if gm:IsGameOver() then
        -- Game over state
        controls.resignBtn:Hide()
        controls.drawBtn:Hide()
        controls.newGameBtn:Show()

        local resultText
        if gm.gameResult == "win" then
            resultText = L["You win!"]
            controls.statusText:SetTextColor(unpack(Theme.TEXT_GREEN))
        elseif gm.gameResult == "loss" then
            resultText = L["You lose!"]
            controls.statusText:SetTextColor(unpack(Theme.TEXT_ERROR))
        else
            resultText = L["It's a draw!"]
            controls.statusText:SetTextColor(unpack(Theme.TEXT_GOLD))
        end
        controls.statusText:SetText(resultText)

    elseif gm:IsPlaying() then
        -- Playing state
        controls.resignBtn:Show()
        controls.newGameBtn:Hide()

        -- Only show draw button in multiplayer
        if gm.gameMode == "multiplayer" then
            controls.drawBtn:Show()
        else
            controls.drawBtn:Hide()
        end

        -- Turn indicator
        if gm.isLocalTurn then
            controls.statusText:SetText(L["Your Turn"])
            controls.statusText:SetTextColor(unpack(Theme.TEXT_GREEN))
        else
            controls.statusText:SetText(L["Opponent's Turn"])
            controls.statusText:SetTextColor(unpack(Theme.TEXT_DIM))
        end

        -- Check indicator
        if gm.activeGame and gm.activeGame.inCheck then
            local checkText = controls.statusText:GetText() .. " - " .. L["Check!"]
            controls.statusText:SetText(checkText)
            controls.statusText:SetTextColor(unpack(Theme.TEXT_ERROR))
        end
    else
        controls.resignBtn:Hide()
        controls.drawBtn:Hide()
        controls.newGameBtn:Hide()
        controls.statusText:SetText("")
    end

    -- Move counter
    controls.moveText:SetText(L["Moves: "] .. #gm.moveHistory)
end

function GameControls:Destroy()
    if self.frame then
        self.frame:Hide()
        self.frame = nil
    end
    MonkeyGames.activeGameControls = nil
end
