/* ============================================================
 * Film lightbox — one player, two doors, two films.
 *
 * Opened from the hero ("Watch the film") and from the film section below.
 * Both routes land here so there is a single place where a film plays with
 * sound, and the hero loop stays what it should be: silent background.
 *
 * window.__gmOpenFilm(storyId?) is the imperative entry point, so any
 * surface can open it without threading state through the tree. storyId
 * picks which film plays — it resolves against window.__gmHeroStories
 * (defined in hero-cinematic.jsx, the single source of truth for both
 * components) so the two can never list a film differently. Omitting
 * storyId, or passing one hero-cinematic.jsx doesn't recognise, falls back
 * to the first story rather than opening a blank player.
 * ============================================================ */

const FilmLightbox = () => {
  const [open, setOpen] = useState(false);
  const [story, setStory] = useState(null);
  const videoRef = useRef(null);
  const lastFocus = useRef(null);

  useEffect(() => {
    // Imperative opener so the hero, the section, or a nav link can all call
    // it — any of them can now say WHICH film, or leave it to default.
    window.__gmOpenFilm = (storyId) => {
      const stories = window.__gmHeroStories || [];
      const resolved = stories.find((s) => s.id === storyId) || stories[0] || null;
      lastFocus.current = document.activeElement;
      setStory(resolved);
      setOpen(true);
    };
    return () => { delete window.__gmOpenFilm; };
  }, []);

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

    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);

    // The page behind must not scroll while the film is up.
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const v = videoRef.current;
    if (v) {
      v.currentTime = 0;
      // Opening IS the user gesture, so sound is allowed here — unlike the
      // hero loop, which must stay muted to autoplay at all.
      v.muted = false;
      v.play().catch(() => { v.controls = true; });
    }

    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
      if (v) v.pause();
      // Return focus to whatever opened it.
      if (lastFocus.current && lastFocus.current.focus) lastFocus.current.focus();
    };
  }, [open]);

  return (
    <div
      className={`film-lb ${open ? "is-open" : ""}`}
      role="dialog"
      aria-modal="true"
      aria-label={story ? `GuestMaker: ${story.name}` : "GuestMaker: the film"}
      aria-hidden={open ? undefined : "true"}
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
    >
      <button
        className="film-lb__close"
        onClick={() => setOpen(false)}
        aria-label="Close the film"
      >
        <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true">
          <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.6"
                strokeLinecap="round" fill="none" />
        </svg>
      </button>

      <div className="film-lb__stage">
        {story && (
          <video
            // Keyed by story id so switching films remounts a fresh <video>.
            // A <source> child's src does not hot-swap on prop update — the
            // element only re-reads its sources on mount or an explicit
            // .load() — so without this key, opening MEMORY then ONCE kept
            // silently replaying MEMORY's already-buffered frames while the
            // DOM's own src attribute correctly read once-film.mp4.
            key={story.id}
            ref={videoRef}
            className="film-lb__video"
            poster={story.filmPoster}
            preload="none"
            playsInline
            controls
            onEnded={() => setOpen(false)}
          >
            {/* Only mounted once open, so nothing downloads until asked for. */}
            {open && <source src={story.filmSrc} type="video/mp4" />}
          </video>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { FilmLightbox });
