// Hero.jsx — Felipe Fin Fanfa
// Full-bleed photo hero with layered premium FX:
//   z-0  background photo (hero-background.svg)
//   z-1  brand vignette overlay
//   z-2  smoke-fx WebGL canvas (injected by smoke-fx.js)
//   z-3  front mist CSS layer
//   z-4  top + bottom vignettes
//   z-5  UI: left highlights, right ticker, bottom wordmark + CTAs + socials

function CursorWordmark({ text = 'Felipe Fin Fanfa' }) {
  const wrapRef    = React.useRef(null);
  const glowGradRef = React.useRef(null);   // glow behind letters
  const spotGradRef = React.useRef(null);   // spotlight on fill

  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;

    let raf = 0;
    // Start with center of SVG in viewBox units (1600 × 220)
    let tx = 800, ty = 110;
    let cx = 800, cy = 110;

    const onMove = (e) => {
      const svgEl = wrap.querySelector('svg');
      if (!svgEl) return;
      const rect = svgEl.getBoundingClientRect();
      // Map cursor to viewBox coordinate space (1600 × 220)
      // No clamping — gradient center can be outside viewBox so the
      // light feels like it's coming from wherever the cursor is on screen.
      tx = ((e.clientX - rect.left) / rect.width) * 1600;
      ty = ((e.clientY - rect.top)  / rect.height) * 220;
      if (!raf) raf = requestAnimationFrame(tick);
    };

    const tick = () => {
      cx += (tx - cx) * 0.12;
      cy += (ty - cy) * 0.12;
      [glowGradRef.current, spotGradRef.current].forEach(g => {
        if (!g) return;
        g.setAttribute('cx', String(Math.round(cx)));
        g.setAttribute('cy', String(Math.round(cy)));
      });
      if (Math.abs(tx - cx) > 0.3 || Math.abs(ty - cy) > 0.3) {
        raf = requestAnimationFrame(tick);
      } else { raf = 0; }
    };

    window.addEventListener('mousemove', onMove, { passive: true });
    return () => {
      window.removeEventListener('mousemove', onMove);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div ref={wrapRef} style={{ width: '100%', pointerEvents: 'none' }}>
      <svg
        viewBox="0 0 1600 220"
        preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: 'auto', display: 'block', overflow: 'visible' }}
        aria-label={text}
        role="img"
      >
        <defs>
          {/*
           * userSpaceOnUse → cx/cy are in viewBox pixels (0–1600, 0–220).
           * Mouse handler maps real cursor to these coords so the gradient
           * tracks accurately even when cursor is far from the text.
           *
           * r="420" ≈ 26% of viewBox width — generous halo radius.
           */}

          {/* Outer glow — wide, behind the letters */}
          <radialGradient
            ref={glowGradRef}
            id="ff-glow-bg"
            cx="800" cy="110" r="420"
            gradientUnits="userSpaceOnUse"
          >
            <stop offset="0%"   stopColor="#7BA4FF" stopOpacity="0.85" />
            <stop offset="40%"  stopColor="#2C6AFF" stopOpacity="0.45" />
            <stop offset="75%"  stopColor="#1C60DA" stopOpacity="0.15" />
            <stop offset="100%" stopColor="#1C60DA" stopOpacity="0" />
          </radialGradient>

          {/* Spotlight — subtle brightening on the solid fill */}
          <radialGradient
            ref={spotGradRef}
            id="ff-spot"
            cx="800" cy="110" r="300"
            gradientUnits="userSpaceOnUse"
          >
            <stop offset="0%"   stopColor="#FFFFFF" stopOpacity="0.40" />
            <stop offset="50%"  stopColor="#FFFFFF" stopOpacity="0.12" />
            <stop offset="100%" stopColor="#FFFFFF" stopOpacity="0" />
          </radialGradient>

          {/* Blur for the background glow layer */}
          <filter id="ff-glow-blur" x="-12%" y="-60%" width="124%" height="220%">
            <feGaussianBlur stdDeviation="10" />
          </filter>
        </defs>

        {/*
         * Rendering order (bottom → top):
         *   1. Glow blob  — drawn first, blurred, BEHIND the letters.
         *      Uses cursor gradient fill. The crisp base text (layer 2)
         *      is painted on top and covers the interior, so the blurred
         *      glow is ONLY visible on the outside edges. Zero internal lines.
         *   2. Solid base — crisp fill, covers glow interior.
         *   3. Spotlight  — slight brightness boost on fill near cursor.
         */}

        {/* ── Layer 1: glow blob behind letters — EXTERNAL only ── */}
        <text
          x="800" y="172"
          textAnchor="middle"
          textLength="1520"
          lengthAdjust="spacingAndGlyphs"
          fill="url(#ff-glow-bg)"
          stroke="none"
          filter="url(#ff-glow-blur)"
          style={{ fontFamily: 'Geist, sans-serif', fontWeight: 800, fontSize: 200 }}
        >{text}</text>

        {/* ── Layer 2: solid crisp base — covers glow interior ── */}
        <text
          x="800" y="172"
          textAnchor="middle"
          textLength="1520"
          lengthAdjust="spacingAndGlyphs"
          fill="rgba(206,212,242,0.84)"
          stroke="none"
          style={{ fontFamily: 'Geist, sans-serif', fontWeight: 800, fontSize: 200 }}
        >{text}</text>

        {/* ── Layer 3: cursor spotlight on fill ── */}
        <text
          x="800" y="172"
          textAnchor="middle"
          textLength="1520"
          lengthAdjust="spacingAndGlyphs"
          fill="url(#ff-spot)"
          stroke="none"
          style={{ fontFamily: 'Geist, sans-serif', fontWeight: 800, fontSize: 200 }}
        >{text}</text>
      </svg>
    </div>
  );
}

