import { useEffect, useMemo, useState, type RefObject } from "react"; import StepProgress from "./StepProgress"; import type { SessionStep } from "../lib/api"; interface WalkthroughPlayerProps { steps: SessionStep[]; videoRef: RefObject; onSeekMs: (timestampMs: number) => void; onExit: () => void; } function WalkthroughPlayer({ steps, videoRef, onSeekMs, onExit }: WalkthroughPlayerProps) { const [currentStepIndex, setCurrentStepIndex] = useState(0); const [pausedForStep, setPausedForStep] = useState(false); const currentStep = useMemo(() => steps[currentStepIndex], [steps, currentStepIndex]); useEffect(() => { if (!currentStep) return; onSeekMs(currentStep.timestamp_start_ms); const video = videoRef.current; if (!video) return; setPausedForStep(false); void video.play(); }, [currentStepIndex, currentStep, onSeekMs, videoRef]); useEffect(() => { const video = videoRef.current; if (!video || !currentStep) return; const handleTimeUpdate = () => { if (pausedForStep) return; const currentMs = video.currentTime * 1000; if (currentMs >= currentStep.timestamp_end_ms) { video.pause(); setPausedForStep(true); } }; video.addEventListener("timeupdate", handleTimeUpdate); return () => video.removeEventListener("timeupdate", handleTimeUpdate); }, [videoRef, currentStep, pausedForStep]); const goToStep = (index: number) => { if (index < 0 || index >= steps.length) return; setCurrentStepIndex(index); }; const continueToNext = () => { if (currentStepIndex < steps.length - 1) { goToStep(currentStepIndex + 1); return; } onExit(); }; useEffect(() => { if (!pausedForStep) return; if (!currentStep?.autoplay) return; const timer = window.setTimeout(() => { if (currentStepIndex < steps.length - 1) { setCurrentStepIndex((index) => Math.min(index + 1, steps.length - 1)); return; } onExit(); }, 650); return () => window.clearTimeout(timer); }, [pausedForStep, currentStep?.autoplay, currentStepIndex, steps.length, onExit]); if (!currentStep || steps.length === 0) return null; return (
{currentStep.title}
{currentStep.description}
); } export default WalkthroughPlayer;