/* global React, gsap */

function Hero({ onCta }) {
  const t = window.useT();
  const lang = React.useContext(window.LangContext).lang;
  const videoRef = React.useRef(null);
  const headlineRef = React.useRef(null);
  const eyebrowRef = React.useRef(null);
  const subRef = React.useRef(null);
  const ctaRef = React.useRef(null);
  const [videoReady, setVideoReady] = React.useState(false);
  const posterSrc = 'images/hero/poster.webp';

  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    let cancelled = false;
    let revealTimer = null;
    const reveal = () => {
      if (cancelled || revealTimer) return;
      // Hold the poster a moment before crossfading to video
      revealTimer = setTimeout(() => { if (!cancelled) setVideoReady(true); }, 600);
    };

    // Prefer frame-perfect handoff: wait for first decoded frame to be painted
    if ('requestVideoFrameCallback' in v) {
      v.requestVideoFrameCallback(() => reveal());
    }
    // Fallbacks for older browsers / safety net
    const onPlaying = () => reveal();
    const onCanPlayThrough = () => reveal();
    v.addEventListener('playing', onPlaying, { once: true });
    v.addEventListener('canplaythrough', onCanPlayThrough, { once: true });

    // If already playable, schedule reveal on next frame to avoid sync stutter
    if (v.readyState >= 4) {
      requestAnimationFrame(() => reveal());
    }

    return () => {
      cancelled = true;
      if (revealTimer) clearTimeout(revealTimer);
      v.removeEventListener('playing', onPlaying);
      v.removeEventListener('canplaythrough', onCanPlayThrough);
    };
  }, []);

  // Cinematic intro: split-words reveal + slow zoom-out video
  React.useEffect(() => {
    if (!window.gsap) return;
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      if (eyebrowRef.current) eyebrowRef.current.style.opacity = 1;
      if (subRef.current) subRef.current.style.opacity = 1;
      if (ctaRef.current) ctaRef.current.style.opacity = 1;
      return;
    }
    const ctx = gsap.context(() => {
      // Slow zoom-out on video & poster
      gsap.fromTo([videoRef.current, '.hero-poster'],
        { scale: 1.35 },
        { scale: 1, duration: 5, ease: 'none' }
      );

      // Split headline into words wrapped in mask
      const h = headlineRef.current;
      if (h) {
        const walk = (node) => {
          const out = [];
          node.childNodes.forEach((c) => {
            if (c.nodeType === 3) {
              const words = c.textContent.split(/(\s+)/);
              words.forEach((w) => {
                if (w.trim() === '') {
                  out.push(document.createTextNode(w));
                } else {
                  const mask = document.createElement('span');
                  mask.className = 'word-mask';
                  mask.style.cssText = 'display:inline-block;overflow:hidden;vertical-align:bottom;line-height:1;';
                  const inner = document.createElement('span');
                  inner.className = 'word-inner';
                  inner.style.cssText = 'display:inline-block;transform:translateY(110%);';
                  inner.textContent = w;
                  mask.appendChild(inner);
                  out.push(mask);
                }
              });
            } else if (c.nodeType === 1) {
              const tag = c.tagName.toLowerCase();
              if (tag === 'br') {
                out.push(c.cloneNode());
              } else {
                // For <em> wrap content recursively but keep wrapper styling
                const clone = c.cloneNode(false);
                walk(c).forEach((n) => clone.appendChild(n));
                clone.dataset.italicAccent = (tag === 'em') ? '1' : '';
                out.push(clone);
              }
            }
          });
          return out;
        };
        const replacement = walk(h);
        h.innerHTML = '';
        replacement.forEach((n) => h.appendChild(n));

        const inners = h.querySelectorAll('.word-inner');
        const accentInners = h.querySelectorAll('[data-italic-accent="1"] .word-inner');

        const tl = gsap.timeline({ defaults: { ease: 'expo.out' } });
        // Eyebrow first
        tl.fromTo(eyebrowRef.current,
          { opacity: 0, y: 14 },
          { opacity: 1, y: 0, duration: 0.8 }, 0.15);
        // Words rise
        tl.to(inners, { y: 0, duration: 1.1, stagger: 0.06 }, 0.25);
        // Accent overshoot
        if (accentInners.length) {
          tl.fromTo(accentInners,
            { y: 0 },
            { y: -8, duration: 0.45, ease: 'back.out(2.6)', yoyo: true, repeat: 1 },
            '+=0.05');
        }
        // Sub
        tl.fromTo(subRef.current, {opacity: 0, y: 18}, {opacity: 1, y: 0, duration: 0.9}, '-=0.6');
        // CTAs
        tl.fromTo(ctaRef.current, {opacity: 0, y: 16}, {opacity: 1, y: 0, duration: 0.55, ease: 'expo.out'}, '+=0.12');
      }
    });
    return () => ctx.revert();
  }, []);

  return (
    <section
      id="top"
      data-screen-label="01 Hero"
      className="hero-section"
      style={{
        position: 'relative',
        height: '100vh',
        minHeight: 720,
        overflow: 'hidden',
        background: 'var(--lr-tierra-900)',
      }}>
      {/* Poster image — visible until video is ready */}
      <div
        className="hero-poster"
        role="img"
        aria-label={t('hero.poster.label')}
        style={{
          position: 'absolute', inset: 0,
          backgroundImage: `url('${posterSrc}')`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          opacity: videoReady ? 0 : 1,
          transition: 'opacity 2200ms cubic-bezier(.22,.61,.36,1) 400ms',
          zIndex: 1,
          transformOrigin: 'center',
          willChange: 'opacity',
        }}
      />
      {/* Video background */}
      <video
        ref={videoRef}
        poster={posterSrc}
        autoPlay
        muted
        loop
        playsInline
        preload="auto"
        aria-label={t('hero.video.label')}
        style={{
          position: 'absolute', inset: 0,
          width: '100%', height: '100%',
          objectFit: 'cover',
          objectPosition: 'center',
          opacity: videoReady ? 1 : 0,
          transition: 'opacity 2000ms cubic-bezier(.22,.61,.36,1)',
          zIndex: 2,
          willChange: 'opacity',
        }}
      >
        <source media="(min-width: 769px)" src="media/hero.mp4" type="video/mp4" />
        <source src="media/hero-mobile.mp4" type="video/mp4" />
      </video>
      {/* Scrim */}
      <div className="hero-scrim" style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(27,20,16,0.55) 0%, rgba(27,20,16,0.15) 30%, rgba(27,20,16,0.15) 55%, rgba(27,20,16,0.85) 100%)',
        zIndex: 3,
      }} />
      {/* Headline */}
      <div className="hero-headline-wrapper" style={{
        position: 'absolute', left: 56, right: 56, bottom: 140,
        maxWidth: 1320, margin: '0 auto',
        zIndex: 4,
      }}>
        <div ref={eyebrowRef} style={{
          fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 11,
          letterSpacing: '0.32em', textTransform: 'uppercase',
          color: 'var(--lr-arena-calida)', marginBottom: 24,
          opacity: 0,
        }}>
          {t('hero.eyebrow')}
        </div>
        <h1 key={`d-${lang}`} ref={headlineRef} className="hero-title" style={{
          fontFamily: 'var(--font-display)', fontWeight: 400,
          fontSize: 'clamp(48px, 7.4vw, 112px)', lineHeight: 0.98,
          letterSpacing: '-0.025em',
          color: 'var(--lr-cal-blanca)', margin: 0,
          maxWidth: 1100,
        }}>
          {t('hero.title.main').split('\n')[0]}<br/>
          {t('hero.title.main').split('\n')[1].replace(t('hero.title.emphasis'), '')}<em style={{
            fontFamily: 'var(--font-italic)', fontStyle: 'italic',
            fontWeight: 400, color: 'var(--lr-arena-calida)',
            textDecoration: 'underline',
            textDecorationThickness: '0.06em',
            textUnderlineOffset: '0.18em',
            textDecorationColor: 'var(--lr-terracota)',
          }}>{t('hero.title.emphasis')}</em>
        </h1>
        <h1 key={`m-${lang}`} className="hero-title-mobile" style={{
          display: 'none',
          fontFamily: 'var(--font-display)', fontWeight: 400,
          fontSize: 'clamp(34px, 9.8vw, 52px)', lineHeight: 1.04,
          letterSpacing: '-0.025em',
          color: 'var(--lr-cal-blanca)', margin: 0,
          maxWidth: 360,
          textShadow: '0 2px 18px rgba(27,20,16,0.36)',
        }}>
          {t('hero.title.mobile').replace(t('hero.title.emphasis'), '')}<em style={{
            fontFamily: 'var(--font-italic)', fontStyle: 'italic',
            fontWeight: 400, color: 'var(--lr-arena-calida)',
            textDecoration: 'underline',
            textDecorationThickness: '0.06em',
            textUnderlineOffset: '0.18em',
            textDecorationColor: 'var(--lr-terracota)',
          }}>{t('hero.title.emphasis')}</em>
        </h1>
        <div style={{
          marginTop: 40, display: 'flex', gap: 32, alignItems: 'flex-end',
          flexWrap: 'wrap',
        }}>
          <p ref={subRef} className="hero-sub-p" style={{
            fontFamily: 'var(--font-body)', fontSize: 17, lineHeight: 1.55,
            color: 'rgba(243,238,231,0.82)', maxWidth: 760, margin: 0,
            opacity: 0,
          }}>
            <span style={{whiteSpace:'pre-line'}}>{t('hero.subtitle')}</span>
          </p>
          <div ref={ctaRef} className="hero-cta" style={{ display: 'flex', gap: 28, marginLeft: 'auto', alignItems: 'center', opacity: 0 }}>
            <button onClick={onCta} className="hero-cta-primary" style={{
              fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 12,
              letterSpacing: '0.18em', textTransform: 'uppercase',
              background: 'var(--lr-terracota)', color: 'var(--lr-cal-blanca)',
              border: 'none', borderRadius: 2,
              padding: '20px 36px', cursor: 'pointer',
              minHeight: 44, minWidth: 44,
              outlineOffset: 3,
              transition: 'background var(--duration-fast) var(--ease-standard)',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--lr-terracota-700)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--lr-terracota)'; }}
            onFocus={(e) => { e.currentTarget.style.outline = '2px solid var(--lr-terracota)'; }}
            onBlur={(e) => { e.currentTarget.style.outline = ''; }}>
              {t('hero.cta.primary')}
            </button>
          </div>
        </div>
      </div>

      <style>{`
        .hero-cta-primary:hover { background: var(--lr-terracota-700); }
        .hero-cta-primary:active { transform: scale(0.97); transition: transform 80ms var(--ease-standard); }
        @media (prefers-reduced-motion: reduce) {
          .hero-cta-primary:active { transform: none; }
          .hero-poster, .hero-section video { transition: none !important; }
        }
        @media (max-width: 767px) {
          .hero-title {
            display: none !important;
          }
          .hero-title-mobile {
            display: block !important;
          }
          .hero-scrim {
            background:
              linear-gradient(180deg, rgba(27,20,16,0.72) 0%, rgba(27,20,16,0.28) 28%, rgba(27,20,16,0.35) 58%, rgba(27,20,16,0.9) 100%) !important;
          }
          .hero-headline-wrapper {
            left: 24px !important;
            right: auto !important;
            width: calc(100% - 48px) !important;
            max-width: none !important;
            bottom: max(72px, env(safe-area-inset-bottom)) !important;
          }
          .hero-cta {
            margin-left: 0 !important;
            width: 100%;
          }
          .hero-cta button {
            flex: 1 1 0 !important;
            min-width: 0 !important;
            padding: 16px 18px !important;
          }
          .hero-section {
            height: 100svh !important;
            min-height: 620px !important;
          }
          .hero-sub-p {
            font-size: clamp(15px, 3.6vw, 17px) !important;
          }
        }
        @media (max-width: 600px) {
          .hero-headline-wrapper {
            left: 16px !important;
            right: auto !important;
            width: calc(100% - 32px) !important;
            bottom: max(44px, env(safe-area-inset-bottom)) !important;
          }
          .hero-title {
            display: none !important;
          }
          .hero-title-mobile {
            font-size: clamp(32px, 10.6vw, 42px) !important;
            max-width: 330px !important;
          }
          .hero-cta {
            flex-direction: column !important;
            align-items: stretch !important;
            gap: 12px !important;
            margin-left: 0 !important;
            width: 100%;
          }
          .hero-cta button {
            width: 100% !important;
          }
          .hero-section {
            min-height: 600px !important;
          }
        }
      `}</style>
    </section>
  );
}

window.Hero = Hero;