function HeroHighlights({ mounted, highlights }) {
  return (
    <div className="ff-hero-highlights" style={{
      position: 'absolute', zIndex: 5,
      left: 'clamp(20px, 5vw, 80px)',
      top: '50%',
      transform: 'translateY(-50%)',
      display: 'flex', flexDirection: 'column', gap: 'clamp(14px, 2.2vh, 22px)',
    }}>
      {highlights.map((item, i) => (
        <div
          key={item.label}
          style={{
            opacity: mounted ? 1 : 0,
            transform: mounted ? 'translateX(0)' : 'translateX(-18px)',
            transition: `opacity 900ms ease ${500 + i * 110}ms, transform 900ms cubic-bezier(0.2,0.7,0.1,1) ${500 + i * 110}ms`,
            display: 'flex', flexDirection: 'column', gap: 2,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {/* Accent dot */}
            <span style={{
              width: 3, height: 3, borderRadius: '50%',
              background: '#1C60DA',
              boxShadow: '0 0 6px rgba(28,96,218,0.8)',
              flexShrink: 0,
            }} />
            <span style={{
              fontFamily: 'Geist, sans-serif',
              fontWeight: 600,
              fontSize: 'clamp(11px, 0.9vw, 13px)',
              color: 'rgba(206,212,242,0.92)',
              letterSpacing: '0.01em',
            }}>{item.label}</span>
          </div>
          <div style={{
            paddingLeft: 11,
            fontFamily: 'Geist Mono, monospace',
            fontSize: 'clamp(9px, 0.75vw, 11px)',
            color: 'rgba(206,212,242,0.42)',
            letterSpacing: '0.10em',
            textTransform: 'uppercase',
          }}>{item.detail}</div>
        </div>
      ))}
    </div>
  );
}

function Hero({ onNavigate }) {
  const heroRef     = React.useRef(null);
  const bgRef       = React.useRef(null);
  const overlayRef  = React.useRef(null);
  const wordmarkRef = React.useRef(null);
  const [ready, setReady] = React.useState(false);
  const { lang } = React.useContext(window.LangContext);
  const t = window.ffT[lang].hero;
  const isTouch = React.useMemo(
    () => window.matchMedia('(pointer: coarse)').matches, []
  );

  // Wait for loader to exit before animating in
  React.useEffect(() => {
    if (document.body.classList.contains('is-ready')) { setReady(true); return; }
    const obs = new MutationObserver(() => {
      if (document.body.classList.contains('is-ready')) { setReady(true); obs.disconnect(); }
    });
    obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
    const t = setTimeout(() => setReady(true), 5000);
    return () => { obs.disconnect(); clearTimeout(t); };
  }, []);

  const mounted = ready;

  // Scroll-driven parallax — rAF-throttled, direct DOM writes
  // Disabled on touch devices: the scale/translate causes jank on mobile.
  React.useEffect(() => {
    if (window.matchMedia('(pointer: coarse)').matches) return;
    let raf = 0;
    const update = () => {
      const y  = window.scrollY;
      const vh = window.innerHeight || 800;
      const p  = Math.min(1, y / vh);

      if (bgRef.current) {
        bgRef.current.style.transform =
          `translate3d(0, ${y * 0.28}px, 0) scale(${1 + p * 0.04})`;
      }
      if (overlayRef.current) {
        overlayRef.current.style.opacity = String(0.5 + p * 0.4);
      }
      if (wordmarkRef.current) {
        wordmarkRef.current.style.opacity   = String(Math.max(0, 1 - p * 1.5));
        wordmarkRef.current.style.transform = `translate3d(0, ${p * 36}px, 0)`;
      }
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    if (window.lenis?.on) window.lenis.on('scroll', onScroll);
    else window.addEventListener('scroll', onScroll, { passive: true });
    update();
    return () => {
      if (window.lenis?.off) window.lenis.off('scroll', onScroll);
      window.removeEventListener('scroll', onScroll);
    };
  }, []);

  const buildWords = (text, baseDelay = 0, perWord = 70) =>
    text.split(' ').map((w, i) => (
      <span key={i} style={{ display: 'inline-block', overflow: 'hidden', verticalAlign: 'bottom', paddingRight: '0.25em' }}>
        <span style={{
          display: 'inline-block',
          transform: mounted ? 'translateY(0)' : 'translateY(110%)',
          opacity: mounted ? 1 : 0,
          transition: `transform 1100ms cubic-bezier(0.2,0.7,0.1,1) ${baseDelay + i * perWord}ms, opacity 900ms ease ${baseDelay + i * perWord}ms`,
        }}>{w}</span>
      </span>
    ));

  return (
    <section
      id="home"
      ref={heroRef}
      style={{
        position: 'relative',
        height: '100dvh',
        minHeight: 680,
        background: '#01040A',
        overflow: 'hidden',
        zIndex: 1,
      }}
    >
      {/* ── z-0  Background photo — parallax ── */}
      <div
        ref={bgRef}
        aria-hidden="true"
        style={{
          position: 'absolute', inset: isTouch ? 0 : '-18% -2% -2% -2%',
          zIndex: 0, willChange: isTouch ? 'auto' : 'transform',
          opacity: mounted ? 1 : 0,
          transition: 'opacity 2200ms cubic-bezier(0.22,0.61,0.36,1) 100ms',
        }}
      >
        <img
          src="assets/hero-background.svg"
          alt=""
          draggable={false}
          style={{
            width: '100%', height: '100%',
            objectFit: 'cover',
            objectPosition: isTouch ? '50% center' : '50% -18%',
            display: 'block',
            filter: 'saturate(0.72) contrast(1.04) brightness(0.80) hue-rotate(-4deg)',
          }}
        />
      </div>

      {/* ── z-1  Brand vignette ── */}
      <div
        ref={overlayRef}
        aria-hidden="true"
        style={{
          position: 'absolute', inset: 0, zIndex: 1,
          opacity: 0.5, willChange: isTouch ? 'auto' : 'opacity',
          background: `
            linear-gradient(to top,
              #01040A 0%, rgba(2,6,23,0.90) 25%,
              rgba(14,22,59,0.55) 58%, rgba(14,22,59,0.14) 100%),
            radial-gradient(ellipse 72% 55% at 18% 92%, rgba(28,96,218,0.14) 0%, transparent 70%),
            radial-gradient(ellipse 55% 45% at 92% 0%, rgba(2,6,23,0.28) 0%, transparent 60%)
          `,
        }}
      />

      {/* (z-2 smoke-fx canvas injected by smoke-fx.js) */}

      {/* ── z-3  Front mist CSS drift ── */}
      <div aria-hidden="true" className="ff-hero-mist" style={{
        position: 'absolute', inset: 0, zIndex: 3,
        pointerEvents: 'none', mixBlendMode: 'screen', opacity: 0.13,
        background: `
          radial-gradient(ellipse 65% 28% at 28% 78%, rgba(206,212,242,0.16) 0%, transparent 60%),
          radial-gradient(ellipse 75% 32% at 78% 88%, rgba(156,179,255,0.12) 0%, transparent 65%)
        `,
        animation: 'ffMistDrift 32s ease-in-out infinite alternate',
      }} />

      {/* ── z-4  Top vignette — nav legibility ── */}
      <div aria-hidden="true" style={{
        position: 'absolute', left: 0, right: 0, top: 0, height: 180,
        background: 'linear-gradient(180deg, rgba(1,4,10,0.52) 0%, rgba(1,4,10,0.18) 50%, transparent 100%)',
        pointerEvents: 'none', zIndex: 4,
      }} />

      {/* ── z-4  Bottom seam — into next section ── */}
      <div aria-hidden="true" style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 200,
        background: 'linear-gradient(180deg, transparent 0%, rgba(1,4,10,0.65) 55%, #01040A 100%)',
        pointerEvents: 'none', zIndex: 4,
      }} />

      {/* ── z-5  Left highlights: LLMs / Automações / etc. ── */}
      <HeroHighlights mounted={mounted} highlights={t.highlights} />

      {/* ── z-5  Top-right ticker: lat/long + availability ── */}
      <div className="ff-hero-ticker" style={{
        position: 'absolute', zIndex: 5,
        top: 'clamp(96px, 11vh, 132px)',
        right: 'clamp(20px, 5vw, 80px)',
        display: 'flex', alignItems: 'center', gap: 12,
        fontFamily: 'Geist Mono, monospace',
        fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'rgba(206,212,242,0.55)',
        opacity: mounted ? 1 : 0,
        transition: 'opacity 1000ms ease 220ms',
      }}>
        <span>27.5954° S · 48.5480° W</span>
        <span style={{ width: 1, height: 11, background: 'rgba(206,212,242,0.18)' }} />
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            width: 6, height: 6, borderRadius: '50%', background: '#1C60DA',
            boxShadow: '0 0 10px #1C60DA',
            animation: 'ffPulseAlt 2.4s ease-in-out infinite',
          }} />
          {t.available}
        </span>
      </div>

      {/* ── z-5  Bottom block: eyebrow + wordmark + CTAs + socials ── */}
      <div
        ref={wordmarkRef}
        style={{
          position: 'absolute', zIndex: 5,
          left: 'clamp(16px, 3.5vw, 56px)',
          right: 'clamp(16px, 3.5vw, 56px)',
          bottom: 'clamp(28px, 6vh, 72px)',
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          willChange: 'opacity, transform',
          gap: 'clamp(16px, 2.4vh, 28px)',
        }}
      >
        {/* Eyebrow */}
        <div style={{
          fontFamily: 'Geist Mono, monospace',
          fontSize: 11, letterSpacing: '0.30em', textTransform: 'uppercase',
          color: 'rgba(206,212,242,0.58)',
          display: 'inline-flex', alignItems: 'center', gap: 14,
          opacity: mounted ? 1 : 0,
          transform: mounted ? 'translateY(0)' : 'translateY(8px)',
          transition: 'opacity 1000ms ease 380ms, transform 1000ms ease 380ms',
        }}>
          <span style={{
            display: 'inline-block', width: 'clamp(24px, 3.5vw, 52px)', height: 1,
            background: 'rgba(206,212,242,0.28)',
            transform: mounted ? 'scaleX(1)' : 'scaleX(0)',
            transformOrigin: 'right center',
            transition: 'transform 1100ms cubic-bezier(0.2,0.7,0.1,1) 500ms',
          }} />
          {t.eyebrow}
          <span style={{
            display: 'inline-block', width: 'clamp(24px, 3.5vw, 52px)', height: 1,
            background: 'rgba(206,212,242,0.28)',
            transform: mounted ? 'scaleX(1)' : 'scaleX(0)',
            transformOrigin: 'left center',
            transition: 'transform 1100ms cubic-bezier(0.2,0.7,0.1,1) 500ms',
          }} />
        </div>

        {/* Wordmark — filled, cursor-lit */}
        <div style={{
          width: '100%',
          opacity: mounted ? 1 : 0,
          transform: mounted ? 'translateY(0) scale(1)' : 'translateY(22px) scale(0.988)',
          filter: mounted ? 'blur(0)' : 'blur(5px)',
          transition: 'opacity 1300ms cubic-bezier(0.22,0.61,0.36,1) 520ms, transform 1300ms cubic-bezier(0.22,0.61,0.36,1) 520ms, filter 1300ms ease 520ms',
        }}>
          <CursorWordmark text="Felipe Fin Fanfa" />
        </div>

        {/* CTAs — below the wordmark, inside the hero */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', justifyContent: 'center',
          opacity: mounted ? 1 : 0,
          transform: mounted ? 'translateY(0)' : 'translateY(10px)',
          transition: 'opacity 900ms ease 900ms, transform 900ms ease 900ms',
        }}>
          <button
            onClick={() => onNavigate('projects')}
            style={{
              fontFamily: 'Geist, sans-serif', fontWeight: 500,
              fontSize: 'clamp(12px, 1vw, 14px)', letterSpacing: '0.005em',
              background: 'rgba(206,212,242,0.06)', color: 'rgba(206,212,242,0.80)',
              border: '1px solid rgba(206,212,242,0.20)',
              padding: 'clamp(10px, 1.2vh, 13px) clamp(18px, 2vw, 24px)',
              borderRadius: 9999, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 9,
              transition: 'all 240ms cubic-bezier(0.4,0,0.2,1)',
              backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.borderColor = 'rgba(206,212,242,0.50)';
              e.currentTarget.style.color = '#FFFFFF';
              e.currentTarget.style.background = 'rgba(206,212,242,0.10)';
              e.currentTarget.style.transform = 'translateY(-1px)';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.borderColor = 'rgba(206,212,242,0.20)';
              e.currentTarget.style.color = 'rgba(206,212,242,0.80)';
              e.currentTarget.style.background = 'rgba(206,212,242,0.06)';
              e.currentTarget.style.transform = 'none';
            }}
          >
            {t.ctaSecondary}
            <svg width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.8" viewBox="0 0 24 24">
              <path d="M5 12h14M12 5l7 7-7 7"/>
            </svg>
          </button>

          <button
            onClick={() => {
              if (isTouch) {
                const el = document.getElementById('contact-form');
                if (el) {
                  const rect = el.getBoundingClientRect();
                  const centered = rect.top + window.scrollY - Math.max(0, (window.innerHeight - rect.height) / 2);
                  window.scrollTo({ top: centered, left: window.scrollX, behavior: 'smooth' });
                }
              } else {
                onNavigate('contact');
              }
            }}
            style={{
              fontFamily: 'Geist, sans-serif', fontWeight: 500,
              fontSize: 'clamp(12px, 1vw, 14px)', letterSpacing: '0.005em',
              background: '#1C60DA', color: '#fff', border: 'none',
              padding: 'clamp(10px, 1.2vh, 13px) clamp(18px, 2vw, 24px)',
              borderRadius: 9999, cursor: 'pointer',
              transition: 'all 240ms cubic-bezier(0.4,0,0.2,1)',
              boxShadow: '0 0 0 1px rgba(28,96,218,0.35), 0 6px 18px rgba(28,96,218,0.30)',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.transform = 'translateY(-1px)';
              e.currentTarget.style.boxShadow = '0 0 0 1px rgba(43,111,232,0.55), 0 10px 26px rgba(28,96,218,0.48)';
              e.currentTarget.style.filter = 'brightness(1.12)';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.transform = 'none';
              e.currentTarget.style.boxShadow = '0 0 0 1px rgba(28,96,218,0.35), 0 6px 18px rgba(28,96,218,0.30)';
              e.currentTarget.style.filter = 'none';
            }}
          >
            {t.ctaPrimary}
          </button>

          {/* Social links inline with CTAs */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginLeft: 6 }}>
            {[
              {
                href: 'https://github.com/felipefinfanfa', label: 'GitHub',
                icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.477 2 2 6.477 2 12c0 4.418 2.865 8.166 6.839 9.489.5.092.682-.217.682-.482 0-.237-.009-.868-.013-1.703-2.782.604-3.369-1.342-3.369-1.342-.454-1.154-1.11-1.462-1.11-1.462-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.578 9.578 0 0 1 12 6.836a9.59 9.59 0 0 1 2.504.337c1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.202 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.578.688.48C19.138 20.163 22 16.418 22 12c0-5.523-4.477-10-10-10z"/></svg>,
              },
              {
                href: 'https://linkedin.com/in/felipefinfanfa', label: 'LinkedIn',
                icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>,
              },
            ].map(({ href, label, icon }) => (
              <a key={label} href={href} target="_blank" rel="noopener noreferrer" aria-label={label}
                style={{ color: 'rgba(206,212,242,0.48)', display: 'flex', alignItems: 'center', transition: 'color 220ms ease, transform 220ms ease, filter 220ms ease' }}
                onMouseEnter={e => { e.currentTarget.style.color = '#FFFFFF'; e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.filter = 'drop-shadow(0 0 8px rgba(28,96,218,0.5))'; }}
                onMouseLeave={e => { e.currentTarget.style.color = 'rgba(206,212,242,0.48)'; e.currentTarget.style.transform = 'none'; e.currentTarget.style.filter = 'none'; }}
              >{icon}</a>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, CursorWordmark });
