import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } 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 { ReactComponent as OnTouchCogIcon } from "../assets/blocks/ontouchcog.svg";
import { ReactComponent as OnNoTouchCogIcon } from "../assets/blocks/onnotouchcog.svg";
import { ReactComponent as UpIcon } from "../assets/blocks/up.svg";
import { ReactComponent as DownIcon } from "../assets/blocks/down.svg";
import { ReactComponent as NowhereIcon } from "../assets/blocks/nowhere.svg";
import BlockSelector4 from "../block-selector-4";
import { setSelectedBlockFromTutorialForClick, setSelectedBlockFromTutorialForNoClick } from "../utils/selected-blocks-from-tutorial";
import { getConnectedCog, hasMartyWebAppHost } from "../utils/CogManager";
import { CommandPair, FallbackCogButton, SuccessBadge, TutorialFrame } from "./TutorialFrame";
const posterItemsNoClick = [
    { icon: UpIcon, block: "moveup", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: DownIcon, block: "movedown", execute: async () => true },
];
const posterItemsClick = [
    { icon: UpIcon, block: "moveup", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: DownIcon, block: "movedown", execute: async () => true },
];
const staticBlockItemUp = { icon: OnTouchCogIcon, block: "ontouchcog", execute: async () => true };
const staticBlockItemDown = { icon: OnNoTouchCogIcon, block: "onnotouchcog", execute: async () => true };
const defaultClickBlock = posterItemsClick[0];
const defaultNoClickBlock = posterItemsNoClick[2];
export function Phase4({ nextPhase }) {
    const [gameContainerDimensions, setGameContainerDimensions] = useState({
        width: "min(42vw, 620px)",
        height: "min(30vh, 320px)",
        visibility: "hidden",
    });
    const [blocksIconState, setBlocksIconState] = useState("visible");
    const [isComplete, setIsComplete] = useState(false);
    const [shouldShowFallbackPress] = useState(() => !hasMartyWebAppHost() && !getConnectedCog());
    const [selectedClickBlock, setSelectedClickBlock] = useState(defaultClickBlock);
    const [selectedNoClickBlock, setSelectedNoClickBlock] = useState(defaultNoClickBlock);
    const phaserGameRef = useRef(null);
    const selectedClickBlockRef = useRef(defaultClickBlock);
    const selectedNoClickBlockRef = useRef(defaultNoClickBlock);
    const completionStarted = useRef(false);
    const nextPhaseTimeoutRef = useRef();
    const onSelectedClickBlockChange = useCallback((block) => {
        selectedClickBlockRef.current = block;
        setSelectedClickBlock(block);
    }, []);
    const onSelectedNoClickBlockChange = useCallback((block) => {
        selectedNoClickBlockRef.current = block;
        setSelectedNoClickBlock(block);
    }, []);
    const completeStep = useCallback(() => {
        if (completionStarted.current)
            return;
        completionStarted.current = true;
        const clickBlock = selectedClickBlockRef.current;
        const noClickBlock = selectedNoClickBlockRef.current;
        setSelectedBlockFromTutorialForClick(clickBlock);
        setSelectedBlockFromTutorialForNoClick(noClickBlock);
        setBlocksIconState("animation");
        setIsComplete(true);
        nextPhaseTimeoutRef.current = window.setTimeout(() => nextPhase({
            click: clickBlock,
            noClick: noClickBlock,
        }), 900);
    }, [nextPhase]);
    const setFallbackInputState = useCallback((button) => {
        const scene = phaserGameRef.current?.scene;
        if (!scene?.player || completionStarted.current)
            return;
        scene.isGameRunning = true;
        scene.previewInputState = button;
        scene.selectedCogClickedBlock = selectedClickBlockRef.current;
        scene.selectedCogNoClickBlock = selectedNoClickBlockRef.current;
    }, []);
    const startFallbackPress = useCallback((event) => {
        event.preventDefault();
        setFallbackInputState("click");
    }, [setFallbackInputState]);
    const stopFallbackPress = useCallback((event) => {
        event?.preventDefault();
        setFallbackInputState("release");
    }, [setFallbackInputState]);
    const handleCurrentSceneReady = useCallback((scene) => {
        scene.isPreviewOnly = true;
        scene.isGameRunning = true;
        scene.previewInputState = "release";
        scene.physics.resume();
        scene.anims.resumeAll();
        scene.selectedCogClickedBlock = selectedClickBlockRef.current;
        scene.selectedCogNoClickBlock = selectedNoClickBlockRef.current;
        scene.obstacles?.clear(true, true);
        scene.stars?.clear(true, true);
        scene.shinyStars?.clear(true, true);
        scene.gameOverContainer?.setAlpha(0);
        scene.isGameOverVisible = false;
        scene.sky?.scaleToFit();
        scene.ground?.scaleToFit();
        scene.ground?.positionOnSky();
        scene.player?.setTexture("marty-in-plane");
        scene.player?.scaleToFit();
        scene.player?.positionOnSky();
        setGameContainerDimensions(currentDimensions => ({
            ...currentDimensions,
            visibility: "visible"
        }));
    }, []);
    useEffect(() => {
        return () => {
            if (nextPhaseTimeoutRef.current) {
                window.clearTimeout(nextPhaseTimeoutRef.current);
            }
        };
    }, []);
    const blocksIconContainerClasses = [
        styles.doubleColumnContainer,
        blocksIconState === "animation" ? styles.fadeOutAnimation : "",
    ].join(" ");
    return (_jsx(TutorialFrame, { stepIndex: 0, title: "Choose Flight Controls", hint: "Pick what Robofly does while Cog is pressed, and what it does when Cog is released.", controls: _jsxs(_Fragment, { children: [_jsx(CommandPair, { CogIcon: OnTouchCogIcon, ActionIcon: selectedClickBlock.icon }), _jsx(CommandPair, { CogIcon: OnNoTouchCogIcon, ActionIcon: selectedNoClickBlock.icon }), shouldShowFallbackPress ? (_jsx("button", { className: styles.fallbackButton, type: "button", onPointerDown: startFallbackPress, onPointerUp: stopFallbackPress, onPointerCancel: stopFallbackPress, onPointerLeave: stopFallbackPress, disabled: isComplete, children: "Press" })) : null, _jsx(FallbackCogButton, { onPress: completeStep, disabled: isComplete, label: "Continue" })] }), badge: isComplete ? _jsx(SuccessBadge, { TickIcon: TickIcon }) : null, children: _jsxs("div", { className: blocksIconContainerClasses, children: [_jsxs("div", { className: `${styles.doubleBlockSelectorContainer} ${styles.selectorFocusAnchor}`, children: [_jsx(BlockSelector4, { gameRef: phaserGameRef, staticBlock: "up", posterItems: posterItemsClick, staticBlockItem: staticBlockItemUp, onSelectedBlockChange: onSelectedClickBlockChange, initialSelectedIndex: 0 }), _jsx(BlockSelector4, { gameRef: phaserGameRef, staticBlock: "down", posterItems: posterItemsNoClick, staticBlockItem: staticBlockItemDown, onSelectedBlockChange: onSelectedNoClickBlockChange, initialSelectedIndex: 2 })] }), _jsx("div", { className: styles.gameContainer, style: gameContainerDimensions, children: _jsx(PhaserGame, { ref: phaserGameRef, currentActiveScene: handleCurrentSceneReady }) })] }) }));
}
