import { useComputed } from '@preact/signals';
import { createGameHost, type GameModule } from 'boardgame-core';
import Phaser from 'phaser';
import { h } from 'preact';
import { PhaserGame, PhaserScene } from 'boardgame-phaser';

export default function App<TState extends Record<string, unknown>>(props: { gameModule: GameModule<TState>, gameScene: { new(): Phaser.Scene } }) {

  const gameHost = useComputed(() => {
    const gameHost = createGameHost(props.gameModule);
    return { gameHost };
  });

  const scene = useComputed(() => new props.gameScene());

  const handleReset = async () => {
    const result = await gameHost.value.gameHost.start();
    console.log('Game finished!', result);
  };

  const label = useComputed(() => 
    gameHost.value.gameHost.status.value === 'running' ? '重新开始' : '开始游戏'
  );

  // Phaser 画布配置
  const phaserConfig = {
    type: Phaser.AUTO,
    width: 800,
    height: 700,
    backgroundColor: '#111827',
  };

  return (
    <div class="flex flex-col h-screen bg-gray-900">
      {/* Phaser 游戏场景 */}
      <div class="flex-1 relative flex items-center justify-center">
        <PhaserGame config={phaserConfig}>
          <PhaserScene sceneKey="RegicideGameScene" scene={scene.value} autoStart data={gameHost.value} />
        </PhaserGame>
      </div>

      {/* 底部控制栏 */}
      <div class="p-4 bg-gray-900 border-t border-gray-700 flex justify-between items-center">
        <div class="text-sm text-gray-400">
          ⚔️ Regicide - 击败所有12个敌人
        </div>
        <button
          onClick={handleReset}
          class="px-6 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 disabled:bg-gray-600 disabled:cursor-not-allowed transition-colors font-medium"
        >
          {label}
        </button>
      </div>
    </div>
  );
}
