/* hero.jsx — five hero options via `variant` prop.
   spotlight | editorial | minimal | statement | marquee */
const { useEffect: useEffectHero, useRef: useRefHero } = React;

const HERO_STREAM = 'https://stream.mux.com/tLkHO1qZoaaQOUeVWo8hEBeGQfySP02EPS02BmnNFyXys.m3u8';
const HERO_MP4   = 'https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260328_065045_c44942da-53c6-4804-b734-f9e07fc22e08.mp4';

/* Standard HLS video (Spotlight / Editorial) */
function HeroVideo() {
  const ref = useRefHero(null);
  useEffectHero(() => {
    const video = ref.current;
    if (!video) return;
    let hls;
    const start = () => { video.play().catch(() => {}); };
    if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = HERO_STREAM; video.addEventListener('loadedmetadata', start);
    } else if (window.Hls && window.Hls.isSupported()) {
      hls = new window.Hls({ enableWorker: false });
      hls.loadSource(HERO_STREAM); hls.attachMedia(video);
      hls.on(window.Hls.Events.MANIFEST_PARSED, start);
    }
    return () => { if (hls) hls.destroy(); };
  }, []);
  return <video ref={ref} className="hero__video" muted loop playsInline preload="auto" aria-hidden="true" />;
}

/* Fade-loop MP4 video (Marquee): 0.5s fade-in, 0.5s fade-out, 100ms pause, repeat */
function HeroFadeVideo() {
  const ref = useRefHero(null);
  useEffectHero(() => {
    const v = ref.current;
    if (!v) return;
    v.src = HERO_MP4; v.muted = true; v.playsInline = true; v.preload = 'auto';
    v.style.opacity = '0';
    let raf = 0, dying = false;
    const FADE = 500; // ms
    const animate = (startTime, from, to, cb) => {
      const step = (now) => {
        const p = Math.min(1, (now - startTime) / FADE);
        v.style.opacity = String(from + (to - from) * p);
        if (p < 1) { raf = requestAnimationFrame(step); } else { cb && cb(); }
      };
      raf = requestAnimationFrame(step);
    };
    const onCanPlay = () => { dying = false; animate(performance.now(), 0, 0.35, null); v.play().catch(() => {}); };
    const onTimeUpdate = () => {
      if (!dying && v.duration && v.currentTime > v.duration - 0.5) {
        dying = true; animate(performance.now(), 0.35, 0, null);
      }
    };
    const onEnded = () => { v.style.opacity = '0'; setTimeout(() => { dying = false; v.currentTime = 0; v.play().catch(() => {}); }, 100); };
    v.addEventListener('canplay', onCanPlay, { once: false });
    v.addEventListener('timeupdate', onTimeUpdate);
    v.addEventListener('ended', onEnded);
    v.load();
    return () => { cancelAnimationFrame(raf); v.removeEventListener('canplay', onCanPlay); v.removeEventListener('timeupdate', onTimeUpdate); v.removeEventListener('ended', onEnded); };
  }, []);
  return <video ref={ref} className="hero__video hero__video--fade" muted playsInline aria-hidden="true" />;
}

const goContact = () => document.querySelector('#contact').scrollIntoView({ behavior: 'smooth' });
const goWork = () => document.querySelector('#portfolio').scrollIntoView({ behavior: 'smooth' });
function PillCTA({ label }) {
  return <button className="btn-pill" onClick={goContact}>{label || 'Start free audit'} <Icon name="arrowRight" size={18} stroke={2.2} /></button>;
}
function GhostCTA() {
  return <button className="btn-ghost-light" onClick={goWork}><Icon name="play" size={15} fill="currentColor" stroke={0} /> See the work</button>;
}

const INLINE_STATS = [{ n: '150+', l: 'Projects' }, { n: '96%', l: 'Retention' }, { n: '3.4×', l: 'Avg. ROI' }];

function HeroStatsCard() {
  return (
    <div className="hcard reveal">
      <div className="hcard__head"><div className="hcard__mark"><Icon name="target" size={26} /></div><div><div className="hcard__bignum">150+</div><div className="hcard__bigcap">Projects delivered</div></div></div>
      <div className="hcard__bar-row"><span className="k">Client satisfaction</span><span className="v">98%</span></div>
      <div className="hcard__bar"><i style={{ width: '98%' }} /></div>
      <div className="hcard__grid">
        {[{ n:'12+',l:'Years' },{ n:'24/7',l:'Support' },{ n:'3.4×',l:'ROI' },{ n:'<14d',l:'Launch' }].map(c=><div key={c.l} className="hcard__cell"><div className="n">{c.n}</div><div className="l">{c.l}</div></div>)}
      </div>
    </div>
  );
}

/* ========== OPTION 1: Spotlight ========== */
function HeroSpotlight() {
  return (
    <section className="hero hero--center" id="top" data-screen-label="Hero">
      <HeroVideo />
      <div className="hero__scrim" />
      <div className="hero__glow" />
      <div className="hero__grid"><span /><span /><span /></div>
      <div className="mt-container hero-center">
        <div className="glass-mini reveal">
          <span className="glass-mini__tag">[ EST. 2013 ]</span>
          <p className="glass-mini__head">Led by senior <em>specialists</em></p>
          <p className="glass-mini__desc">SEO · Web · AI automation, under one roof.</p>
        </div>
        <span className="hero__eyebrow reveal">Integrated digital growth</span>
        <h1 className="hero__title hero__title--lg reveal">Your business<br />deserves to be<br /><em>found<span className="accent">.</span></em></h1>
        <p className="hero__sub reveal">SEO, web development and AI automation under one roof. The site we build ranks, the rankings convert, and the conversions run on autopilot.</p>
        <div className="hero__actions reveal"><PillCTA /><GhostCTA /></div>
        <div className="hero__inline-stats reveal">
          {INLINE_STATS.map((s) => <div key={s.l} className="his"><span className="his__n">{s.n}</span><span className="his__l">{s.l}</span></div>)}
        </div>
      </div>
    </section>
  );
}

