// Film — shared embed for the standalone HTML movies.
// Runs only while scrolled into view, honors prefers-reduced-motion (waits for an
// explicit play), and gives every film a stop control. Exposes no direct file URL:
// fullscreen uses the Fullscreen API on the iframe, not an anchor to the source.

function Film({ tag, title, note, src }) {
  const wrapRef = React.useRef(null);
  const frameRef = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  const [intent, setIntent] = React.useState(null); // null = auto, true/false = user's call
  const [full, setFull] = React.useState(false);

  const calm = React.useMemo(
    () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches,
    []
  );
  // Auto-play only when the visitor hasn't asked for stillness.
  const live = inView && (intent === null ? !calm : intent);

  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    if (typeof IntersectionObserver === "undefined") { setInView(true); return; }
    const io = new IntersectionObserver(
      (entries) => entries.forEach((en) => setInView(en.isIntersecting)),
      { rootMargin: "150px 0px", threshold: 0.2 }
    );
    io.observe(wrap);
    return () => io.disconnect();
  }, []);

  const swallowSaveKeys = React.useCallback((e) => {
    const k = (e.key || "").toLowerCase();
    if ((e.metaKey || e.ctrlKey) && (k === "s" || k === "p")) {
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
  }, []);

  React.useEffect(() => {
    const block = (e) => { e.preventDefault(); return false; };
    const wrap = wrapRef.current;
    if (!wrap) return;
    wrap.addEventListener("contextmenu", block);
    wrap.addEventListener("dragstart", block);
    return () => {
      wrap.removeEventListener("contextmenu", block);
      wrap.removeEventListener("dragstart", block);
    };
  }, []);

  React.useEffect(() => {
    if (!live) return;
    document.addEventListener("keydown", swallowSaveKeys);
    return () => document.removeEventListener("keydown", swallowSaveKeys);
  }, [live, swallowSaveKeys]);

  const harden = () => {
    try {
      const d = frameRef.current && frameRef.current.contentDocument;
      if (!d) return;
      const block = (e) => { e.preventDefault(); return false; };
      d.addEventListener("contextmenu", block);
      d.addEventListener("dragstart", block);
      d.addEventListener("keydown", swallowSaveKeys);
    } catch (err) {/* cross-origin: nothing to harden */}
  };

  React.useEffect(() => {
    const onChange = () => setFull(Boolean(document.fullscreenElement));
    document.addEventListener("fullscreenchange", onChange);
    return () => document.removeEventListener("fullscreenchange", onChange);
  }, []);

  const toggleFull = () => {
    const el = frameRef.current;
    if (!el) return;
    if (document.fullscreenElement) document.exitFullscreen();
    else if (el.requestFullscreen) el.requestFullscreen();
  };

  return (
    <figure className="film" ref={wrapRef}>
      <figcaption className="film__head">
        <span className="film__tag">{tag}</span>
        <span className="film__title">{title}</span>
        <span className="film__ctrls">
          <button type="button" className="film__btn" onClick={() => setIntent(!live)}
                  aria-label={live ? "Stop animation" : "Play animation"}>
            {live ? "Stop" : "Play"}
          </button>
          <button type="button" className="film__btn" onClick={toggleFull} disabled={!live}
                  aria-label={full ? "Exit full screen" : "View full screen"}>
            {full ? "Exit full screen" : "Full screen"}
          </button>
        </span>
      </figcaption>
      <div className="film__frame">
        {live
          ? <iframe ref={frameRef} src={src} title={title} onLoad={harden}
                    sandbox="allow-scripts allow-same-origin"
                    allow="autoplay; fullscreen" allowFullScreen></iframe>
          : <button type="button" className="film__idle" onClick={() => setIntent(true)}>
              <span className="film__idle-mark" aria-hidden="true">▶</span>
              <span>{intent === false || calm ? "Play animation" : "Scroll into view to play"}</span>
            </button>}
      </div>
      {note ? <p className="film__note">{note}</p> : null}
    </figure>
  );
}

window.Film = Film;
