import { useEffect, useRef } from 'react'; import { useTimeLimit } from '../../hooks/useTimeLimit'; import { setCurrentVideo } from '../../services/connectionTracker'; interface VideoPlayerProps { videoId: string; videoTitle?: string; channelName?: string; onClose: () => void; } export function VideoPlayer({ videoId, videoTitle, channelName, onClose }: VideoPlayerProps) { const { limitReached, startTracking, stopTracking, remainingTime } = useTimeLimit(); const iframeRef = useRef(null); const checkLimitIntervalRef = useRef(null); useEffect(() => { // Set video info for connection tracking setCurrentVideo(videoTitle && channelName ? { title: videoTitle, channelName } : null); // Prevent body scroll document.body.style.overflow = 'hidden'; // Handle Escape key const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape') { stopTracking(); setCurrentVideo(null); onClose(); } }; window.addEventListener('keydown', handleEscape); // Start tracking time when player opens if (!limitReached) { startTracking(); } // Check limit periodically and stop video if reached checkLimitIntervalRef.current = setInterval(() => { if (limitReached && iframeRef.current) { // Stop the video by removing autoplay and reloading with paused state if (iframeRef.current.src.includes('autoplay=1')) { iframeRef.current.src = iframeRef.current.src.replace('autoplay=1', 'autoplay=0'); } stopTracking(); setCurrentVideo(null); } }, 1000); return () => { // Clear video info when player closes setCurrentVideo(null); document.body.style.overflow = 'unset'; window.removeEventListener('keydown', handleEscape); stopTracking(); if (checkLimitIntervalRef.current) { clearInterval(checkLimitIntervalRef.current); } }; }, [videoId, videoTitle, channelName, onClose, limitReached, startTracking, stopTracking]); // Stop video immediately if limit reached useEffect(() => { if (limitReached && iframeRef.current) { // Change iframe src to stop autoplay const currentSrc = iframeRef.current.src; if (currentSrc.includes('autoplay=1')) { iframeRef.current.src = currentSrc.replace('autoplay=1', 'autoplay=0'); } stopTracking(); } }, [limitReached, stopTracking]); const handleClose = () => { stopTracking(); setCurrentVideo(null); onClose(); }; return (
e.stopPropagation()} > {limitReached ? (

Daily Time Limit Reached

You've reached your daily video watching limit. Come back tomorrow!

) : ( <>
{Math.floor(remainingTime)} min remaining today