/* global React */

/**
 * VideoPlayer — minimal styled player that streams any video file the
 * Live Server can serve. Pass `src` as a path relative to the tracker root
 * (e.g. "assets/projects/paradise/episodes/episode_00_pilot/assets/video/sequence_03_cafe/selected/SH0630_v003.mp4").
 *
 * Props:
 *   src       — URL or relative path to the video
 *   poster    — optional poster image
 *   onClose   — optional close handler (renders × button)
 *   title     — optional caption above the player
 */
function VideoPlayer({ src, poster, onClose, title }) {
  const [error, setError] = React.useState(null);
  if (!src) return null;
  return (
    <div className="vp-shell glass">
      {(title || onClose) && (
        <div className="vp-head">
          {title && <div className="vp-title">{title}</div>}
          {onClose && (
            <button className="vp-close" onClick={onClose} aria-label="Close">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
          )}
        </div>
      )}
      <div className="vp-frame">
        {error ? (
          <div className="vp-error">
            <div className="vp-error-title">Video unavailable</div>
            <div className="vp-error-sub">Couldn't load <code>{src}</code>. Check the path or that Live Server is serving it.</div>
          </div>
        ) : (
          <video
            className="vp-video"
            src={src}
            poster={poster}
            controls
            preload="metadata"
            onError={() => setError("load_failed")}>
            Sorry, your browser doesn't support embedded video.
          </video>
        )}
      </div>
    </div>
  );
}

/**
 * VideoModal — full-screen video popup with backdrop + Esc-to-close.
 */
function VideoModal({ src, poster, title, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);
  return (
    <div className="vp-modal-backdrop" onClick={onClose}>
      <div className="vp-modal" onClick={(e) => e.stopPropagation()}>
        <VideoPlayer src={src} poster={poster} title={title} onClose={onClose}/>
      </div>
    </div>
  );
}

Object.assign(window, { VideoPlayer, VideoModal });
