// Video lightbox for the films section — same visual language as the site's
// existing pc-lbx video modal (centered frame, pink Unmute pill, circular X
// above the frame), with added prev/next between films and a CTA below.
function vimeoParts(url) {
  if (!url || url.indexOf("vimeo") < 0) return null;
  const m = url.match(/vimeo\.com\/(?:video\/)?(\d+)(?:\/([a-zA-Z0-9]+))?/);
  return m ? { id: m[1], hash: m[2] || null } : null;
}

function THReelsMedia({ f, muted, vRef, onReady, onStarted, onSoundBlocked }) {
  const vp = vimeoParts(f.video);
  // Vimeo films go through the shared SDK-only VimeoFilm controller (mobile-safe
  // mute/unmute + poster fallback). Direct files keep the native <video> path.
  if (vp) {
    return <window.VimeoFilm video={f.video} poster={f.img} alt={f.client || ""} loader="logo"
      className="th-rp-media" muted={muted} onReady={onReady} onSoundBlocked={onSoundBlocked} />;
  }
  return f.video
    ? <video ref={vRef} className="th-rp-media" src={f.video} poster={f.img}
        muted={muted} loop playsInline autoPlay preload="auto" onPlaying={onStarted} />
    : <img className="th-rp-media" src={f.img} alt="" draggable="false" />;
}

function THReelsPlayer({ films, index, onIndex, onClose }) {
  const n = films.length;
  const cur = films[index];
  const vRef = React.useRef(null);
  const vimeoRef = React.useRef(null);
  const [muted, setMuted] = React.useState(true);   // start muted; the pink Unmute pill invites sound
  const [expanded, setExpanded] = React.useState(false);
  const go = React.useCallback((d) => onIndex((index + d + n) % n), [index, n, onIndex]);
  React.useEffect(() => { vimeoRef.current = null; }, [index]);
  // Phase-1 preload: warm ONLY the next film once the current one has started.
  const prefetchNext = React.useCallback(() => {
    if (n < 2 || !window.saysoPrefetchFilm) return;
    window.saysoPrefetchFilm(films[(index + 1) % n]);
  }, [films, index, n]);
  // Opening the reels player takes playback priority over background grid previews.
  React.useEffect(() => {
    if (window.saysoPreviewGate) window.saysoPreviewGate.setForeground(true);
    return () => { if (window.saysoPreviewGate) window.saysoPreviewGate.setForeground(false); };
  }, []);
  // Unmute runs directly in the tap handler (iOS gesture requirement); UI flips
  // to "sound on" only after the SDK player confirms, else stays muted (retry-safe).
  const toggleSound = React.useCallback((e) => {
    if (e) e.stopPropagation();
    const p = vimeoRef.current;
    const v = vRef.current;
    if (!muted) {                                   // muting is always allowed
      if (v) { try { v.muted = true; } catch (_) {} }
      if (p) { try { p.setMuted(true).catch(() => {}); } catch (_) {} }
      setMuted(true); return;
    }
    if (v) { try { v.muted = false; v.volume = 1; } catch (_) {} setMuted(false); return; }
    if (p) {
      Promise.resolve()
        .then(() => p.setMuted(false))
        .then(() => p.setVolume(1))
        .then(() => (p.getMuted ? p.getMuted() : false))
        .then((m) => { if (!m) setMuted(false); })   // UI flips only when sound is REALLY on
        .catch(() => { /* stay muted; retry-safe */ });
      return;
    }
    setMuted(false);
  }, [muted]);

  React.useEffect(() => {
    const v = vRef.current;
    if (v) { v.currentTime = 0; const p = v.play(); if (p) p.catch(() => {}); }
  }, [index]);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowRight") go(1);
      else if (e.key === "ArrowLeft") go(-1);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [go, onClose]);

  return (
    <div className="th-rp" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className={"th-rp-frame" + (cur.wide ? "" : " vert") + (expanded ? " expanded" : "")}>
        <div className="th-rp-stage">
          <THReelsMedia f={cur} muted={muted} vRef={vRef} onReady={(p) => { vimeoRef.current = p; prefetchNext(); }} onStarted={prefetchNext} onSoundBlocked={() => setMuted(true)} />
          <button className="th-rp-close" type="button" aria-label="Close" onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
          </button>
          <button className="th-rp-expand" type="button" aria-label={expanded ? "Shrink" : "Enlarge full frame"} onClick={() => setExpanded((x) => !x)}>
            {expanded
              ? <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" /></svg>
              : <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5" /></svg>}
          </button>
          {cur.video && (
            <button className={"pc-unmute" + (!muted ? " is-active" : "")} type="button" onClick={toggleSound}>
              {muted
                ? <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z" /><path d="m23 9-6 6M17 9l6 6" /></svg><span>Unmute</span></>
                : <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z" /><path d="M15.5 8.5a5 5 0 0 1 0 7M19 5a9 9 0 0 1 0 14" /></svg><span>Mute</span></>}
            </button>
          )}
        </div>

        <div className="th-rp-cap">
          <span className="th-rp-proj">{cur.wide ? cur.client + " | " + (cur.proj || "Customer") : cur.client}</span>
          {cur.loc && <span className="th-rp-loc">Filmed in {cur.loc}</span>}
        </div>

        <div className="th-rp-navrow">
          <button className="th-rp-nav-btn" type="button" aria-label="Previous film" onClick={() => go(-1)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#181818" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
          </button>
          <span className="th-rp-count">{index + 1} / {n}</span>
          <button className="th-rp-nav-btn" type="button" aria-label="Next film" onClick={() => go(1)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#181818" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6" /></svg>
          </button>
        </div>

        <div className="th-rp-ctablock">
          <span className="th-rp-ctalead">Want a film like this?</span>
          <button className="pc-btn pc-btn-pri th-rp-cta start-your-film-btn" type="button" onClick={() => window.pcGo && window.pcGo(window.PC_LINKS.navBook, { event: "start_your_film_click", button_id: "start_your_film", destination: "app_presignup" })}>
            Start your film
          </button>
        </div>
      </div>
    </div>
  );
}

window.THReelsPlayer = THReelsPlayer;
