// scenes-hero.jsx — the opening: huge "Ari" letterforms, dawn sky, sun ascending,
// type that breathes + reacts magnetically to cursor.
//
// Cursor influence: each letter tilts subtly toward the pointer (a "magnetic" feel)
// without ever leaving its baseline. As you scroll, the letters lift apart and
// the sun (above 'A') sets, becoming a moon — but that's handled by celestial.js.

const { useRef, useEffect, useState, useMemo } = React;

function useMouse() {
  const m = useRef({ x: 0, y: 0, nx: 0, ny: 0 });
  useEffect(() => {
    function move(e) {
      m.current.x = e.clientX;
      m.current.y = e.clientY;
      m.current.nx = (e.clientX / window.innerWidth - 0.5) * 2;
      m.current.ny = (e.clientY / window.innerHeight - 0.5) * 2;
    }
    window.addEventListener('pointermove', move, { passive: true });
    return () => window.removeEventListener('pointermove', move);
  }, []);
  return m;
}

// A single letter that responds magnetically to the cursor.
function MagneticLetter({ children, strength = 18, breath = 0, style }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let rafId;
    let tx = 0, ty = 0, rz = 0, cx = 0, cy = 0, cr = 0;
    function tick() {
      rafId = requestAnimationFrame(tick);
      const rect = el.getBoundingClientRect();
      const lx = rect.left + rect.width / 2;
      const ly = rect.top + rect.height / 2;
      const mx = window.__ariMouse?.x ?? lx;
      const my = window.__ariMouse?.y ?? ly;
      const dx = mx - lx, dy = my - ly;
      const d = Math.hypot(dx, dy);
      const reach = 460;
      const k = Math.max(0, 1 - d / reach);
      const targetX = (dx / Math.max(1, d)) * k * strength;
      const targetY = (dy / Math.max(1, d)) * k * strength;
      const targetR = (dx / Math.max(1, d)) * k * 4; // slight rotation
      cx += (targetX - cx) * 0.12;
      cy += (targetY - cy) * 0.12;
      cr += (targetR - cr) * 0.12;
      const breatheY = Math.sin(performance.now() / 1800 + breath) * 4;
      el.style.transform = `translate(${cx.toFixed(2)}px, ${(cy + breatheY).toFixed(2)}px) rotate(${cr.toFixed(2)}deg)`;
    }
    tick();
    return () => cancelAnimationFrame(rafId);
  }, [strength, breath]);
  return <span ref={ref} style={{ display: 'inline-block', willChange: 'transform', ...style }}>{children}</span>;
}

// Global mouse tracker for magnetic letters (avoid one listener per letter).
(function () {
  if (window.__ariMouseInit) return;
  window.__ariMouseInit = true;
  window.__ariMouse = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
  window.addEventListener('pointermove', (e) => {
    window.__ariMouse.x = e.clientX;
    window.__ariMouse.y = e.clientY;
  }, { passive: true });
})();

