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 { ReactComponent as StarTarget } from './assets/star-target.svg';
import { raftDisconnectedSubscriptionHelper } from './utils/raft-subscription-helpers';
import { RaftTypeE } from '@robotical/webapp-types/dist-types/src/types/raft';
import OverlayingTutorial from './overlaying-tutorial';
import WonOverlay from './WonOverlay';
import { ReactComponent as StarIcon } from './assets/star.svg';
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 { selectedBlockFromTutorialForClick, selectedBlockFromTutorialForNoClick } from './utils/selected-blocks-from-tutorial';
import ShouldIStayOrShouldIGo from './ShouldIStayOrShouldIGo';
import { hasMartyWebAppHost } from './utils/CogManager';
import { FiInfo, FiX } from 'react-icons/fi';
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 staticBlockItemsUp = [
    { icon: OnTouchCogIcon, block: "ontouchcog", execute: async () => true },
];
const staticBlockItemsDown = [
    { icon: OnNoTouchCogIcon, block: "onnotouchcog", execute: async () => true },
];
function arrangeSelectedBlock(items, selectedBlock) {
    const index = items.findIndex(item => item.block === selectedBlock.block);
    if (index === -1)
        return items;
    const selectedItem = items[index];
    const middleIndex = Math.floor(items.length / 2);
    const nextItems = items.filter(item => item.block !== selectedItem.block);
    nextItems.splice(middleIndex, 0, selectedItem);
    return nextItems;
}
function RoboFly() {
    const [gameContainerDimensions, setGameContainerDimensions] = useState({ width: "80vw", height: "60vh" });
    const [collectedStars, setCollectedStars] = useState(0);
    const [isZooming, setIsZooming] = useState(false);
    const [starFeedbackId, setStarFeedbackId] = useState(0);
    const phaserGameRef = useRef(null);
    const [connectedCog, setConnectedCog] = useState(null);
    const [isWinningFlagVisible, setIsWinningFlagVisible] = useState(false);
    const [posterItemsClickState, setPosterItemsClickState] = useState([]);
    const [posterItemsNoClickState, setPosterItemsNoClickState] = useState([]);
    const [selectedClickBlock, setSelectedClickBlock] = useState(posterItemsClick[0]);
    const [selectedNoClickBlock, setSelectedNoClickBlock] = useState(posterItemsNoClick[2]);
    const [shouldIStayOrShouldIGoVisible, setShouldIStayOrShouldIGoVisible] = useState(false);
    const [isInfoModalOpen, setIsInfoModalOpen] = useState(false);
    const [hasHostApp] = useState(() => hasMartyWebAppHost());
    const subHelper = useRef(null);
    const targetAchievedTimeoutRef = useRef();
    const wasGameRunningBeforeInfoModalRef = useRef(false);
    const fallbackPressIntervalRef = useRef();
    useEffect(() => {
        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();
        };
    }, []);
    useEffect(() => {
        const handleSkyReady = (sky) => {
            setGameContainerDimensions({
                width: sky.displayWidth + "px",
                height: sky.displayHeight + "px"
            });
        };
        const handleStarCollected = (sceneInstance) => {
            setCollectedStars(sceneInstance.collectedStars);
            setStarFeedbackId(feedbackId => feedbackId + 1);
        };
        const handleTargetAchieved = () => {
            if (!phaserGameRef.current?.scene)
                return;
            setIsWinningFlagVisible(true);
            targetAchievedTimeoutRef.current = window.setTimeout(() => {
                setIsWinningFlagVisible(false);
                setShouldIStayOrShouldIGoVisible(true);
            }, 2000);
        };
        const handleDie = () => {
            setCollectedStars(0);
        };
        EventBus.on('sky-ready', handleSkyReady);
        EventBus.on('star-collected', handleStarCollected);
        EventBus.on('target-achieved', handleTargetAchieved);
        EventBus.on('die', handleDie);
        return () => {
            EventBus.removeListener('sky-ready', handleSkyReady);
            EventBus.removeListener('die', handleDie);
            EventBus.removeListener('star-collected', handleStarCollected);
            EventBus.removeListener('target-achieved', handleTargetAchieved);
            if (targetAchievedTimeoutRef.current) {
                window.clearTimeout(targetAchievedTimeoutRef.current);
            }
        };
    }, []);
    useEffect(() => {
        if (collectedStars > 0) {
            setIsZooming(true);
            const timeout = window.setTimeout(() => {
                setIsZooming(false);
            }, 300);
            return () => window.clearTimeout(timeout);
        }
    }, [collectedStars]);
    useEffect(() => {
        if (!isInfoModalOpen)
            return;
        const sceneWhenOpened = phaserGameRef.current?.scene;
        wasGameRunningBeforeInfoModalRef.current = !!sceneWhenOpened?.isGameRunning;
        if (sceneWhenOpened?.sys && sceneWhenOpened.isGameRunning) {
            sceneWhenOpened.isGameRunning = false;
            sceneWhenOpened.physics.pause();
            sceneWhenOpened.anims.pauseAll();
        }
        const handleKeyDown = (event) => {
            if (event.key === "Escape") {
                setIsInfoModalOpen(false);
            }
        };
        window.addEventListener("keydown", handleKeyDown);
        return () => {
            window.removeEventListener("keydown", handleKeyDown);
            const scene = sceneWhenOpened;
            if (wasGameRunningBeforeInfoModalRef.current && scene?.sys && !scene.isGameOverVisible) {
                scene.physics.resume();
                scene.anims.resumeAll();
                scene.isGameRunning = true;
            }
            wasGameRunningBeforeInfoModalRef.current = false;
        };
    }, [isInfoModalOpen]);
    useEffect(() => {
        return () => {
            if (fallbackPressIntervalRef.current) {
                window.clearInterval(fallbackPressIntervalRef.current);
            }
        };
    }, []);
    const applySelectedBlocksToScene = useCallback((scene) => {
        scene.selectedCogClickedBlock = selectedClickBlock;
        scene.selectedCogNoClickBlock = selectedNoClickBlock;
    }, [selectedClickBlock, selectedNoClickBlock]);
    const onTutorialFinished = (tutorialSelections) => {
        const selectedBlockClick = tutorialSelections?.click || selectedBlockFromTutorialForClick || posterItemsClick[0];
        const selectedBlockNoClick = tutorialSelections?.noClick || selectedBlockFromTutorialForNoClick || posterItemsNoClick[2];
        const nextClickItems = arrangeSelectedBlock(posterItemsClick, selectedBlockClick);
        const nextNoClickItems = arrangeSelectedBlock(posterItemsNoClick, selectedBlockNoClick);
        setPosterItemsClickState(nextClickItems);
        setPosterItemsNoClickState(nextNoClickItems);
        setSelectedClickBlock(selectedBlockClick);
        setSelectedNoClickBlock(selectedBlockNoClick);
        if (phaserGameRef.current?.scene) {
            phaserGameRef.current.scene.selectedCogClickedBlock = selectedBlockClick;
            phaserGameRef.current.scene.selectedCogNoClickBlock = selectedBlockNoClick;
            phaserGameRef.current.scene.isTutorialFinished = true;
        }
        EventBus.emit('tutorial-finished');
        window.setTimeout(() => {
            if (phaserGameRef.current?.scene && !phaserGameRef.current.scene.isGameRunning) {
                phaserGameRef.current.scene.handleGameRestart();
            }
        }, 150);
    };
    const runFallbackAction = useCallback((button) => {
        const scene = phaserGameRef.current?.scene;
        if (!scene)
            return;
        if (!scene.isGameRunning && !scene.isGameOverVisible) {
            scene.handleGameRestart();
        }
        if (!scene.isGameRunning)
            return;
        applySelectedBlocksToScene(scene);
        EventBus.emit('input-received', { source: 'fallback-button', state: button });
        scene.player?.actionDecider(button);
    }, [applySelectedBlocksToScene]);
    const startFallbackPress = useCallback((event) => {
        event.preventDefault();
        if (fallbackPressIntervalRef.current) {
            window.clearInterval(fallbackPressIntervalRef.current);
        }
        runFallbackAction("click");
        fallbackPressIntervalRef.current = window.setInterval(() => {
            runFallbackAction("click");
        }, 90);
    }, [runFallbackAction]);
    const stopFallbackPress = useCallback((event) => {
        event?.preventDefault();
        if (fallbackPressIntervalRef.current) {
            window.clearInterval(fallbackPressIntervalRef.current);
            fallbackPressIntervalRef.current = undefined;
        }
        runFallbackAction("release");
    }, [runFallbackAction]);
    const onKeepPlaying = () => {
        setShouldIStayOrShouldIGoVisible(false);
        setCollectedStars(0);
        phaserGameRef.current?.scene?.handleGameRestart();
    };
    const onGoNext = () => {
        window.applicationManager?.carouselNavigatorManager.getNavigator("games")?.navigate("/skiing-game");
    };
    const SelectedClickIcon = selectedClickBlock.icon;
    const SelectedNoClickIcon = selectedNoClickBlock.icon;
    const isMissionReady = posterItemsClickState.length > 0 && posterItemsNoClickState.length > 0;
    const shouldShowFallbackPress = !hasHostApp && !connectedCog && isMissionReady;
    const playAreaClasses = [
        styles.playArea,
        isMissionReady ? styles.playAreaWithSelector : ""
    ].join(" ");
    const gameContainerStyle = {
        ...gameContainerDimensions,
        width: isMissionReady ? `min(${gameContainerDimensions.width}, 100%)` : gameContainerDimensions.width,
    };
    return (_jsxs("div", { className: styles.App, children: [isWinningFlagVisible && _jsx(WonOverlay, {}), shouldIStayOrShouldIGoVisible && _jsx(ShouldIStayOrShouldIGo, { keepPlaying: onKeepPlaying, goNext: onGoNext }), _jsx(OverlayingTutorial, { onTutorialFinished: onTutorialFinished }), _jsxs("div", { className: playAreaClasses, children: [isMissionReady && (_jsxs("div", { className: styles.blockSelector3Container, children: [_jsx(BlockSelector4, { gameRef: phaserGameRef, posterItems: posterItemsClickState, staticBlockItem: staticBlockItemsUp[0], staticBlock: "up", onSelectedBlockChange: setSelectedClickBlock }), _jsx(BlockSelector4, { gameRef: phaserGameRef, posterItems: posterItemsNoClickState, staticBlockItem: staticBlockItemsDown[0], staticBlock: "down", onSelectedBlockChange: setSelectedNoClickBlock })] })), _jsxs("div", { className: styles.gameContainer, style: gameContainerStyle, children: [_jsxs("div", { className: styles.missionHud, children: [_jsxs("div", { className: styles.missionCluster, children: [_jsxs("div", { className: styles.progressPill, children: [_jsx(StarIcon, { className: styles.starIcon }), _jsxs("div", { className: `${styles.score} ${isZooming ? styles.zoom : ''}`, children: [collectedStars, _jsx("span", { children: "/10" })] })] }), isMissionReady && (_jsxs(_Fragment, { children: [_jsxs("div", { className: styles.commandPill, "aria-hidden": "true", children: [_jsx(OnTouchCogIcon, { className: styles.commandCogIcon }), _jsx("span", { className: styles.commandArrow, children: "\u2192" }), _jsx(SelectedClickIcon, { className: styles.commandActionIcon })] }), _jsxs("div", { className: styles.commandPill, "aria-hidden": "true", children: [_jsx(OnNoTouchCogIcon, { className: styles.commandCogIcon }), _jsx("span", { className: styles.commandArrow, children: "\u2192" }), _jsx(SelectedNoClickIcon, { className: styles.commandActionIcon })] })] })), shouldShowFallbackPress && (_jsx("button", { className: styles.fallbackPressButton, type: "button", onPointerDown: startFallbackPress, onPointerUp: stopFallbackPress, onPointerCancel: stopFallbackPress, onPointerLeave: stopFallbackPress, children: "Press" }))] }), _jsxs("div", { className: styles.hudActions, children: [isMissionReady && (_jsx("button", { className: styles.infoButton, type: "button", "aria-label": "Game instructions", title: "Game instructions", onClick: () => setIsInfoModalOpen(true), children: _jsx(FiInfo, { "aria-hidden": "true" }) })), _jsx("div", { className: styles.targetPill, "aria-hidden": "true", children: _jsx(StarTarget, { className: styles.starTargetIcon }) })] })] }), isMissionReady && isInfoModalOpen && (_jsx("div", { className: styles.infoModalBackdrop, role: "presentation", onClick: () => setIsInfoModalOpen(false), children: _jsxs("div", { className: styles.infoModalPanel, role: "dialog", "aria-modal": "true", "aria-labelledby": "robofly-game-info-title", onClick: (event) => event.stopPropagation(), children: [_jsxs("div", { className: styles.infoModalHeader, children: [_jsx("h2", { id: "robofly-game-info-title", children: "How To Play" }), _jsx("button", { className: styles.infoCloseButton, type: "button", "aria-label": "Close instructions", onClick: () => setIsInfoModalOpen(false), children: _jsx(FiX, { "aria-hidden": "true" }) })] }), _jsxs("div", { className: styles.infoModalSteps, children: [_jsxs("div", { className: styles.infoStep, children: [_jsx("div", { className: styles.infoStepIcon, children: _jsx(OnTouchCogIcon, { "aria-hidden": "true" }) }), _jsx("p", { children: "Press or hold Cog to run the touch action." })] }), _jsxs("div", { className: styles.infoStep, children: [_jsx("div", { className: styles.infoStepIcon, children: _jsx(OnNoTouchCogIcon, { "aria-hidden": "true" }) }), _jsx("p", { children: "Release Cog to run the no-touch action." })] }), _jsxs("div", { className: styles.infoStep, children: [_jsx("div", { className: styles.infoStepIcon, children: _jsx(StarIcon, { "aria-hidden": "true" }) }), _jsx("p", { children: "Collect 10 stars while avoiding the cogs." })] })] })] }) })), starFeedbackId > 0 && (_jsx("div", { className: styles.starFeedback, "aria-hidden": "true", children: "+1" }, starFeedbackId)), _jsx(PhaserGame, { ref: phaserGameRef })] })] })] }));
}
export default RoboFly;
