import { _decorator, Component, Node, Label, Button } from 'cc';
import { WoodenManGame, GamePhase } from './WoodenManGame';
const { ccclass, property } = _decorator;

@ccclass('WoodenManUI')
export class WoodenManUI extends Component {
    @property(WoodenManGame)
    game: WoodenManGame | null = null;

    @property(Label)
    roundLabel: Label | null = null;

    @property(Label)
    timerLabel: Label | null = null;

    @property(Node)
    stepButtons: Node | null = null;

    @property(Label)
    statusLabel: Label | null = null;

    @property(Label)
    dollStateLabel: Label = null;  // 木头人状态提示

    private localPlayerId = 0; // 本地玩家ID

    start() {
        this.initUI();
    }

    private initUI() {
        // 初始化步数选择按钮
        if (this.stepButtons) {
            for (let i = 1; i <= 6; i++) {
                const button = this.stepButtons.getChildByName(`Step${i}`)?.getComponent(Button);
                if (button) {
                    button.node.on('click', () => this.onStepSelected(i));
                }
            }
        }
    }

    update() {
        if (!this.game) return;

        const gameState = this.game.getGameState();

        // 更新回合显示
        if (this.roundLabel) {
            this.roundLabel.string = `Round: ${gameState.currentRound}/15`;
        }

        // 更新计时器
        if (this.timerLabel) {
            this.timerLabel.string = `Time: ${Math.ceil(gameState.remainingTime)}s`;
        }

        // 更新状态文本
        if (this.statusLabel) {
            const player = gameState.players.find(p => p.id === this.localPlayerId);
            if (player) {
                this.statusLabel.string = `Position: ${player.position}m\nState: ${this.getStateText(player.state)}`;
            }
        }

        // 更新木头人状态
        if (this.game.getCurrentPhase() === GamePhase.MOVING) {
            this.dollStateLabel.string = "木头人转身了!";
        } else {
            this.dollStateLabel.string = "123木头人...";
        }
    }

    private getStateText(state: number): string {
        switch (state) {
            case 0: return 'Alive';
            case 1: return 'Dead';
            case 2: return 'Qualified';
            default: return 'Unknown';
        }
    }

    private onStepSelected(steps: number) {
        if (this.game) {
            this.game.playerChooseSteps(this.localPlayerId, steps);
        }
    }
}