/* Shared video registry. Paths are relative to the html file. */
window.VIDEOS = [
  "media/insta_video_62101.MP4",
  "media/insta_video_22661_2.mov",
  "media/insta_video_31225.MP4",
  "media/reel-03.mp4",
  "media/insta_video_48822.MP4",
  "media/insta_video_9765.MP4",
  "media/reel-07.mp4",
  "media/insta_video_5445.MP4",
  "media/reel-10.mp4",
  "media/insta_video_80580.MP4",
  "media/insta_video_13477.MP4",
  "media/insta_video_67580.MP4"
];

window.VIDEO_LABELS = [
  "Caleb Joye / Oakley",
  "Augusta Quaynor / Chanel",
  "Ella Ezeike / Brent Faiyaz",
  "Will Wharton / Balenciaga",
  "Jean Estene / Vogue",
  "Grant Spanier / Marc Jacobs",
  "Augusta Quaynor / Loewe",
  "Sabra Binder / Suki Waterhouse",
  "Emiliano Cuesta / Salomon",
  "Jean Estene / The Real Real",
  "Devin Desouza / Lexxola",
  "Grant Spanier / Dazed"
];

/* ---------- Video playback engine ---------- */
/* Bypasses React entirely for <video> creation to avoid the muted-property
   bug. Creates videos via DOM API so muted/playsinline are set correctly
   from the start — iOS checks these properties (not attributes) before
   allowing autoplay. On mobile, limits concurrent loads to 4. */

const _isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
const _conn = navigator.connection || navigator.mozConnection || null;
const _isSlow = _conn && (_conn.saveData || _conn.effectiveType === "2g" || _conn.effectiveType === "slow-2g");
const _maxConcurrent = _isSlow ? 2 : _isMobile ? 3 : 12;
const _activeVideos = new Set();
const _DARK_POSTER = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1' height='1'%3E%3Crect fill='%230f0f0f' width='1' height='1'/%3E%3C/svg%3E";

function _createVideo(container, src) {
  const v = document.createElement("video");
  v.muted = true;
  v.defaultMuted = true;
  v.loop = true;
  v.playsInline = true;
  v.autoplay = true;
  v.preload = _isMobile ? "none" : "auto";
  v.poster = _DARK_POSTER;
  v.setAttribute("muted", "");
  v.setAttribute("playsinline", "");
  v.setAttribute("webkit-playsinline", "");
  v.setAttribute("autoplay", "");
  v.setAttribute("loop", "");
  Object.assign(v.style, {
    position: "absolute", top: "0", left: "0",
    width: "100%", height: "100%",
    objectFit: "cover",
    opacity: "0",
    zIndex: "0",
    transition: "opacity 600ms cubic-bezier(0.16, 1, 0.3, 1)"
  });
  v.addEventListener("loadeddata", () => { v.style.opacity = "1"; });
  v.src = src;
  container.appendChild(v);
  return v;
}

/* Reusable video tile — autoplay muted loop, true lazy load. */
var _tileIndex = 0;
function VideoTile({ src, label, sub, aspect = "3/4", dark = true, preload = "metadata", showSprockets = true, style = {}, onClick }) {
  const wrapRef = React.useRef(null);
  const videoRef = React.useRef(null);
  const staggerRef = React.useRef(_tileIndex++);

  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap || !src) return;
    let video = null;
    let disposed = false;
    let staggerTimer = null;
    var delay = staggerRef.current * (_isMobile ? 300 : 120);

    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !video && !disposed) {
        io.disconnect();
        staggerTimer = setTimeout(function() {
          if (disposed) return;
          video = _createVideo(wrap, src);
          videoRef.current = video;
          setupPlayPause(video);
        }, delay);
      }
    }, { rootMargin: "200px" });
    io.observe(wrap);

    function setupPlayPause(v) {
      const vis = new IntersectionObserver((entries) => {
        entries.forEach(e => {
          if (disposed) return;
          if (e.isIntersecting) {
            if (_activeVideos.size < _maxConcurrent || _activeVideos.has(v)) {
              _activeVideos.add(v);
              v.muted = true;
              v.play().catch(() => {});
            }
          } else {
            v.pause();
            _activeVideos.delete(v);
          }
        });
      }, { threshold: 0.1 });
      vis.observe(v);
      // Also try playing on canplay for videos that load slowly.
      v.addEventListener("canplay", function onReady() {
        if (!disposed && v.paused) {
          v.muted = true;
          v.play().catch(() => {});
        }
      });
    }

    return () => {
      disposed = true;
      io.disconnect();
      if (staggerTimer) clearTimeout(staggerTimer);
      if (video) {
        video.pause();
        _activeVideos.delete(video);
        video.removeAttribute("src");
        video.load();
        video.remove();
        videoRef.current = null;
      }
    };
  }, [src]);

  const palette = dark
    ? { bg: "#0f0f0f", label: "rgba(244,241,234,0.6)", title: "var(--paper)", edge: "rgba(244,241,234,0.12)" }
    : { bg: "var(--paper-2)", label: "var(--muted)", title: "var(--fg)", edge: "var(--line-strong)" };

  return (
    <div
      ref={wrapRef}
      data-cursor="play" data-cursor-label="PLAY"
      onClick={(e) => {
        const v = videoRef.current;
        if (v && v.paused) { v.muted = true; v.play().catch(()=>{}); }
        onClick?.(e);
      }}
      style={{
        aspectRatio: aspect,
        background: palette.bg,
        position: "relative",
        overflow: "hidden",
        cursor: "none",
        ...style
      }}
    >
      {/* grain — static CSS noise */}
      <div style={{
        position:"absolute", inset: 0,
        backgroundImage:"repeating-conic-gradient(rgba(0,0,0,0.06) 0% 25%, transparent 0% 50%)",
        backgroundSize:"3px 3px",
        mixBlendMode:"overlay",
        pointerEvents:"none",
        opacity: 0.4,
        zIndex: 1
      }}/>
      {showSprockets && (
        <>
          <div style={{position:"absolute", top: 0, left: 0, right: 0, height: 12, display:"flex", gap: 6, padding: "4px 6px", zIndex: 2}}>
            {Array.from({length: 10}).map((_,k) => <div key={k} style={{flex: 1, background: palette.edge, borderRadius: 1}}/>)}
          </div>
          <div style={{position:"absolute", bottom: 0, left: 0, right: 0, height: 12, display:"flex", gap: 6, padding: "4px 6px", zIndex: 2}}>
            {Array.from({length: 10}).map((_,k) => <div key={k} style={{flex: 1, background: palette.edge, borderRadius: 1}}/>)}
          </div>
        </>
      )}
      {/* labels */}
      {(label || sub) && (
        <div style={{
          position:"absolute", inset: "20px 16px",
          display:"flex", flexDirection:"column", justifyContent:"space-between",
          color: palette.label, fontFamily:"var(--mono)", fontSize: 10,
          letterSpacing:"0.12em", textTransform:"uppercase",
          pointerEvents:"none", zIndex: 3,
          textShadow: "0 1px 10px rgba(0,0,0,0.4)"
        }}>
          <div>{sub}</div>
          {label && (
            <div style={{fontFamily:"var(--display)", fontSize: 22, color: palette.title, textTransform:"none", letterSpacing:"-0.01em"}}>
              {label}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

window.VideoTile = VideoTile;
