import { useEffect, useRef } from "react";
import * as Phaser from "phaser";
import { scenes } from "./scenes";
import { PhaserConfig } from "./config";

const PhaserGame = () => {
    const gameRef = useRef<Phaser.Game | null>(null);
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (gameRef.current) return;
        if (!containerRef.current) return;

        const config: Phaser.Types.Core.GameConfig = {
            type: Phaser.AUTO,
            parent: containerRef.current,
            backgroundColor: PhaserConfig.backgroundColor,
            scene: scenes,
            scale: {
                mode: Phaser.Scale.RESIZE,
                autoCenter: Phaser.Scale.CENTER_BOTH,
                width: '100%',
                height: '100%',
            },
            // No physics: this is a turn-based card game. Combat is resolved by
            // the pure-TS CombatEngine, not by an Arcade/Matter world.
        };

        gameRef.current = new Phaser.Game(config);

        return () => {
            gameRef.current?.destroy(true);
            gameRef.current = null;
        };
    }, []);

    return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />;
};

export default PhaserGame;
