/* KNOWLEDGE — scroll-scrubbed bike_cosmic video on desktop.
   On mobile / touch / small viewports, falls back to a simple autoplay-loop
   because scroll-driven video seeking is unreliable on those browsers. */

const KNOWLEDGE_VIDEO = "assets/bike_cosmic.mp4";

function Knowledge() {
  const [scrubMode, setScrubMode] = React.useState(true);
  const videoRef = React.useRef(null);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mql = window.matchMedia("(hover: hover) and (pointer: fine) and (min-width: 768px)");
    const update = () => setScrubMode(mql.matches);
    update();
    if (mql.addEventListener) mql.addEventListener("change", update);
    else if (mql.addListener) mql.addListener(update);
    return () => {
      if (mql.removeEventListener) mql.removeEventListener("change", update);
      else if (mql.removeListener) mql.removeListener(update);
    };
  }, []);

  React.useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    if (!scrubMode) {
      const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); };
      tryPlay();
      video.addEventListener("loadeddata", tryPlay);
      video.addEventListener("canplay", tryPlay);
      return () => {
        video.removeEventListener("loadeddata", tryPlay);
        video.removeEventListener("canplay", tryPlay);
      };
    }

    const container = containerRef.current;
    if (!container) return;
    video.pause();

    let rafId = null;
    let duration = 0;
    let targetTime = 0;
    let currentTime = 0;
    let running = false;
    const LERP = 0.12;
    const EPS = 0.002;

    const computeTarget = () => {
      const rect = container.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = Math.max(0, Math.min(-rect.top, total));
      const progress = total > 0 ? scrolled / total : 0;
      targetTime = Math.max(0, Math.min(progress * duration, duration - 0.001));
    };

    const tick = () => {
      const diff = targetTime - currentTime;
      if (Math.abs(diff) < EPS) {
        currentTime = targetTime;
        try { video.currentTime = currentTime; } catch (e) {}
        running = false;
        rafId = null;
        return;
      }
      currentTime += diff * LERP;
      try { video.currentTime = currentTime; } catch (e) {}
      rafId = requestAnimationFrame(tick);
    };

    const onScroll = () => {
      if (duration <= 0) return;
      computeTarget();
      if (!running) {
        running = true;
        rafId = requestAnimationFrame(tick);
      }
    };

    const onMeta = () => {
      duration = video.duration || 0;
      computeTarget();
      currentTime = targetTime;
      try { video.currentTime = currentTime; } catch (e) {}
    };
    video.addEventListener("loadedmetadata", onMeta);
    if (video.readyState >= 1) onMeta();

    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    onScroll();

    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      video.removeEventListener("loadedmetadata", onMeta);
      if (rafId) cancelAnimationFrame(rafId);
    };
  }, [scrubMode]);

  const videoCommon = {
    ref: videoRef,
    src: KNOWLEDGE_VIDEO,
    muted: true,
    playsInline: true,
    preload: "auto",
    className: "absolute inset-0 w-full h-full object-cover pointer-events-none",
  };
  const videoEl = scrubMode
    ? <video key="scrub" {...videoCommon} />
    : <video key="loop" {...videoCommon} autoPlay loop />;

  const overlays = (
    <React.Fragment>
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          zIndex: -1,
          background:
            "radial-gradient(120% 80% at 50% 50%, #181818 0%, #080808 60%, #000 100%)",
        }}
      />
      <div className="absolute inset-0 noise-overlay opacity-[0.5] mix-blend-overlay pointer-events-none" />
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          background:
            "linear-gradient(to right, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.25) 45%, rgba(0,0,0,0.05) 70%, rgba(0,0,0,0.0) 100%)",
        }}
      />
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          background:
            "linear-gradient(to bottom, rgba(0,0,0,0.35) 0%, rgba(0,0,0,0) 30%, rgba(0,0,0,0) 70%, rgba(0,0,0,0.7) 100%)",
        }}
      />
      <div
        className="absolute top-5 left-6 md:top-7 md:left-10 z-10 text-[10px] sm:text-xs tracking-[0.25em] uppercase flex items-center gap-2"
        style={{ color: "rgba(225,224,204,0.7)" }}
      >
        <span className="inline-block w-1.5 h-1.5 rounded-full bg-primary animate-pulse" />
        <span>Manifesto / 002</span>
      </div>
      <div
        className="absolute top-5 right-6 md:top-7 md:right-10 z-10 text-[10px] sm:text-xs tracking-[0.25em] uppercase"
        style={{ color: "rgba(225,224,204,0.55)" }}
      >
        <span>Knowledge · Reach</span>
      </div>
      <div className="absolute inset-0 z-10 flex items-center px-6 sm:px-10 md:px-16 pointer-events-none">
        <div className="max-w-3xl">
          <div
            aria-hidden="true"
            className="font-serif-italic mb-5 md:mb-8 select-none leading-none"
            style={{
              color: "rgba(225,224,204,0.45)",
              fontSize: "clamp(56px, 7vw, 120px)",
            }}
          >
            "
          </div>
          <blockquote
            className="leading-[1.04] tracking-[-0.02em]"
            style={{
              color: "#E1E0CC",
              fontSize: "clamp(28px, 4.2vw, 68px)",
              fontWeight: 400,
            }}
          >
            <span>Knowledge without</span>{" "}
            <span className="font-serif-italic" style={{ color: "rgba(225,224,204,0.75)" }}>
              reach
            </span>{" "}
            <span>is a secret.</span>
            <br />
            <span className="font-serif-italic" style={{ color: "rgba(225,224,204,0.75)" }}>
              Reach
            </span>{" "}
            <span>without</span>{" "}
            <span className="font-serif-italic" style={{ color: "rgba(225,224,204,0.75)" }}>
              knowledge
            </span>{" "}
            <span>is noise.</span>
            <br />
            <span>We engineer the space where both compound.</span>
          </blockquote>
          <div
            className="mt-8 md:mt-12 flex items-center gap-3 text-[10px] sm:text-xs tracking-[0.25em] uppercase"
            style={{ color: "rgba(225,224,204,0.55)" }}
          >
            <span className="inline-block w-6 h-[1px] bg-primary/60" />
            <span>DATA DOGS — Studio doctrine</span>
          </div>
        </div>
      </div>
      <div
        className="absolute bottom-5 left-6 right-6 md:bottom-7 md:left-10 md:right-10 z-10 flex items-end justify-between text-[10px] sm:text-xs tracking-[0.25em] uppercase"
        style={{ color: "rgba(225,224,204,0.5)" }}
      >
        <div className="flex items-center gap-2">
          <span>◉</span>
          <span>{scrubMode ? "Scroll to play" : "Live loop"}</span>
        </div>
        <div className="hidden sm:block font-mono tracking-wider">
          §03 · DOCTRINE
        </div>
        <div>
          <a href="#" className="nav-link">Read the essay ↗</a>
        </div>
      </div>
    </React.Fragment>
  );

  if (scrubMode) {
    return (
      <section
        ref={containerRef}
        className="bg-black relative"
        style={{ height: "300vh" }}
      >
        <div className="sticky top-0 h-screen w-full px-4 md:px-6 py-4 md:py-6">
          <div className="relative w-full h-full rounded-2xl md:rounded-[2rem] overflow-hidden bg-black">
            {videoEl}
            {overlays}
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="bg-black px-4 md:px-6 pt-0 pb-4 md:pb-6">
      <div className="relative w-full rounded-2xl md:rounded-[2rem] overflow-hidden bg-black">
        <div
          className="relative w-full"
          style={{ aspectRatio: "21 / 9", minHeight: "min(92vh, 820px)" }}
        >
          {videoEl}
          {overlays}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Knowledge });
