import { useState, useEffect } from 'react';
import { ExpressTemplate } from '../types';

/**
 * useVideoDurations — Probes actual video durations for form-sourced scenes.
 *
 * When a user uploads a video to a form field, this hook creates a temporary
 * <video> element to read its metadata and returns the actual duration in seconds.
 *
 * Returns a map of sceneId → duration (seconds) for scenes whose uploaded
 * videos have been probed. Scenes without uploaded videos are not included.
 */
export function useVideoDurations(
  template: ExpressTemplate | null,
  fieldData: Record<string, string>,
): Record<string, number> {
  const [durations, setDurations] = useState<Record<string, number>>({});

  useEffect(() => {
    if (!template) return;

    // Find scenes that source video from form uploads
    const formVideoScenes = template.scenes.filter(
      s => s.segmentSource === 'form' && (s.type === 'intro' || s.type === 'outro' || s.type === 'content')
    );

    for (const scene of formVideoScenes) {
      const fieldId = `segment-${scene.id}`;
      const videoUrl = fieldData[fieldId];

      if (!videoUrl || videoUrl.trim() === '') {
        // No video uploaded — remove any stale duration
        setDurations(prev => {
          if (prev[scene.id]) {
            const { [scene.id]: _, ...rest } = prev;
            return rest;
          }
          return prev;
        });
        continue;
      }

      // Probe the video duration
      const video = document.createElement('video');
      video.preload = 'metadata';

      video.onloadedmetadata = () => {
        if (video.duration && isFinite(video.duration)) {
          setDurations(prev => ({
            ...prev,
            [scene.id]: video.duration,
          }));
        }
        video.remove();
      };

      video.onerror = () => {
        video.remove();
      };

      video.src = videoUrl;
    }
  }, [template, fieldData]);

  return durations;
}
