// Hero.jsx — asymmetric editorial spread with orchestrated entrance motion.
const HERO_VIDEO_SRC = "assets/videos/animals/lion.mp4";
const HERO_POSTER_SRC = "assets/animals/hero/lion-poster.png";

function Hero({ onBookCall }) {
  const [ready, setReady] = React.useState(false);
  const [videoPlaying, setVideoPlaying] = React.useState(false);
  const sectionRef = React.useRef(null);
  const stageRef = React.useRef(null);
  const videoRef = React.useRef(null);
  const btnRef = React.useRef(null);
  const mobile = useMobileLayout(900);

  React.useEffect(() => {
    let id2;
    const id1 = requestAnimationFrame(() => {
      id2 = requestAnimationFrame(() => setReady(true));
    });
    return () => {
      cancelAnimationFrame(id1);
      if (id2) cancelAnimationFrame(id2);
    };
  }, []);

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

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
    if (reduced.matches) return undefined;

    let cancelled = false;

    const onPlaying = () => {
      if (!cancelled) {
        setVideoPlaying(true);
        window.markVideoCached?.(HERO_VIDEO_SRC);
      }
    };

    const bootVideo = () => {
      if (cancelled) return;
      if (mobile) {
        video.preload = "auto";
        video.load();
      }
      video.play().catch(() => {});
    };

    video.addEventListener("playing", onPlaying);

    let bootRaf1 = 0;
    let bootRaf2 = 0;
    if (mobile) {
      bootRaf1 = window.requestAnimationFrame(() => {
        bootRaf2 = window.requestAnimationFrame(bootVideo);
      });
    } else {
      bootVideo();
    }

    return () => {
      cancelled = true;
      cancelAnimationFrame(bootRaf1);
      cancelAnimationFrame(bootRaf2);
      video.removeEventListener("playing", onPlaying);
      video.pause();
    };
  }, [mobile]);

  React.useEffect(() => {
    const section = sectionRef.current;
    const stage = stageRef.current;
    if (!section) return undefined;
    if (mobile) return undefined;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
    if (reduced.matches) return undefined;

    let targetX = 0;
    let targetY = 0;
    let cursorX = 0;
    let cursorY = 0;
    let magnetX = 0;
    let magnetY = 0;
    let magnetTargetX = 0;
    let magnetTargetY = 0;
    let scrollY = 0;
    let scrollTargetY = 0;
    let raf = 0;
    let running = false;
    let visible = false;

    const ease = 0.12;

    const loop = () => {
      cursorX += (targetX - cursorX) * ease;
      cursorY += (targetY - cursorY) * ease;
      magnetX += (magnetTargetX - magnetX) * 0.18;
      magnetY += (magnetTargetY - magnetY) * 0.18;
      scrollY += (scrollTargetY - scrollY) * 0.14;

      section.style.setProperty("--hero-cursor-x", cursorX.toFixed(3));
      section.style.setProperty("--hero-cursor-y", cursorY.toFixed(3));
      if (stage) {
        stage.style.setProperty("--hero-scroll-y", `${scrollY.toFixed(2)}px`);
      }
      if (btnRef.current) {
        btnRef.current.style.setProperty("--magnet-x", `${magnetX.toFixed(2)}px`);
        btnRef.current.style.setProperty("--magnet-y", `${magnetY.toFixed(2)}px`);
      }

      const stillMoving =
        Math.abs(targetX - cursorX) > 0.001 ||
        Math.abs(targetY - cursorY) > 0.001 ||
        Math.abs(magnetTargetX - magnetX) > 0.05 ||
        Math.abs(magnetTargetY - magnetY) > 0.05 ||
        Math.abs(scrollTargetY - scrollY) > 0.1;

      if (stillMoving) {
        raf = requestAnimationFrame(loop);
      } else {
        running = false;
        raf = 0;
      }
    };

    const kick = () => {
      if (running) return;
      running = true;
      raf = requestAnimationFrame(loop);
    };

    const onPointerMove = (e) => {
      const rect = section.getBoundingClientRect();
      const px = (e.clientX - rect.left) / rect.width;
      const py = (e.clientY - rect.top) / rect.height;
      targetX = Math.max(-1, Math.min(1, (px - 0.5) * 2));
      targetY = Math.max(-1, Math.min(1, (py - 0.5) * 2));

      section.classList.add("is-tracking");
      if (stage) stage.classList.add("is-tracking");

      const btn = btnRef.current;
      if (btn) {
        const br = btn.getBoundingClientRect();
        const bcx = br.left + br.width / 2;
        const bcy = br.top + br.height / 2;
        const dx = e.clientX - bcx;
        const dy = e.clientY - bcy;
        const dist = Math.hypot(dx, dy);
        const reach = 160;
        if (dist < reach) {
          const strength = 1 - dist / reach;
          magnetTargetX = dx * 0.25 * strength;
          magnetTargetY = dy * 0.32 * strength;
        } else {
          magnetTargetX = 0;
          magnetTargetY = 0;
        }
      }
      kick();
    };

    const onPointerLeave = () => {
      targetX = 0;
      targetY = 0;
      magnetTargetX = 0;
      magnetTargetY = 0;
      section.classList.remove("is-tracking");
      if (stage) stage.classList.remove("is-tracking");
      kick();
    };

    const onScroll = () => {
      if (!visible) return;
      const rect = section.getBoundingClientRect();
      const progress = Math.max(-1, Math.min(1, -rect.top / Math.max(1, rect.height)));
      scrollTargetY = progress * 50;
      kick();
    };

    const visibilityIo = new IntersectionObserver(
      ([entry]) => {
        visible = entry.isIntersecting;
        if (visible) onScroll();
      },
      { threshold: 0 }
    );
    visibilityIo.observe(section);

    section.addEventListener("pointermove", onPointerMove, { passive: true });
    section.addEventListener("pointerleave", onPointerLeave);
    window.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      visibilityIo.disconnect();
      section.removeEventListener("pointermove", onPointerMove);
      section.removeEventListener("pointerleave", onPointerLeave);
      window.removeEventListener("scroll", onScroll);
      if (raf) cancelAnimationFrame(raf);
      section.style.removeProperty("--hero-cursor-x");
      section.style.removeProperty("--hero-cursor-y");
      if (stage) stage.style.removeProperty("--hero-scroll-y");
      if (btnRef.current) {
        btnRef.current.style.removeProperty("--magnet-x");
        btnRef.current.style.removeProperty("--magnet-y");
      }
    };
  }, [mobile]);

  return (
    <section
      ref={sectionRef}
      className={`zg-hero${ready ? " zg-hero--ready" : ""}`}
      aria-labelledby="zg-hero-title"
    >
      <div className="zg-hero-grid">
        <div className="zg-hero-masthead">
          <div className="zg-hero-masthead-inner">
            <h1 id="zg-hero-title" className="zg-hero-headline">
              <span className="line zg-hero-a" data-zg-delay="0">
                We put AI to work
              </span>
              <span className="line muted zg-hero-a" data-zg-delay="1">
                where the{" "}
                <span className="zg-hero-headline-row">
                  <span className="zg-highlight zg-hero-a-highlight" data-zg-delay="1">
                    real work
                  </span>{" "}
                  happens.
                </span>
              </span>
            </h1>

            <div className="zg-hero-deck">
              <p className="zg-hero-sub zg-hero-a" data-zg-delay="2">
                The{" "}
                <span className="zg-accent-underline">outsourced AI team</span>{" "}
                for owner-led and mid-market companies. We map the workflow, build
                the system, and keep improving after launch.
              </p>
              <div className="zg-hero-actions zg-hero-a" data-zg-delay="3">
                <button
                  ref={btnRef}
                  type="button"
                  className="zg-btn zg-hero-btn"
                  onClick={onBookCall}
                >
                  Book a Call <span className="plus">+</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div ref={stageRef} className="zg-hero-stage">
          <div className="zg-hero-stage-reveal" aria-hidden="true" />
          <div
            className={`zg-hero-photo-wrap${
              videoPlaying ? " zg-hero-photo-wrap--playing" : ""
            }`}
          >
            <img
              className={`zg-hero-photo zg-hero-photo-poster${
                videoPlaying ? " is-hidden" : ""
              }`}
              src={HERO_POSTER_SRC}
              alt=""
              loading="eager"
              decoding="async"
              aria-hidden="true"
            />
            <video
              ref={videoRef}
              className={`zg-hero-photo zg-hero-photo-video${
                videoPlaying ? " is-active" : ""
              }`}
              src={HERO_VIDEO_SRC}
              poster={HERO_POSTER_SRC}
              loop
              muted
              playsInline
              preload={mobile ? "none" : "metadata"}
              aria-hidden="true"
            />
          </div>
          <div className="zg-hero-scrim" aria-hidden="true" />
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