/* ========== OPTION 2: Editorial (split) ========== */
function HeroEditorial() {
  return (
    <section className="hero hero--split" id="top" data-screen-label="Hero">
      <HeroVideo />
      <div className="hero__scrim hero__scrim--left" />
      <div className="hero__glow hero__glow--right" />
      <div className="hero__grid"><span /><span /><span /></div>
      <div className="mt-container hero-split">
        <div className="hero-split__copy">
          <span className="hero__eyebrow reveal">Integrated digital growth</span>
          <h1 className="hero__title hero__title--left reveal">Get found.<br />Get chosen.<br /><em>Grow<span className="accent">.</span></em></h1>
          <p className="hero__sub hero__sub--left reveal">Three disciplines — SEO, web and AI automation — run as one growth engine. Outcomes, not outputs.</p>
          <div className="hero__actions reveal"><PillCTA /><GhostCTA /></div>
        </div>
        <HeroStatsCard />
      </div>
    </section>
  );
}

/* ========== OPTION 3: Minimal ========== */
function HeroMinimal() {
  return (
    <section className="hero hero--center hero--minimal" id="top" data-screen-label="Hero">
      <div className="hero__glow hero__glow--soft" />
      <div className="mt-container hero-center">
        <span className="hero__eyebrow reveal">Integrated digital growth</span>
        <h1 className="hero__title hero__title--xl reveal">Your business deserves to be <em>found<span className="accent">.</span></em></h1>
        <p className="hero__sub reveal">We build the visibility to be found, the credibility to be chosen, and the automation to scale without limits.</p>
        <div className="hero__actions reveal"><PillCTA /></div>
        <div className="hero__inline-stats hero__inline-stats--rule reveal">
          {INLINE_STATS.map((s) => <div key={s.l} className="his"><span className="his__n">{s.n}</span><span className="his__l">{s.l}</span></div>)}
        </div>
      </div>
    </section>
  );
}

/* ========== OPTION 4: Statement (light) ========== */
function HeroStatement() {
  return (
    <section className="hero hero--statement" id="top" data-screen-label="Hero">
      <div className="hero-statement__rule" />
      <div className="mt-container hero-statement">
        <div className="hero-statement__top reveal"><span className="eyebrow eyebrow--tick">Integrated digital growth</span><span className="hero-statement__since">EST. 2013</span></div>
        <h1 className="hero-statement__title reveal">The website we build <em>ranks.</em> The rankings <em>convert.</em> The conversions run on <span className="accent">autopilot.</span></h1>
        <div className="hero-statement__bottom reveal">
          <p className="hero-statement__sub">SEO, web development and AI automation under one roof — for ambitious businesses that intend to be found first.</p>
          <div className="hero-statement__actions"><PillCTA /><button className="btn-ghost-dark" onClick={goWork}>See the work <Icon name="arrowRight" size={16} /></button></div>
        </div>
        <div className="hero-statement__stats reveal">
          {INLINE_STATS.concat([{ n: '12+', l: 'Years' }]).map((s) => <div key={s.l} className="hss"><span className="hss__n">{s.n}</span><span className="hss__l">{s.l}</span></div>)}
        </div>
      </div>
    </section>
  );
}

/* ========== OPTION 5: Marquee ========== */
const MARQUEE_LOGOS = ['Northwind', 'Veloce', 'Harbour & Co', 'Aksu Health', 'Brightside', 'Lumen', 'Praxis', 'Kova'];

function LogoIcon({ name }) {
  return (
    <span className="mq-logo reveal">
      <span className="mq-logo__icon">{name[0]}</span>
      <span className="mq-logo__name">{name}</span>
    </span>
  );
}

function HeroMarquee() {
  const logos = [...MARQUEE_LOGOS, ...MARQUEE_LOGOS]; // duplicate for seamless loop
  return (
    <section className="hero hero--marquee" id="top" data-screen-label="Hero">
      <HeroFadeVideo />
      <div className="hero__grid"><span /><span /><span /></div>
      <div className="mq-blob" aria-hidden="true" />
      <div className="hero--marquee__body">
        <div className="mt-container mq-content">
          <span className="hero__eyebrow reveal" style={{ justifyContent: 'center' }}>Integrated digital growth</span>
          <h1 className="mq-title reveal">
            <span>Your business deserves</span>
            <br />
            <span className="mq-title__accent">to be <em>found<span className="mq-dot">.</span></em></span>
          </h1>
          <p className="mq-sub reveal">SEO, web development and AI automation under one roof — built for ambitious businesses.</p>
          <div className="hero__actions reveal" style={{ justifyContent: 'center', marginTop: '2.4rem' }}><PillCTA /><GhostCTA /></div>
        </div>

      </div>
    </section>
  );
}

function Hero({ variant = 'spotlight' }) {
  if (variant === 'editorial') return <HeroEditorial />;
  if (variant === 'minimal')   return <HeroMinimal />;
  if (variant === 'statement') return <HeroStatement />;
  if (variant === 'marquee')   return <HeroMarquee />;
  return <HeroSpotlight />;
}

Object.assign(window, { Hero });
