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

/**
 * useVideoDurations — Probes actual video durations for scenes that contain
 * user-uploaded videos.
 *
 * Detects two kinds of video sources:
 * 1. Form-sourced segments (intro/outro with segmentSource='form')
 *    → fieldData key: "segment-{scene.id}"
 * 2. Editable-slot video fields inside content scenes
 *    → fieldData key: field.id
 *
 * Returns a map of sceneId → duration (seconds). When a video is uploaded,
 * its actual duration overrides the static scene.durationSeconds in
 * getTemplateDuration and compileExpressToTimeline.
 */
export function useVideoDurations(
  template: ExpressTemplate | null,
  fieldData: Record<string, string>,
): Record<string, number> {
  const [durations, setDurations] = useState<Record<string, number>>({});

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

    // Collect all (sceneId, videoUrl) pairs to probe
    const toProbe: { sceneId: string; videoUrl: string }[] = [];

    for (const scene of template.scenes) {
      // 1. Form-sourced segments (intro/outro)
      if (scene.segmentSource === 'form') {
        const fieldId = `segment-${scene.id}`;
        const videoUrl = fieldData[fieldId];
        if (videoUrl && videoUrl.trim()) {
          toProbe.push({ sceneId: scene.id, videoUrl });
          continue;
        }
      }

      // 2. Editable-slot video fields inside any scene
      const fields = scene.fields ?? [];
      for (const field of fields) {
        if (
          field.type === 'video' &&
          field.nature === 'editable-slot'
        ) {
          const videoUrl = fieldData[field.id];
          if (videoUrl && videoUrl.trim()) {
            toProbe.push({ sceneId: scene.id, videoUrl });
            break; // One video per scene is enough to set the duration
          }
        }
      }
    }

    // Clear stale durations for scenes that no longer have a video
    const activeSceneIds = new Set(toProbe.map(p => p.sceneId));
    setDurations(prev => {
      const cleaned = { ...prev };
      let changed = false;
      for (const key of Object.keys(cleaned)) {
        if (!activeSceneIds.has(key)) {
          delete cleaned[key];
          changed = true;
        }
      }
      return changed ? cleaned : prev;
    });

    // Probe each video
    for (const { sceneId, videoUrl } of toProbe) {
      const video = document.createElement('video');
      video.preload = 'metadata';

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

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

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

  return durations;
}
