/* Prisma hero — scroll-scrubbed video that zooms into the portfolio "screen".
   Visuals unchanged from v1; nav + CTA now anchor into the inner site. */
const { WordsPullUp, FadeUp, ArrowRight } = window;
const { useEffect } = React;

const HERO_VIDEO = 'assets/clouds-laptop.mp4';
const SCRUB_END = 7.55;             // end the scrub a touch early...
const WHITE_START = 0.82;           // ...and dissolve the last stretch to pure white
const WHITE_END = 0.98;
const SCREEN_WHITE = '#ECEBE6';     // warm white of the laptop screen end-frame
const CREAM = '#E1E0CC';

const NAV_ITEMS = [
  { label: 'About', href: '#about' },
  { label: 'Focus', href: '#focus' },
  { label: 'Work', href: '#work' },
  { label: 'Contact', href: '#contact' }
];

/* ---------------- HERO (scroll-scrubbed video) ---------------- */
function HeroScroll() {
  return (
    <div id="hero-track" style={{ position: 'relative', height: '420vh' }}>
      <div id="hero-sticky" style={{ position: 'sticky', top: 0, height: '100vh', overflow: 'hidden', background: '#000' }}>
        <video id="hero-video"
          muted playsInline preload="auto" tabIndex={-1}
          src={HERO_VIDEO}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />

        {/* Final-stretch dissolve to a whole-white screen */}
        <div id="hero-white" style={{ position: 'absolute', inset: 0, background: SCREEN_WHITE, opacity: 0, pointerEvents: 'none' }} />

        {/* Branding overlay — fades out as the camera pushes into the screen */}
        <div id="hero-ui" style={{ position: 'absolute', inset: 0, willChange: 'opacity, transform' }}>
          {/* legibility gradient (part of the UI layer so it fades with the branding) */}
          <div className="absolute inset-0 bg-gradient-to-b from-black/30 via-transparent to-black/70 pointer-events-none" />
          <div className="noise-overlay absolute inset-0 opacity-[0.5] mix-blend-overlay pointer-events-none" />

          {/* Navbar */}
          <nav className="absolute top-0 left-1/2 -translate-x-1/2 z-20 bg-black rounded-b-2xl md:rounded-b-3xl px-4 py-2 md:px-8">
            <ul className="flex items-center gap-3 sm:gap-6 md:gap-12 lg:gap-14">
              {NAV_ITEMS.map((item) => (
                <li key={item.label}>
                  <a href={item.href} className="nav-link text-[10px] sm:text-xs md:text-sm whitespace-nowrap">{item.label}</a>
                </li>
              ))}
            </ul>
          </nav>

          {/* Bottom content */}
          <div className="absolute bottom-0 left-0 right-0 p-5 sm:p-7 md:p-10 lg:p-12">
            <div className="grid grid-cols-12 gap-4 md:gap-6 items-end">
              <div className="col-span-12 lg:col-span-8">
                <h1 className="font-medium leading-[0.85] tracking-[-0.07em] text-[26vw] sm:text-[24vw] md:text-[22vw] lg:text-[20vw] xl:text-[19vw] 2xl:text-[20vw]"
                  style={{ color: CREAM }}>
                  <WordsPullUp text="Mat H" showAsterisk />
                </h1>
              </div>
              <div className="col-span-12 lg:col-span-4 flex flex-col gap-5 md:gap-6 lg:pb-3">
                <FadeUp delay={0.5}
                  className="text-xs sm:text-sm md:text-base flex flex-col gap-3"
                  style={{ lineHeight: 1.4, color: '#E1E0CC' }}>
                  <p>I work at the intersection of CRM transformation, customer engagement, automation and practical AI.</p>
                  <p>My focus is turning complex organisational problems into clearer operating models, useful systems and working prototypes — especially where customer data, marketing technology, internal knowledge and delivery teams need to line up.</p>
                </FadeUp>
                <FadeUp delay={0.7} className="self-start">
                  <a href="#about" className="group bg-primary rounded-full text-black font-medium text-sm sm:text-base inline-flex items-center gap-2 hover:gap-3 transition-all duration-300 pl-5 pr-1.5 py-1.5">
                    Read more
                    <span className="bg-black rounded-full w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center transition-transform duration-300 group-hover:scale-110">
                      <ArrowRight className="w-4 h-4" style={{ color: CREAM }} />
                    </span>
                  </a>
                </FadeUp>
              </div>
            </div>
          </div>

          {/* Scroll cue */}
          <div id="scroll-cue" className="absolute left-1/2 -translate-x-1/2 bottom-4 flex flex-col items-center gap-1.5 pointer-events-none">
            <span className="text-[10px] uppercase" style={{ color: CREAM, letterSpacing: '0.25em' }}>Scroll</span>
            <span style={{ width: 1, height: 26, background: `linear-gradient(${CREAM}, transparent)` }} />
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Scroll scrub + screen-handoff controller ---------------- */
function useHeroScrub() {
  useEffect(() => {
    const video = document.getElementById('hero-video');
    const track = document.getElementById('hero-track');
    const ui = document.getElementById('hero-ui');
    const cue = document.getElementById('scroll-cue');
    const boot = document.getElementById('boot-flash');
    const heroWhite = document.getElementById('hero-white');
    if (!video || !track) return;

    const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
    const smooth = (e0, e1, x) => { const t = clamp((x - e0) / (e1 - e0), 0, 1); return t * t * (3 - 2 * t); };

    let target = 0, current = 0, raf = 0;

    function compute() {
      const vh = window.innerHeight;
      const range = track.offsetHeight - vh;
      const scrolled = clamp(-track.getBoundingClientRect().top, 0, range);
      const p = range > 0 ? scrolled / range : 0;
      target = p * SCRUB_END;

      // Final stretch dissolves to a whole-white screen
      if (heroWhite) heroWhite.style.opacity = String(smooth(WHITE_START, WHITE_END, p));

      // Branding fades + drifts up as the camera pushes in (kept on screen longer)
      const uiHide = smooth(0.34, 0.58, p);
      if (ui) {
        ui.style.opacity = String(1 - uiHide);
        ui.style.transform = 'translateY(' + (-uiHide * 36) + 'px)';
        ui.style.pointerEvents = uiHide > 0.9 ? 'none' : '';
      }
      if (cue) cue.style.opacity = String(1 - smooth(0.02, 0.12, p));

      // Handoff: brief white "screen-on" beat, then the portfolio fills the screen
      const y = window.scrollY || window.pageYOffset || 0;
      const seam = track.offsetTop + track.offsetHeight - vh; // scroll Y where p === 1
      if (boot) {
        const flashIn = smooth(seam - 0.16 * vh, seam, y);
        const flashOut = 1 - smooth(seam, seam + 0.6 * vh, y);
        boot.style.opacity = String(clamp(Math.min(flashIn, flashOut), 0, 1));
      }
    }

    function loop() {
      current += (target - current) * 0.14;            // lerp → smooth, eased scrub
      if (Math.abs(target - current) < 0.003) current = target;
      if (video.readyState >= 1) {
        try { if (Math.abs(video.currentTime - current) > 0.003) video.currentTime = current; } catch (e) {}
      }
      raf = requestAnimationFrame(loop);
    }

    // Prime decoding on first interaction (helps mobile seek smoothly)
    let primed = false;
    const prime = () => {
      if (primed) return; primed = true;
      const pr = video.play();
      if (pr && pr.then) pr.then(() => video.pause()).catch(() => {});
    };
    ['wheel', 'touchstart', 'pointerdown', 'keydown'].forEach((e) =>
      window.addEventListener(e, prime, { once: true, passive: true }));

    const showFirst = () => { try { video.currentTime = 0; } catch (e) {} };
    if (video.readyState >= 1) showFirst(); else video.addEventListener('loadeddata', showFirst, { once: true });

    compute();
    window.addEventListener('scroll', compute, { passive: true });
    window.addEventListener('resize', compute);
    raf = requestAnimationFrame(loop);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('scroll', compute);
      window.removeEventListener('resize', compute);
    };
  }, []);
}

Object.assign(window, { HeroScroll, useHeroScrub, SCREEN_WHITE });
