'use client';
import { useEffect, useRef } from 'react';
import { postCurrentTime } from '../_actions/progress';

interface Props {
    embedUrl: string;
    type: 'youtube' | 'vimeo' | null;
    sessionId: number;
    title?: string;
}

/**
 * VideoPlayer
 *
 * Renders a YouTube or Vimeo iframe and reports the real playback position
 * to the backend every 30 seconds using the respective player APIs.
 *
 * YouTube: uses the IFrame Player API (JS SDK loaded dynamically)
 * Vimeo  : uses the Vimeo Player postMessage protocol
 */
export function VideoPlayer({ embedUrl, type, sessionId, title }: Props) {
    const iframeRef = useRef<HTMLIFrameElement>(null);
    const reportIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
    const ytPlayerRef = useRef<any>(null);

    // ── Cleanup on unmount / session change ────────────────────────────────────
    useEffect(() => {
        return () => {
            if (reportIntervalRef.current) {
                clearInterval(reportIntervalRef.current);
                reportIntervalRef.current = null;
            }
            ytPlayerRef.current = null;
        };
    }, [sessionId]);

    // ── YouTube: use IFrame Player API ─────────────────────────────────────────
    useEffect(() => {
        if (type !== 'youtube') return;

        // Stop any previous interval
        if (reportIntervalRef.current) clearInterval(reportIntervalRef.current);

        const initYT = () => {
            if (!iframeRef.current) return;

            // YT.Player requires the iframe to have an id
            const iframeEl = iframeRef.current;
            if (!iframeEl.id) iframeEl.id = `yt-player-${sessionId}`;

            ytPlayerRef.current = new (window as any).YT.Player(iframeEl.id, {
                events: {
                    onReady: () => {
                        // Poll every 30 s for the actual video currentTime
                        reportIntervalRef.current = setInterval(() => {
                            const player = ytPlayerRef.current;
                            if (!player?.getCurrentTime) return;
                            const seconds = Math.floor(player.getCurrentTime());
                            postCurrentTime(sessionId, seconds);
                        }, 5_000);
                    },
                },
            });
        };

        if ((window as any).YT?.Player) {
            // API already loaded
            initYT();
        } else {
            // Load the YouTube IFrame API script once
            if (!document.getElementById('yt-iframe-api')) {
                const tag = document.createElement('script');
                tag.id = 'yt-iframe-api';
                tag.src = 'https://www.youtube.com/iframe_api';
                document.head.appendChild(tag);
            }
            // YT calls window.onYouTubeIframeAPIReady when ready
            const prev = (window as any).onYouTubeIframeAPIReady;
            (window as any).onYouTubeIframeAPIReady = () => {
                if (prev) prev();
                initYT();
            };
        }

        return () => {
            if (reportIntervalRef.current) {
                clearInterval(reportIntervalRef.current);
                reportIntervalRef.current = null;
            }
            ytPlayerRef.current?.destroy?.();
            ytPlayerRef.current = null;
        };
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [sessionId, type]);

    // ── Vimeo: use postMessage protocol ────────────────────────────────────────
    useEffect(() => {
        if (type !== 'vimeo') return;
        if (reportIntervalRef.current) clearInterval(reportIntervalRef.current);

        const iframe = iframeRef.current;
        if (!iframe) return;

        // Ask Vimeo to send us getCurrentTime every 30 s
        reportIntervalRef.current = setInterval(() => {
            iframe.contentWindow?.postMessage(
                JSON.stringify({ method: 'getCurrentTime' }),
                'https://player.vimeo.com'
            );
        }, 5_000);

        // Listen for the response
        const handleMessage = (e: MessageEvent) => {
            if (e.origin !== 'https://player.vimeo.com') return;
            try {
                const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data;
                if (data?.method === 'getCurrentTime' && typeof data?.value === 'number') {
                    const seconds = Math.floor(data.value);
                    postCurrentTime(sessionId, seconds);
                }
            } catch {
                // ignore parse errors
            }
        };

        window.addEventListener('message', handleMessage);

        return () => {
            if (reportIntervalRef.current) {
                clearInterval(reportIntervalRef.current);
                reportIntervalRef.current = null;
            }
            window.removeEventListener('message', handleMessage);
        };
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [sessionId, type]);

    // ── YouTube embed URL must include enablejsapi=1 ───────────────────────────
    // ── Vimeo embed URL must include api=1 for postMessage ────────────────────
    const finalUrl = (() => {
        if (type === 'youtube') {
            return embedUrl.includes('enablejsapi')
                ? embedUrl
                : `${embedUrl}${embedUrl.includes('?') ? '&' : '?'}enablejsapi=1`;
        }
        if (type === 'vimeo') {
            const sep = embedUrl.includes('?') ? '&' : '?';
            let url = embedUrl;
            if (!url.includes('api=1')) url += `${sep}api=1`;
            return url;
        }
        return embedUrl;
    })();

    return (
        <div className="relative w-full pb-[50%] bg-gradient-to-br rounded-lg from-gray-900 via-black to-gray-900 overflow-hidden shadow-2xl">
            <iframe
                ref={iframeRef}
                id={`player-${sessionId}`}
                src={finalUrl}
                className="absolute top-0 left-0 w-full h-full border-0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"
                allowFullScreen
                title={title}
            />
        </div>
    );
}
