/* Shared video registry. Paths are relative to the html file. */
window.VIDEOS = [
  "media/insta_video_62101.MP4",
  "media/reel-02.mp4",
  "media/insta_video_31225.MP4",
  "media/reel-03.mp4",
  "media/reel-05.mp4",
  "media/reel-06.mp4",
  "media/reel-07.mp4",
  "media/insta_video_5445.MP4",
  "media/reel-09.mp4",
  "media/reel-10.mp4",
  "media/reel-11.mp4",
  "media/reel-12.mp4"
];

window.VIDEO_LABELS = [
  "Caleb Joye / Oakley",
  "Augusta Quaynor / Chanel",
  "Ella Ezeike / Brent Faiyaz",
  "Will Wharton / Balenciaga",
  "Augusta Quaynor / Tiffany & Co.",
  "Will Wharton / Lady Gaga",
  "Augusta Quaynor / Loewe",
  "Sabra Binder / Suki Waterhouse",
  "Caleb Joye / Adidas",
  "Emiliano Cuesta / Salomon",
  "Augusta Quaynor / Cartier",
  "Will Wharton / Taylor Swift Eras Tour"
];

/* ---------- 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 _maxConcurrent = _isMobile ? 4 : 12;
const _activeVideos = new Set();

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 ? "auto" : "metadata";
  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. */
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);

  // Create and manage the video element outside React.
  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap || !src) return;
    let video = null;
    let disposed = false;

    // Only create video when tile is near viewport.
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !video && !disposed) {
        video = _createVideo(wrap, src);
        videoRef.current = video;
        io.disconnect();
        // Start visibility observer for play/pause.
        setupPlayPause(video);
      }
    }, { 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 (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;
