import { useEffect, useState } from 'react';
import { GlitchPlayer, defaultSlideRegistry } from '../vendor/gnommoplayer/gnommoplayer.js';

/**
 * Fetches the full export payload for a video and renders GlitchPlayer
 * in slide-preview mode, paused at the target slide.
 *
 * Uses targetSlideIndex (resolved from targetSlideId) so the player works
 * even when slides have null startTimeSec — timeline activation is bypassed.
 */
export default function GlitchPlayerPanel({ videoId, targetSlideId, viewportMode = 'desktop', refreshKey }) {
  const [presentation, setPresentation] = useState(null);
  const [error, setError] = useState(null);
  const [retryCount, setRetryCount] = useState(0);

  // Clear presentation immediately when the video itself changes (show loading state).
  useEffect(() => {
    if (!videoId) return;
    setPresentation(null);
    setError(null);
  }, [videoId]);

  // Fetch (or re-fetch) whenever videoId, refreshKey, or retryCount changes.
  // On refreshKey-only changes, we don't clear first so the player keeps rendering
  // the previous slide rather than flashing to "LOADING...".
  useEffect(() => {
    if (!videoId) return;

    let cancelled = false;

    fetch(`/api/videos/${videoId}/export`)
      .then(r => {
        if (!r.ok) throw new Error(`Export failed: ${r.status}`);
        return r.json();
      })
      .then(data => { if (!cancelled) { setPresentation(data); setError(null); } })
      .catch(e => { if (!cancelled) setError(String(e)); });

    return () => { cancelled = true; };
  }, [videoId, refreshKey, retryCount]);

  if (!videoId) return null;

  if (error) {
    return (
      <div className="player-status player-status--error">
        <span>LOAD FAILED</span>
        <button
          className="error-boundary__retry"
          style={{ marginLeft: 12 }}
          onClick={() => { setError(null); setRetryCount(n => n + 1); }}
        >
          RETRY
        </button>
      </div>
    );
  }

  if (!presentation) {
    return (
      <div className="player-status">
        LOADING PLAYER...
      </div>
    );
  }

  const modeClass = viewportMode === 'mobile-portrait'
    ? 'player-preview-host--portrait'
    : 'player-preview-host--landscape';

  const slides = presentation.slides ?? [];
  const targetIndex = targetSlideId
    ? Math.max(0, slides.findIndex(s => s.id === targetSlideId))
    : 0;

  return (
    <div className={`gnommo-player-host ${modeClass}`}>
      <GlitchPlayer
        key={`editor-preview-${presentation.id}-v${refreshKey}`}
        presentation={presentation}
        slideRegistry={defaultSlideRegistry}
        mode="slide-preview"
        targetSlideIndex={targetIndex}
        initialSessionId={`editor-preview-${presentation.id}-v${refreshKey}`}
      />
    </div>
  );
}
