import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { PhaserGame } from './game/PhaserGame';
import "./styles.css";
import styles from './App.module.css';
import { useCallback, useEffect, useRef, useState } from 'react';
import { EventBus } from './game/EventBus';
import { raftDisconnectedSubscriptionHelper } from './utils/raft-subscription-helpers';
import { RaftTypeE } from '@robotical/webapp-types/dist-types/src/types/raft';
import WonOverlay from './WonOverlay';
import { ReactComponent as OnTiltLeft } from "./assets/blocks/ontiltleft.svg";
import { ReactComponent as OnTiltRight } from "./assets/blocks/ontiltright.svg";
import { ReactComponent as ForwardIcon } from "./assets/blocks/forward.svg";
import { ReactComponent as BackwardIcon } from "./assets/blocks/backward.svg";
import { ReactComponent as ShootIcon } from "./assets/blocks/shoot.svg";
import { ReactComponent as NowhereIcon } from "./assets/blocks/nowhere.svg";
import { ReactComponent as OnTouchCogIcon } from "./assets/blocks/ontouchcog.svg";
import BlockSelector2 from "./block-selector";
import { selectedBlockFromTutorialForLeft, selectedBlockFromTutorialForRight } from './utils/selected-blocks-from-tutorial';
import ShouldIStayOrShouldIGo from './ShouldIStayOrShouldIGo';
import OverlayingTutorial from './overlaying-tutorial';
const staticBlockItemUp = { icon: OnTiltLeft, block: "ontiltleft", execute: async () => true };
const staticBlockItemDown = { icon: OnTiltRight, block: "ontiltright", execute: async () => true };
const staticBlockItemButton = { icon: OnTouchCogIcon, block: "ontouchcog", execute: async () => true };
const repeat = (n, array) => {
    /* Repeats every element in the array until the array length = n */
    return Array(n).fill(array).flat().slice(0, n);
};
const posterItemsForRight = repeat(12, [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: BackwardIcon, block: "moveleft", execute: async () => true },
]);
const posterItemsForLeft = repeat(12, [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: BackwardIcon, block: "moveleft", execute: async () => true },
]);
const posterItemsForShoot = repeat(12, [
    { icon: ShootIcon, block: "fire", execute: async () => true },
    { icon: NowhereIcon, block: "nowhere", execute: async () => true },
]);
// const staticBlockItemsUp: PosterItem[] = repeat(12, [
//     { icon: OnTiltLeft, block: "ontiltleft", execute: async () => true },
// ]);
// const staticBlockItemsDown: PosterItem[] = repeat(12, [
//     { icon: OnTiltRight, block: "ontiltright", execute: async () => true },
// ]);
function Skiing() {
    // const [gameContainerDimensions, setGameContainerDimensions] = useState({ width: "70vw", height: "80vh" });
    const [gameContainerDimensions, setGameContainerDimensions] = useState({ width: "720px", height: "640px" });
    const [collectedFlags, setCollectedFlags] = useState(0);
    const [collectedFlagsText, setCollectedFlagsText] = useState("");
    const [isZooming, setIsZooming] = useState(false);
    const [isZoomingCenteredScore, setIsZoomingCenteredScore] = useState(false);
    const phaserGameRef = useRef(null);
    const [connectedCog, setConnectedCog] = useState(null);
    const [isWinningFlagVisible, setIsWinningFlagVisible] = useState(false);
    const [isSceneReady, setIsSceneReady] = useState(false);
    const [posterItemsLeftState, setPosterItemsLeftState] = useState([...posterItemsForLeft]);
    const [posterItemsRightState, setPosterItemsRightState] = useState([...posterItemsForRight]);
    const [posterItemsShootState, setPosterItemsShootState] = useState([...posterItemsForShoot]);
    const [tutorialPhase, setTutorialPhase] = useState(1);
    const [shouldIStayOrShouldIGoVisible, setShouldIStayOrShouldIGoVisible] = useState(false);
    const [selectedTiltBlocks, setSelectedTiltBlocks] = useState({
        left: null,
        right: null,
        shoot: null,
    });
    const [showBlockReminder, setShowBlockReminder] = useState(false);
    const [blockReminderDismissed, setBlockReminderDismissed] = useState(false);
    const reminderTimeoutRef = useRef(null);
    const subHelper = useRef(null);
    const isTiltMappingCorrect = selectedTiltBlocks.left?.block === "moveleft" && selectedTiltBlocks.right?.block === "moveright";
    const handleBlockSelectionChange = useCallback((staticBlock, item) => {
        setSelectedTiltBlocks((prev) => ({
            ...prev,
            [staticBlock]: item,
        }));
        // Reset dismissal when user makes a new choice so we can remind again if needed.
        setBlockReminderDismissed(false);
    }, []);
    useEffect(() => {
        /* Checks if we are already connected to a cog */
        const selectedCog = window.applicationManager?.getTheCurrentlySelectedDeviceOrFirstOfItsKind(RaftTypeE.COG);
        if (selectedCog) {
            setConnectedCog(selectedCog);
            subHelper.current = raftDisconnectedSubscriptionHelper(selectedCog);
            subHelper.current.subscribe(() => {
                setConnectedCog(null);
                subHelper.current?.unsubscribe();
            });
        }
        return () => {
            subHelper.current?.unsubscribe();
        };
    }, []);
    const handleConnect = () => {
        window.applicationManager?.connectGenericCog((raft) => {
            setConnectedCog(raft);
            subHelper.current = raftDisconnectedSubscriptionHelper(raft);
            subHelper.current.subscribe(() => {
                setConnectedCog(null);
                subHelper.current?.unsubscribe();
            });
        });
    };
    const handleDisconnect = () => {
        if (connectedCog) {
            window.applicationManager?.disconnectGeneric(connectedCog);
        }
    };
    useEffect(() => {
        EventBus.on('scene-ready', (space) => {
            const spaceHeightScaled = space.scale.height;
            const spaceWidthScaled = space.scale.width;
            setGameContainerDimensions({
                width: spaceWidthScaled + "px",
                height: spaceHeightScaled + "px"
            });
            setIsSceneReady(true);
        });
        // EventBus.on('flags-lost', (scene_instance: GameScene) => {
        //     setCollectedFlags(scene_instance.collectedFlags);
        //     setCollectedFlagsText(`-1=${scene_instance.collectedFlags}`);
        // });
        EventBus.on('target-achieved', () => {
            if (!phaserGameRef.current)
                return;
            if (!phaserGameRef.current.scene)
                return;
            setIsWinningFlagVisible(true);
            setTimeout(() => {
                setIsWinningFlagVisible(false);
                setShouldIStayOrShouldIGoVisible(true);
                // window.applicationManager.carouselNavigatorManager.getNavigator("games")?.setIsVisible(true);
                // window.applicationManager.carouselNavigatorManager.getNavigator("games")?.setHighlightedItem("/maze");
            }, 2000);
        });
        EventBus.on('die', () => {
            setCollectedFlags(0);
            setTutorialPhase(3);
            setPosterItemsLeftState([]);
            setPosterItemsRightState([]);
        });
        return () => {
            EventBus.removeListener('scene-ready');
            EventBus.removeListener('die');
            EventBus.removeListener('flags-lost');
            EventBus.removeListener('target-achieved');
        };
    }, []);
    useEffect(() => {
        if (reminderTimeoutRef.current) {
            clearTimeout(reminderTimeoutRef.current);
            reminderTimeoutRef.current = null;
        }
        if (!isSceneReady) {
            setShowBlockReminder(false);
            return;
        }
        if (tutorialPhase !== undefined) {
            setShowBlockReminder(false);
            return;
        }
        if (isTiltMappingCorrect) {
            setShowBlockReminder(false);
            setBlockReminderDismissed(false);
            return;
        }
        if (blockReminderDismissed) {
            setShowBlockReminder(false);
            return;
        }
        reminderTimeoutRef.current = setTimeout(() => {
            setShowBlockReminder(true);
        }, 10000);
        return () => {
            if (reminderTimeoutRef.current) {
                clearTimeout(reminderTimeoutRef.current);
                reminderTimeoutRef.current = null;
            }
        };
    }, [isSceneReady, tutorialPhase, isTiltMappingCorrect, blockReminderDismissed]);
    useEffect(() => {
        if (collectedFlags > 0) {
            setIsZooming(true);
            setTimeout(() => {
                setIsZooming(false);
            }, 300);
        }
    }, [collectedFlags]);
    useEffect(() => {
        if (collectedFlags > 0) {
            setIsZoomingCenteredScore(true);
            setTimeout(() => {
                setIsZoomingCenteredScore(false);
            }, 1500);
        }
    }, [collectedFlags]);
    const onPlayBtnClick = () => {
        // if cog is connected, start the game, otherwise connect a cog
        if (connectedCog) {
            // phaserGameRef.current?.scene?.handleGameStart();
        }
        else {
            handleConnect();
        }
    };
    const onTutorialFinished = () => {
        // when the tutorial is finished, we get the selected blocks from the programming phase
        // and we push them to the poster items
        // const selectedBlockLeft = selectedBlockFromTutorialForLeft;
        // const selectedBlockRight = selectedBlockFromTutorialForRight;
        // if (selectedBlockLeft) {
        //     setPosterItemsLeftState([selectedBlockLeft]);
        // }
        // if (selectedBlockRight) {
        //     setPosterItemsRightState([selectedBlockRight]);
        // }
        const selectedBlockLeft = selectedBlockFromTutorialForLeft;
        const selectedBlockRight = selectedBlockFromTutorialForRight;
        if (selectedBlockLeft) {
            const index = posterItemsForLeft.findIndex(item => item.block === selectedBlockLeft.block);
            if (index !== -1) {
                const selectedBlock = posterItemsForLeft[index];
                posterItemsForLeft.splice(index, 1);
                posterItemsForLeft.unshift(selectedBlock);
                setPosterItemsLeftState([...posterItemsForLeft]);
            }
        }
        if (selectedBlockRight) {
            const index = posterItemsForRight.findIndex(item => item.block === selectedBlockRight.block);
            if (index !== -1) {
                const selectedBlock = posterItemsForRight[index];
                posterItemsForRight.splice(index, 1);
                posterItemsForRight.unshift(selectedBlock);
                setPosterItemsRightState([...posterItemsForRight]);
            }
        }
        setTutorialPhase(undefined);
    };
    const onKeepPlaying = () => {
        setShouldIStayOrShouldIGoVisible(false);
        // setCollectedFlags(0);
        // setCollectedFlagsText("");
        // setTutorialPhase(3);
        // setPosterItemsLeftState([]);
        // setPosterItemsRightState([]);
    };
    const onGoNext = () => {
        window.applicationManager.carouselNavigatorManager.getNavigator("games")?.navigate("/maze");
    };
    return (_jsxs("div", { className: styles.App, children: [isWinningFlagVisible && _jsx(WonOverlay, {}), shouldIStayOrShouldIGoVisible && _jsx(ShouldIStayOrShouldIGo, { keepPlaying: onKeepPlaying, goNext: onGoNext }), _jsx(OverlayingTutorial, { tutorialPhase: tutorialPhase, setTutorialPhase: setTutorialPhase, onTutorialFinished: onTutorialFinished }), _jsxs("div", { className: styles.gameContainer, style: gameContainerDimensions, children: [showBlockReminder && isSceneReady && (_jsx("div", { className: styles.blockReminder, children: _jsxs("span", { className: styles.blockReminderText, children: [_jsx("span", { style: { display: "block", textDecoration: "underline", width: "100%", textAlign: 'center' }, children: "Tip: fix steering" }), _jsx("br", {}), "Tilt Left \u00A0\u00A0\u00A0\u2192\u00A0\u00A0  Move Left", _jsx("br", {}), "Tilt Right \u00A0\u2192\u00A0\u00A0 Move Right."] }) })), _jsx("div", { className: styles.blockSelectorContainer, children: _jsx("div", { className: styles.blockSelectorList, children: isSceneReady && (_jsxs(_Fragment, { children: [!!posterItemsRightState.length && _jsx(BlockSelector2, { gameRef: phaserGameRef, staticBlock: "right", posterItems: posterItemsRightState, staticBlockItems: [staticBlockItemDown], onSelectionChange: handleBlockSelectionChange }), !!posterItemsShootState.length && _jsx(BlockSelector2, { gameRef: phaserGameRef, staticBlock: "shoot", posterItems: posterItemsShootState, staticBlockItems: [staticBlockItemButton], onSelectionChange: handleBlockSelectionChange }), !!posterItemsLeftState.length && _jsx(BlockSelector2, { gameRef: phaserGameRef, staticBlock: "left", staticBlockItems: [staticBlockItemUp], posterItems: posterItemsLeftState, onSelectionChange: handleBlockSelectionChange })] })) }) }), _jsx(PhaserGame, { ref: phaserGameRef })] })] }));
}
export default Skiing;
