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 { getConnectedCog, hasMartyWebAppHost } from "../utils/CogManager";
import TiltGauge from "../TiltGauge";
import { FallbackTiltButton, SuccessBadge, TutorialFrame } from "./TutorialFrame";
export function GaugePhase({ nextPhase, BlocksConnectedIcon, initialBlock, blocksGif, stepIndex, title, hint, fallbackLabel, fallbackKey, }) {
    const tiltGaugeRef = useRef(null);
    const [blocksIconState, setBlocksIconState] = useState("visible");
    const [isComplete, setIsComplete] = useState(false);
    const [shouldShowFallbackButton] = useState(() => !hasMartyWebAppHost() && !getConnectedCog());
    const completionStarted = useRef(false);
    const nextPhaseTimeoutRef = useRef();
    const completeStep = useCallback(() => {
        if (completionStarted.current)
            return;
        completionStarted.current = true;
        tiltGaugeRef.current?.setScore(1);
        setBlocksIconState("animation");
        setIsComplete(true);
        nextPhaseTimeoutRef.current = window.setTimeout(nextPhase, 900);
    }, [nextPhase]);
    const runFallbackTilt = useCallback(() => {
        completeStep();
    }, [completeStep]);
    useEffect(() => {
        if (blocksIconState !== "visible") {
            return;
        }
        const intervalId = window.setInterval(() => {
            const connectedCog = getConnectedCog();
            if (!connectedCog)
                return;
            const cog = connectedCog;
            const { ay, ax } = cog.raftStateInfo.accelerometer;
            const rawTilt = Math.atan2(ay, -ax) - Math.PI / 2;
            const normalisedTilt = normaliseTiltScore(rawTilt, initialBlock.block);
            tiltGaugeRef.current?.setScore(normalisedTilt);
            if (normalisedTilt > 0.95) {
                completeStep();
            }
        }, 200);
        return () => window.clearInterval(intervalId);
    }, [blocksIconState, completeStep, initialBlock.block]);
    useEffect(() => {
        if (!shouldShowFallbackButton)
            return;
        const handleKeyDown = (event) => {
            if (event.key === fallbackKey) {
                runFallbackTilt();
            }
        };
        window.addEventListener("keydown", handleKeyDown);
        return () => window.removeEventListener("keydown", handleKeyDown);
    }, [fallbackKey, runFallbackTilt, shouldShowFallbackButton]);
    useEffect(() => {
        return () => {
            if (nextPhaseTimeoutRef.current) {
                window.clearTimeout(nextPhaseTimeoutRef.current);
            }
        };
    }, []);
    const blocksIconContainerClasses = [
        styles.tiltPracticeContainer,
        blocksIconState === "animation" ? styles.fadeOutAnimation : "",
    ].join(" ");
    return (_jsx(TutorialFrame, { stepIndex: stepIndex, title: title, hint: hint, controls: shouldShowFallbackButton
            ? _jsx(FallbackTiltButton, { onPress: runFallbackTilt, disabled: isComplete, label: fallbackLabel })
            : null, badge: isComplete ? _jsx(SuccessBadge, { TickIcon: TickIcon }) : null, children: _jsxs("div", { className: blocksIconContainerClasses, children: [_jsx("div", { className: styles.tiltVisualFocus, children: _jsx("img", { src: blocksGif, alt: "", className: styles.blocksGif }) }), _jsxs("div", { className: styles.gaugeContainer, "aria-hidden": "true", children: [_jsx(BlocksConnectedIcon, { className: styles.commandIcon }), _jsx(TiltGauge, { ref: tiltGaugeRef, title: "" })] })] }) }));
}
function normaliseTiltScore(rawTilt, block) {
    const clampedTilt = Math.max(-1.4, Math.min(1.4, rawTilt));
    if (block === "tiltleft") {
        if (clampedTilt >= 0) {
            return 0;
        }
        return Math.min(1, Math.abs(clampedTilt) / 1.4);
    }
    if (block === "tiltright") {
        if (clampedTilt <= 0) {
            return 0;
        }
        return Math.min(1, clampedTilt / 1.4);
    }
    return 0;
}