function Hero() {
  const wrapRef = useRef(null);
  const [progress, setProgress] = useState(0); // local progress within hero

  useEffect(() => {
    if (!window.AriScroll) return;
    return window.AriScroll.subscribe((p) => {
      // hero spans 0..0.12
      const local = Math.max(0, Math.min(1, p / 0.12));
      setProgress(local);
      const el = wrapRef.current;
      if (el) {
        // parallax — letters drift up & fade as you scroll
        el.style.setProperty('--hero-p', local.toFixed(4));
      }
    });
  }, []);

  const fade = 1 - Math.pow(progress, 1.4);
  const lift = -progress * 120;

  return (
    <section id="hero" style={{
      position: 'relative',
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'column',
      overflow: 'hidden',
      padding: '0 5vw',
    }}>
      {/* Distant horizon — a soft silhouette of mountains */}
      <svg viewBox="0 0 1440 200" preserveAspectRatio="none" style={{
        position: 'absolute', left: 0, right: 0, bottom: '20vh', width: '100%', height: '24vh',
        opacity: fade * 0.55, pointerEvents: 'none',
        maskImage: 'linear-gradient(to bottom, #000 0%, #000 50%, transparent 100%)',
        WebkitMaskImage: 'linear-gradient(to bottom, #000 0%, #000 50%, transparent 100%)',
      }}>
        <path d="M0,200 L0,140 Q90,100 180,110 Q270,70 360,85 Q450,40 540,55 Q630,90 720,80 Q810,30 900,50 Q990,95 1080,80 Q1170,40 1260,70 Q1350,100 1440,80 L1440,200 Z" fill="#c8995a" opacity=".7"/>
        <path d="M0,200 L0,165 Q120,135 240,140 Q360,110 480,125 Q600,90 720,110 Q840,80 960,100 Q1080,130 1200,115 Q1320,90 1440,110 L1440,200 Z" fill="#8a5e2a" opacity=".85"/>
      </svg>

      {/* The eyebrow — small caps mono with hairline lines */}
      <div style={{
        fontFamily: 'var(--mono)',
        fontSize: 11,
        letterSpacing: '0.55em',
        textTransform: 'uppercase',
        color: 'var(--sepia)',
        display: 'flex', alignItems: 'center', gap: 18,
        marginTop: 'min(14vh, 120px)',
        marginBottom: 56,
        opacity: fade,
        transform: `translateY(${lift * 0.4}px)`,
        transition: 'opacity .8s',
      }}>
        <span style={{ width: 80, height: 1, background: 'linear-gradient(90deg, transparent, currentColor)' }}></span>
        <span style={{ animation: 'fadeIn 1.2s .2s both' }}>A field guide to a quieter day</span>
        <span style={{ width: 80, height: 1, background: 'linear-gradient(90deg, currentColor, transparent)' }}></span>
      </div>

      {/* The wordmark — huge "Ari" with magnetic letters */}
      <h1 ref={wrapRef} style={{
        fontFamily: 'var(--serif)',
        fontSize: 'clamp(180px, 26vw, 420px)',
        lineHeight: 0.82,
        fontWeight: 400,
        letterSpacing: '-0.06em',
        position: 'relative',
        display: 'flex',
        alignItems: 'flex-end',
        gap: '0.02em',
        transform: `translateY(${lift}px)`,
        opacity: fade,
        margin: 0,
      }}>
        <MagneticLetter strength={22} breath={0} style={{
          fontStyle: 'italic',
          background: 'linear-gradient(180deg, #2c1f10 0%, #5a3f1c 35%, #b07d28 65%, #d4a85a 100%)',
          WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
          backgroundSize: '100% 220%',
          animation: 'gradDrift 11s ease-in-out infinite alternate',
        }}>A</MagneticLetter>
        <MagneticLetter strength={20} breath={1.4} style={{
          background: 'linear-gradient(180deg, #2c1f10 0%, #5a3f1c 40%, #8a5e2a 80%, #b07d28 100%)',
          WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
          backgroundSize: '100% 220%',
          animation: 'gradDrift 13s ease-in-out infinite alternate',
        }}>r</MagneticLetter>
        <MagneticLetter strength={26} breath={2.8} style={{
          fontStyle: 'italic',
          background: 'linear-gradient(180deg, #2c1f10 0%, #7e5a2c 45%, #b07d28 75%, #d4a85a 100%)',
          WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
          backgroundSize: '100% 220%',
          animation: 'gradDrift 14s ease-in-out infinite alternate',
          padding: '0 0.08em',
        }}>i</MagneticLetter>

        {/* "LABS" — small caps mono next to the wordmark */}
        <span style={{
          fontFamily: 'var(--mono)',
          fontWeight: 300,
          fontSize: 'clamp(20px, 2vw, 36px)',
          letterSpacing: '0.45em',
          color: 'var(--sepia)',
          paddingBottom: '0.6em',
          marginLeft: '0.4em',
          alignSelf: 'flex-end',
          textTransform: 'uppercase',
          opacity: 0.85,
        }}>Labs</span>
      </h1>

      {/* Subtitle — the lede */}
      <p style={{
        fontFamily: 'var(--serif)',
        fontSize: 'clamp(20px, 2vw, 30px)',
        fontStyle: 'italic',
        color: 'var(--sepia)',
        maxWidth: 720,
        textAlign: 'center',
        lineHeight: 1.4,
        marginTop: 60,
        opacity: fade,
        transform: `translateY(${-lift * -0.3}px)`,
      }}>
        Four <em style={{ fontStyle: 'normal', color: 'var(--gold)' }}>small things</em> for one life.<br/>
        Quiet software, made on a shelf in Manchester.
      </p>

      {/* Bottom: scroll cue (subtle vertical line) */}
      <div style={{
        position: 'absolute',
        bottom: 36,
        left: '50%',
        transform: 'translateX(-50%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
        fontFamily: 'var(--mono)',
        fontSize: 10,
        letterSpacing: '0.4em',
        textTransform: 'uppercase',
        color: 'var(--sepia)',
        opacity: fade * 0.55,
        pointerEvents: 'none',
      }}>
        <span style={{
          width: 1, height: 64,
          background: 'linear-gradient(180deg, currentColor, transparent)',
          transformOrigin: 'top',
          animation: 'lineDraw 2.4s ease-in-out infinite',
        }}></span>
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
        @keyframes gradDrift { 0% { background-position: 50% 0% } 100% { background-position: 50% 100% } }
        @keyframes lineDraw { 0%, 100% { transform: scaleY(.3) } 50% { transform: scaleY(1) } }
      `}</style>
    </section>
  );
}

window.Hero = Hero;
window.MagneticLetter = MagneticLetter;
