/* Hero — preserves the original scroll-scrubbed video mechanic.
   v2: text anchored to corners (film-title style) instead of dead center.
   Center of frame stays clean for the video subject. */
const { useEffect: useEffectH, useRef: useRefH } = React;

function Hero() {
  const containerRef  = useRefH(null);
  const videoRef      = useRefH(null);
  const scrollHintRef = useRefH(null);

  const labelRef    = useRefH(null);
  const line1Ref    = useRefH(null);
  const line2Ref    = useRefH(null);
  const subtitleRef = useRefH(null);
  const btnRef      = useRefH(null);
  const sideTagRef  = useRefH(null);

  const p2LabelRef = useRefH(null);
  const p2TitleRef = useRefH(null);
  const p2SubRef   = useRefH(null);
  const p2BtnRef   = useRefH(null);
  const p2SideRef  = useRefH(null);

  useEffectH(() => {
    const container = containerRef.current;
    const video     = videoRef.current;
    if (!container || !video) return;

    gsap.registerPlugin(ScrollTrigger);
    let gsapCtx;

    const initAll = () => {
      video.pause();
      video.currentTime = 0;

      // ---- Scroll → video scrub, rAF-throttled + delta-skip ----
      // Without throttling, every scroll event triggers an expensive seek;
      // on iOS that pegs the decoder and feels laggy. We coalesce into one
      // write per frame and skip seeks smaller than the inter-keyframe gap.
      let targetTime = 0;
      let lastApplied = -1;
      let ticking = false;
      const MIN_DELTA = 0.035; // ~30fps worth of video; smaller = juddery

      const applyFrame = () => {
        ticking = false;
        if (!video.duration) return;
        if (Math.abs(targetTime - lastApplied) < MIN_DELTA) return;
        // fastSeek when available — hops to nearest keyframe, much smoother
        if (typeof video.fastSeek === 'function') {
          try { video.fastSeek(targetTime); } catch (e) { video.currentTime = targetTime; }
        } else {
          video.currentTime = targetTime;
        }
        lastApplied = targetTime;
      };

      const onScroll = () => {
        const containerTop    = container.offsetTop;
        const containerHeight = container.offsetHeight;
        const viewportHeight  = window.innerHeight;
        const scrolled  = window.scrollY - containerTop;
        const scrollable = containerHeight - viewportHeight;
        const progress  = Math.max(0, Math.min(1, scrolled / scrollable));
        targetTime = progress * (video.duration || 0);
        if (!ticking) {
          ticking = true;
          requestAnimationFrame(applyFrame);
        }
      };
      window.addEventListener('scroll', onScroll, { passive: true });
      window.addEventListener('resize', onScroll, { passive: true });

      gsapCtx = gsap.context(() => {
        const tl = gsap.timeline({
          scrollTrigger: { trigger: container, start: 'top top', end: 'bottom bottom', scrub: 1.2 },
        });

        tl.to(scrollHintRef.current, { autoAlpha: 0, duration: 0.05 }, 0.04);

        // PHASE 1 IN
        tl.fromTo(labelRef.current,    { autoAlpha: 0, y: 20 }, { autoAlpha: 1, y: 0, duration: 0.09, ease: 'power2.out' }, 0)
          .fromTo(sideTagRef.current,  { autoAlpha: 0, x: 18 }, { autoAlpha: 1, x: 0, duration: 0.10, ease: 'power2.out' }, 0.02)
          .fromTo(line1Ref.current,    { autoAlpha: 0, y: 50 }, { autoAlpha: 1, y: 0, duration: 0.11, ease: 'power2.out' }, 0.02)
          .fromTo(line2Ref.current,    { autoAlpha: 0, y: 50 }, { autoAlpha: 1, y: 0, duration: 0.11, ease: 'power2.out' }, 0.05)
          .fromTo(subtitleRef.current, { autoAlpha: 0, y: 18 }, { autoAlpha: 1, y: 0, duration: 0.08, ease: 'power2.out' }, 0.08)
          .fromTo(btnRef.current,      { autoAlpha: 0, y: 18 }, { autoAlpha: 1, y: 0, duration: 0.08, ease: 'power2.out' }, 0.10);

        // PHASE 1 DRIFT
        tl.to(line1Ref.current,    { y: -14, duration: 0.30, ease: 'none' }, 0.12)
          .to(line2Ref.current,    { y: -14, duration: 0.30, ease: 'none' }, 0.12)
          .to(subtitleRef.current, { y: -8,  duration: 0.30, ease: 'none' }, 0.12)
          .to(btnRef.current,      { y: -8,  duration: 0.30, ease: 'none' }, 0.12);

        // PHASE 1 OUT
        tl.to(labelRef.current,    { autoAlpha: 0, y: -18, duration: 0.07, ease: 'power2.in' }, 0.42)
          .to(sideTagRef.current,  { autoAlpha: 0, x:  18, duration: 0.07, ease: 'power2.in' }, 0.42)
          .to(line1Ref.current,    { autoAlpha: 0, y: -28, duration: 0.07, ease: 'power2.in' }, 0.43)
          .to(line2Ref.current,    { autoAlpha: 0, y: -28, duration: 0.07, ease: 'power2.in' }, 0.44)
          .to(subtitleRef.current, { autoAlpha: 0, y: -18, duration: 0.07, ease: 'power2.in' }, 0.42)
          .to(btnRef.current,      { autoAlpha: 0, y: -18, duration: 0.07, ease: 'power2.in' }, 0.43);

        // PHASE 2 IN
        tl.fromTo(p2LabelRef.current, { autoAlpha: 0, y: 20 }, { autoAlpha: 1, y: 0, duration: 0.08, ease: 'power2.out' }, 0.60)
          .fromTo(p2SideRef.current,  { autoAlpha: 0, x:-18 }, { autoAlpha: 1, x: 0, duration: 0.10, ease: 'power2.out' }, 0.61)
          .fromTo(p2TitleRef.current, { autoAlpha: 0, y: 56 }, { autoAlpha: 1, y: 0, duration: 0.12, ease: 'power2.out' }, 0.62)
          .fromTo(p2SubRef.current,   { autoAlpha: 0, y: 22 }, { autoAlpha: 1, y: 0, duration: 0.08, ease: 'power2.out' }, 0.66)
          .fromTo(p2BtnRef.current,   { autoAlpha: 0, y: 18 }, { autoAlpha: 1, y: 0, duration: 0.08, ease: 'power2.out' }, 0.70);

        // PHASE 2 OUT
        tl.to(p2LabelRef.current, { autoAlpha: 0, y: -14, duration: 0.10, ease: 'power2.in' }, 0.84)
          .to(p2SideRef.current,  { autoAlpha: 0, x: -18, duration: 0.10, ease: 'power2.in' }, 0.84)
          .to(p2TitleRef.current, { autoAlpha: 0, y: -34, duration: 0.10, ease: 'power2.in' }, 0.84)
          .to(p2SubRef.current,   { autoAlpha: 0, y: -22, duration: 0.10, ease: 'power2.in' }, 0.84)
          .to(p2BtnRef.current,   { autoAlpha: 0, y: -16, duration: 0.10, ease: 'power2.in' }, 0.85);
      }, container);

      return () => {
        window.removeEventListener('scroll', onScroll);
        window.removeEventListener('resize', onScroll);
      };
    };

    let cleanup;
    if (video.readyState >= 1) {
      cleanup = initAll();
    } else {
      const handler = () => { cleanup = initAll(); };
      video.addEventListener('loadedmetadata', handler, { once: true });
      return () => { video.removeEventListener('loadedmetadata', handler); gsapCtx?.revert(); };
    }
    return () => { cleanup?.(); gsapCtx?.revert(); };
  }, []);

  return (
    <div ref={containerRef} className="hero-scroll" id="home">
      <div className="sticky top-0 h-screen overflow-hidden bg-black">

        {/* Video */}
        <video
          ref={videoRef}
          className="absolute inset-0 w-full h-full object-cover"
          muted playsInline webkit-playsinline="true" x5-playsinline="true"
          preload="auto" disableRemotePlayback disablePictureInPicture
          aria-hidden="true"
        >
          <source src="assets/hero.mp4" type="video/mp4" />
        </video>

        {/* Subtle dark grade — keeps video vibrant, lifts type at edges */}
        <div className="absolute inset-0 pointer-events-none" style={{
          background:
            'linear-gradient(to top, rgba(10,10,10,0.62) 0%, rgba(10,10,10,0.12) 38%, rgba(10,10,10,0.10) 62%, rgba(10,10,10,0.45) 100%)',
        }} />

        {/* Side vignettes — frame the subject without flattening it */}
        <div className="absolute inset-0 pointer-events-none" style={{
          background:
            'radial-gradient(ellipse 60% 90% at 0% 100%, rgba(10,10,10,0.55) 0%, transparent 50%),' +
            'radial-gradient(ellipse 60% 90% at 100% 100%, rgba(10,10,10,0.35) 0%, transparent 55%)',
        }} />

        {/* Film grain (tiny noise, optional but glues type to plate) */}
        <div className="absolute inset-0 pointer-events-none opacity-[0.18] mix-blend-overlay" style={{
          backgroundImage:
            'url("data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22160%22 height=%22160%22><filter id=%22n%22><feTurbulence type=%22fractalNoise%22 baseFrequency=%220.9%22 numOctaves=%222%22/></filter><rect width=%22100%25%22 height=%22100%25%22 filter=%22url(%23n)%22 opacity=%220.7%22/></svg>")',
          backgroundSize: '180px 180px',
        }} />

        {/* Bottom blend into the page cream */}
        <div className="absolute bottom-0 left-0 right-0 pointer-events-none" style={{
          height: '160px',
          background: 'linear-gradient(to bottom, rgba(250,248,242,0) 0%, rgba(250,248,242,0.55) 55%, rgba(250,248,242,0.95) 88%, var(--cream-soft) 100%)',
        }} />

        {/* ── Content overlay ── */}
        <div className="relative h-full w-full">

          {/* Editorial frame ticks */}
          <div className="absolute top-[120px] left-6 md:left-10 z-[3] hidden md:flex flex-col gap-1" ref={sideTagRef}>
            <div className="w-px h-12" style={{ background: 'rgba(255,255,255,0.5)' }} />
            <span className="text-[10px] uppercase tracking-[0.22em] text-white/70">N · 48° 51′</span>
            <span className="text-[10px] uppercase tracking-[0.22em] text-white/70">E · 002° 21′</span>
          </div>

          <div className="absolute top-[120px] right-6 md:right-10 z-[3] hidden md:flex flex-col items-end gap-1" ref={p2SideRef}>
            <div className="w-px h-12" style={{ background: 'rgba(255,255,255,0.5)' }} />
            <span className="text-[10px] uppercase tracking-[0.22em] text-white/70">REEL 01 · 04:23</span>
            <span className="text-[10px] uppercase tracking-[0.22em] text-white/70">ABOVE / 36,000 FT</span>
          </div>

          {/* ── PHASE 1 — corner-anchored on desktop, centered on mobile ── */}
          <div className="absolute left-5 md:left-10 lg:left-14 right-5 md:right-auto bottom-28 md:bottom-28 z-[3] max-w-3xl text-center md:text-left">
            <p ref={labelRef} className="section-label mb-4 md:mb-5" style={{ color: 'rgba(255,255,255,0.85)' }}>
              <span className="inline-block w-1.5 h-1.5 rounded-full mr-2.5 align-middle" style={{ background: 'var(--sky)' }} />
              A Travel Atelier — Est. 2009
            </p>

            <h1 className="mb-5 md:mb-6" aria-label="Be happy. Travel more.">
              <span ref={line1Ref} className="serif block tracking-[-0.025em] leading-[0.92] text-white"
                style={{ fontSize: 'clamp(2.6rem, 9.5vw, 9rem)' }}>
                Be <span className="serif-it" style={{ color: '#C9E6F8' }}>happy</span>.
              </span>
              <span ref={line2Ref} className="serif block tracking-[-0.025em] leading-[0.92] text-white"
                style={{ fontSize: 'clamp(2.6rem, 9.5vw, 9rem)', marginTop: '-4px' }}>
                Travel <span className="serif-it" style={{ color: '#C9E6F8' }}>more</span>.
              </span>
            </h1>

            <p ref={subtitleRef} className="text-[14px] md:text-[15px] mb-7 md:mb-8 max-w-md mx-auto md:mx-0 leading-relaxed text-white/80">
              Quiet, hand-built journeys for travelers who'd rather feel a place than tick it off a list.
            </p>

            <a ref={btnRef} href="#packages" id="cta-plan"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-[14px] transition-colors duration-200"
              style={{ background: 'var(--white)', color: 'var(--ink)' }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 2L11 13"/><path d="M22 2L15 22l-4-9-9-4 19-7z"/>
              </svg>
              Begin your itinerary
            </a>
          </div>

          {/* ── PHASE 2 — corner-anchored on desktop, centered on mobile ── */}
          <div className="absolute left-5 md:left-auto right-5 md:right-10 lg:right-14 bottom-28 md:bottom-28 z-[3] max-w-3xl text-center md:text-right pointer-events-none">
            <p ref={p2LabelRef} className="section-label mb-4 md:mb-5" style={{ color: 'rgba(255,255,255,0.85)' }}>
              <span className="inline-block w-1.5 h-1.5 rounded-full mr-2.5 align-middle" style={{ background: 'var(--sky)' }} />
              Above the noise
            </p>

            <h2 ref={p2TitleRef} className="serif tracking-[-0.025em] leading-[0.94] mb-5 md:mb-6 text-white"
              style={{ fontSize: 'clamp(2.4rem, 9vw, 8.5rem)' }}>
              Above the<br/>
              <span className="serif-it" style={{ color: '#C9E6F8' }}>ordinary</span>.
            </h2>

            <p ref={p2SubRef} className="text-[14px] md:text-[15px] max-w-md mx-auto md:mx-0 md:ml-auto leading-relaxed mb-7 md:mb-8 text-white/80">
              Curated by people, not algorithms. We design no more than 240 trips a year —
              so we can answer the phone, every time.
            </p>

            <a ref={p2BtnRef} href="#packages"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-[14px] transition-colors duration-200 pointer-events-auto"
              style={{ background: 'var(--white)', color: 'var(--ink)' }}>
              See where we go
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M12 5l7 7-7 7"/>
              </svg>
            </a>
          </div>

          {/* Scroll hint — center bottom */}
          <div ref={scrollHintRef} className="absolute bottom-7 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2">
            <span className="text-[10px] font-medium tracking-[0.3em] uppercase text-white/70">Scroll</span>
            <div className="w-px h-9" style={{ background: 'linear-gradient(to bottom, rgba(255,255,255,0.7), transparent)' }} />
          </div>
        </div>
      </div>
    </div>
  );
}

window.Hero = Hero;
