import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { ReactComponent as TickIcon } from "../assets/green-tick.svg";
import styles from "./styles.module.css";
import { PhaserGame } from "../tutorial-game/PhaserGame";
import { EventBus } from "../tutorial-game/EventBus";
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 NowhereIcon } from "../assets/blocks/nowhere.svg";
import BlockSelector4 from "../block-selector-4";
import { setSelectedBlockFromTutorialForLeft, setSelectedBlockFromTutorialForRight, selectedBlockFromTutorialForLeft, selectedBlockFromTutorialForRight } from "../utils/selected-blocks-from-tutorial";
import playImage from '../assets/playbutton.svg';
const posterItemsLeft = [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: BackwardIcon, block: "moveleft", execute: async () => true },
];
const posterItemsRight = [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: BackwardIcon, block: "moveleft", execute: async () => true },
];
const staticBlockItemUp = { icon: OnTiltLeft, block: "ontiltleft", execute: async () => true };
const staticBlockItemDown = { icon: OnTiltRight, block: "ontiltright", execute: async () => true };
export function Phase3({ nextPhase }) {
    const [gameContainerDimensions, setGameContainerDimensions] = useState({ width: "40vw", height: "60vh", visibility: "hidden" });
    const [posterItemsLeftState, setPosterItemsLeftState] = useState([]);
    const [posterItemsRightState, setPosterItemsRightState] = useState([]);
    const [isSceneReady, setIsSceneReady] = useState(false);
    const [tickIconState, setTickIconState] = useState("hidden");
    const [blocksIconState, setBlocksIconState] = useState("visible");
    const phaserGameRef = useRef(null);
    const [showAreYouReady, setShowAreYouReady] = useState(false);
    useEffect(() => {
        // setting a timeinterval to check every 100ms if both controls have been set
        const checkControlsSet = setInterval(() => {
            const leftClickBlock = phaserGameRef.current?.scene?.selectedCogTiltLeftBlock?.block;
            const rightClickBlock = phaserGameRef.current?.scene?.selectedCogTiltRightBlock?.block;
            if ((leftClickBlock === "moveright" ||
                leftClickBlock === "moveleft") &&
                (rightClickBlock === "moveright" ||
                    rightClickBlock === "moveleft")) {
                setShowAreYouReady(true);
                clearInterval(checkControlsSet);
            }
        }, 100);
        return () => {
            clearInterval(checkControlsSet);
        };
    }, []);
    useEffect(() => {
        // setting the poster items for click and no click IF they exist in the game
        const leftClickBlock = selectedBlockFromTutorialForLeft;
        const rightClickBlock = selectedBlockFromTutorialForRight;
        if (leftClickBlock) {
            const index = posterItemsLeft.findIndex(item => item.block === leftClickBlock.block);
            if (index !== -1) {
                const selectedBlock = posterItemsLeft[index];
                const middleIndex = Math.floor(posterItemsLeft.length / 2);
                // remove the selected block from the poster items
                const newposterItemsClick = posterItemsLeft.filter(item => item.block !== selectedBlock.block);
                // add the selected block to the middle of the poster items
                newposterItemsClick.splice(middleIndex, 0, selectedBlock);
                setPosterItemsLeftState(newposterItemsClick);
            }
        }
        else {
            // if the left block is not set, we set the poster items to the default ones
            setPosterItemsLeftState(posterItemsLeft);
        }
        if (rightClickBlock) {
            const index = posterItemsRight.findIndex(item => item.block === rightClickBlock.block);
            if (index !== -1) {
                const selectedBlock = posterItemsRight[index];
                const middleIndex = Math.floor(posterItemsRight.length / 2);
                // remove the selected block from the poster items
                const newposterItemsRight = posterItemsRight.filter(item => item.block !== selectedBlock.block);
                // add the selected block to the middle of the poster items
                newposterItemsRight.splice(middleIndex, 0, selectedBlock);
                setPosterItemsRightState(newposterItemsRight);
            }
        }
        else {
            // if the right click block is not set, we set the poster items to the default ones
            setPosterItemsRightState(posterItemsRight);
        }
    }, []);
    useEffect(() => {
        EventBus.on('mountain-ready', (mountain) => {
            const mountainHeightScaled = mountain.height * mountain.scaleFactors.height;
            const mountainWidthScaled = mountain.width * mountain.scaleFactors.width;
            setGameContainerDimensions({
                width: mountainWidthScaled + "px",
                height: mountainHeightScaled + "px",
                visibility: "visible"
            });
            setIsSceneReady(true);
        });
        EventBus.on('current-scene-ready', (scene) => {
            setTimeout(() => {
                scene.physics.world.setBounds(0, 0, scene.scale.width, scene.scale.height);
                scene.player?.setCollideWorldBounds(true);
                // scene.spawnFlags();
                // const flag1 = scene.flags?.getChildren()[0];
                // Phaser.Actions.SetX(scene.flags?.getChildren() || [], 50 * (scene.mountain?.scaleFactors?.width || 0));
                // if (flag1) Phaser.Actions.SetY([flag1], 1200 * (scene.mountain?.scaleFactors?.height || 0));
            }, 1000);
        });
        // EventBus.on('flags-collected', (scene: PlayScene) => {
        //     if (scene.collectedFlags === 2) {
        //         setShowAreYouReady(true);
        //         // setTimeout(() => {
        //         // setBlocksIconState("animation");
        //         // phaserGameRef.current?.game?.destroy(true);
        //         // }, 1500);
        //     }
        // });
        return () => {
            // EventBus.removeListener('flags-collected');
            EventBus.removeListener('mountain-ready');
            EventBus.removeListener('current-scene-ready');
            EventBus.removeListener('player-jumped');
        };
    }, []);
    const onBlocksAnimationEnd = useCallback(() => {
        setBlocksIconState("hidden");
        setTickIconState("animation");
    }, []);
    const onTickIconAnimationEnd = useCallback(() => {
        nextPhase();
    }, []);
    const blocksIconContainerClasses = [
        styles.singleColumnContainer,
        blocksIconState === "animation" ? styles.fadeOutAnimation : "",
        blocksIconState === "hidden" ? styles.hide : ""
    ].join(" ");
    const tickIconClassNames = [
        styles.tickIconFullScreen,
        tickIconState === "animation" ? styles.fadeInAnimation : "",
        tickIconState === "hidden" ? styles.hide : "",
        tickIconState === "visible" ? styles.show : "",
    ].join(" ");
    const handleAreYouReadyClick = () => {
        setBlocksIconState("animation");
        phaserGameRef.current?.game?.destroy(true);
        setShowAreYouReady(false);
        if (phaserGameRef.current && phaserGameRef.current.scene) {
            setSelectedBlockFromTutorialForLeft(phaserGameRef.current.scene.selectedCogTiltLeftBlock);
            setSelectedBlockFromTutorialForRight(phaserGameRef.current.scene.selectedCogTiltRightBlock);
        }
    };
    return (_jsxs("div", { className: styles.singleColumnContainer, children: [showAreYouReady && _jsx("div", { className: styles.areYouReadyContainer, children: _jsx("img", { src: playImage, alt: "Play", className: styles.playButton, onClick: handleAreYouReadyClick }) }), _jsxs("div", { className: blocksIconContainerClasses, onAnimationEnd: onBlocksAnimationEnd, children: [_jsxs("div", { className: styles.doubleBlockSelectorContainer, children: [!!posterItemsLeftState.length && _jsx(BlockSelector4, { gameRef: phaserGameRef, staticBlock: "left", posterItems: posterItemsLeftState, staticBlockItem: staticBlockItemUp }), !!posterItemsRightState.length && _jsx(BlockSelector4, { gameRef: phaserGameRef, staticBlock: "right", posterItems: posterItemsRightState, staticBlockItem: staticBlockItemDown })] }), _jsx("div", { className: styles.gameContainer, style: gameContainerDimensions, children: _jsx(PhaserGame, { ref: phaserGameRef }) })] }), _jsx(TickIcon, { className: tickIconClassNames, onAnimationEnd: onTickIconAnimationEnd })] }));
}
