import React, { useState } from "react";
import { AppScreen } from "@/bindings";
import { useTauriEvent } from "@/lib/hooks";
import SetupScreen from "./SetupScreen";
import MenuScreen from "./MenuScreen";
import LobbyScreen from "./LobbyScreen";
import GameScreen from "./GameScreen";
import { flushSync } from "react-dom";

function ScreenRouter({ screen }: { screen: AppScreen }) {
    switch (screen) {
        case "Setup":
            return <SetupScreen />;
        case "Menu":
            return <MenuScreen />;
        case "Lobby":
            return <LobbyScreen />;
        case "Game":
            return <GameScreen />;
        default:
            return <p>???</p>;
    }
}

export default function App({ initialScreen }: { initialScreen: AppScreen }) {
    const [currentScreen, setScreen] = useState(initialScreen);

    useTauriEvent("changeScreen", (newScreen) => {
        const update = () => {
            setScreen(newScreen);
        };

        if (document.startViewTransition) {
            document.startViewTransition(() => flushSync(update));
        } else {
            update();
        }
    });

    return (
        <>
            <ScreenRouter screen={currentScreen} />
        </>
    );
}
