// Hero. The visual is the product: a live workflow panel plus three floating status
// cards that break out of its bounds. Depth comes from ambient light, a 1px hairline
// system and pointer-driven tilt — never from decoration.

// Pointer tilt. Writes CSS custom properties instead of inline transforms so the float
// animation and the tilt can compose, and so reduced-motion can switch it off.
// track: 'self' reacts to the pointer over the element itself; 'window' keeps facing the
// cursor anywhere in the viewport and only returns to rest when it leaves the window.
function useTilt(strength = 6, track = 'self') {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const rest = () => {
      el.removeAttribute('data-tracking');
      el.style.setProperty('--ry', '0deg'); el.style.setProperty('--rx', '0deg');
      el.style.setProperty('--px', '0'); el.style.setProperty('--py', '0');
      el.style.setProperty('--lift', '0');
    };
    // One rAF-coalesced write per frame — pointermove fires far faster than paint.
    let pending = null, frame = 0;
    const apply = () => {
      frame = 0;
      const e = pending;
      if (!e) return;
      const r = el.getBoundingClientRect();
      // Against the window, distance is normalised by the viewport so the panel keeps
      // turning as the cursor travels away instead of saturating at its own edge.
      const w = track === 'window' ? window.innerWidth / 2 : r.width;
      const h = track === 'window' ? window.innerHeight / 2 : r.height;
      const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
      const px = track === 'window' ? (e.clientX - cx) / w : (e.clientX - r.left) / r.width - 0.5;
      const py = track === 'window' ? (e.clientY - cy) / h : (e.clientY - r.top) / r.height - 0.5;
      const clamp = v => Math.max(-1, Math.min(1, v));
      // Tracking is a near-immediate follow (see the short transition on [data-tracking]);
      // only the return to rest is eased, so the panel feels attached to the cursor.
      el.setAttribute('data-tracking', '1');
      el.style.setProperty('--ry', (clamp(px) * strength).toFixed(2) + 'deg');
      el.style.setProperty('--rx', (-clamp(py) * strength).toFixed(2) + 'deg');
      el.style.setProperty('--px', clamp(px).toFixed(3));
      el.style.setProperty('--py', clamp(py).toFixed(3));
      el.style.setProperty('--lift', '1');
    };
    const move = e => { pending = e; if (!frame) frame = requestAnimationFrame(apply); };
    const host = track === 'window' ? window : el;
    host.addEventListener('pointermove', move, { passive: true });
    if (track === 'window') {
      document.addEventListener('pointerleave', rest);
      window.addEventListener('blur', rest);
    } else {
      el.addEventListener('pointerleave', rest);
    }
    return () => {
      host.removeEventListener('pointermove', move);
      document.removeEventListener('pointerleave', rest);
      window.removeEventListener('blur', rest);
      el.removeEventListener('pointerleave', rest);
      if (frame) cancelAnimationFrame(frame);
    };
  }, [strength, track]);
  return ref;
}

// Ambient light and the orbital field. Pure CSS, 3–8% opacity, no imagery.
function HeroAtmos() {
  return (
    <div className="lp-atmos" aria-hidden="true">
      {/* The field plate carries the grid, trails, particles and ground glow; the CSS layers
          that used to draw those were removed so nothing competes with it. */}
      <span className="lp-atmos-plate" />
      <span className="lp-glow lp-glow--ion" />
      {[[58, 12], [72, 86], [88, 34], [64, 58], [42, 91], [95, 66]].map(([l, t], i) => (
        <span key={i} className="lp-node" style={{ left: l + '%', top: t + '%', animationDelay: i * 420 + 'ms' }} />
      ))}
      <span className="lp-atmos-veil" />
    </div>
  );
}

const HERO_STEPS = [
  { n: '01', label: 'Research', icon: 'search' },
  { n: '02', label: 'Estrategia', icon: 'trip_origin', active: true },
  { n: '03', label: 'Propuesta', icon: 'description' },
  { n: '04', label: 'Revisión', icon: 'task_alt' }
];

const HERO_ACTIVITY = [
  ['Analizando la reunión', '48 min', 'done'],
  ['Consultando CRM', '18 fuentes', 'live'],
  ['Cruzando con procesos', '32 procesos', 'live'],
  ['Redactando propuesta', 'En cola', 'queued']
];

function WorkflowPanel() {
  const { BeamFrame } = window.EG;
  const tilt = useTilt(12, 'window');
  return (
    <div className="lp-tilt lp-wf-tilt" ref={tilt}>
      <BeamFrame variant="ocean" size="line" strength={0.7} radius="var(--radius-panel)">
        <div className="lp-wf">
          <div className="lp-wf-head">
            <span className="lp-wf-dot" />
            <span className="lp-wf-title"><strong>AI</strong> WORKFLOW <span>·</span> PROPUESTA COMERCIAL</span>
            <span className="lp-wf-live">Ejecución en curso<span className="lp-wf-livedot" /></span>
          </div>
          <div className="lp-wf-steps">
            {HERO_STEPS.map((s, i) => (
              <React.Fragment key={s.n}>
                <div className={'lp-wf-step' + (s.active ? ' is-active' : '')}>
                  <span className="eg-icon lp-wf-stepicon">{s.icon}</span>
                  <span>
                    <span className="lp-wf-stepn">{s.n}</span>
                    <span className="lp-wf-steplabel">{s.label}</span>
                  </span>
                </div>
                {i < HERO_STEPS.length - 1 && <span className="eg-icon lp-wf-arrow">arrow_forward</span>}
              </React.Fragment>
            ))}
          </div>
          <div className="lp-wf-body">
            <div className="lp-wf-card">
              <span className="eg-eyebrow">Actividad del agente</span>
              <ul className="lp-wf-acts">
                {HERO_ACTIVITY.map(([label, meta, state]) => (
                  <li key={label} className={'lp-wf-act is-' + state}>
                    <span className="eg-icon lp-wf-actdot">{state === 'done' ? 'check_circle' : state === 'queued' ? 'radio_button_unchecked' : 'radio_button_checked'}</span>
                    <span className="lp-wf-actlabel">{label}</span>
                    <span className="lp-wf-actmeta">{meta}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div className="lp-wf-card">
              <span className="eg-eyebrow">Impacto estimado</span>
              <div className="lp-wf-impact">
                <div className="lp-wf-impact-l">
                  <span className="lp-wf-big">2.5<em>h / semana</em></span>
                  <span className="lp-wf-delta"><span className="eg-icon">south</span>82%</span>
                  <span className="lp-wf-note">menos tiempo<br />en ciclo actual</span>
                </div>
                <svg className="lp-wf-spark" viewBox="0 0 132 96" preserveAspectRatio="none" aria-hidden="true">
                <defs>
                  <linearGradient id="lpSpark" x1="0" y1="0" x2="1" y2="0">
                    <stop offset="0" stopColor="var(--ion-500)" stopOpacity="0.25" />
                    <stop offset="1" stopColor="var(--signal-400)" />
                  </linearGradient>
                </defs>
                <polyline points="2,88 20,78 36,83 52,60 68,66 84,42 100,46 116,20 129,8" fill="none" stroke="url(#lpSpark)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
                <circle cx="129" cy="8" r="4" fill="var(--signal-400)" />
              </svg>
              </div>
            </div>
          </div>
        </div>
      </BeamFrame>
    </div>
  );
}

function FloatCard({ children, active, delay, className = '' }) {
  const tilt = useTilt(9);
  return (
    <div ref={tilt} className={'lp-tilt lp-float ' + (active ? 'lp-float--accent ' : '') + className} style={{ animationDelay: delay }}>
      {children}
    </div>
  );
}

function FloatingCards() {
  const { Avatar } = window.EG;
  // The accent rotates between the three cards so the group reads as one live system
  // rather than three static badges. Paused for reduced-motion users.
  const [active, setActive] = React.useState(1);
  React.useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const t = setInterval(() => setActive(i => (i + 1) % 3), 3200);
    return () => clearInterval(t);
  }, []);
  return (
    <div className="lp-floats">
      <FloatCard active={active === 0} delay="0ms">
        <div className="lp-float-row">
          <span className="eg-icon lp-float-icon">group</span>
          <span>
            <span className="lp-float-num">4</span>
            <span className="lp-float-cap">agentes activos</span>
          </span>
        </div>
        <div className="lp-float-avatars">
          {['Marta Sanz', 'Diego Peña', 'Laura Beltrán'].map(n => <Avatar key={n} name={n} size="sm" tone="accent" />)}
          <span className="lp-float-more">+1</span>
        </div>
      </FloatCard>
      <FloatCard active={active === 1} delay="620ms">
        <span className="lp-float-badge"><span className="eg-icon">bolt</span></span>
        <span className="lp-float-title">Automatización<br />desplegada</span>
        <span className="lp-float-state"><span className="lp-float-statedot" />En producción</span>
      </FloatCard>
      <FloatCard active={active === 2} delay="1180ms">
        <span className="lp-float-badge lp-float-badge--quiet"><span className="eg-icon">smart_toy</span></span>
        <span className="lp-float-title">Agente ejecutado</span>
        <span className="lp-float-state"><span className="lp-float-statedot" />hace 2 min</span>
      </FloatCard>
    </div>
  );
}

function Hero() {
  const { MetalButton } = window.EG;
  const visualRef = React.useRef(null);
  // border-beam's wrapper reports less flow height than the panel actually renders
  // (measured: 330px allocated for a 381px panel), so the cards below it would sit inside
  // the panel. Measure the real gap once and correct it — self-healing on resize, and if
  // the library ever contains its child properly the correction becomes zero.
  React.useEffect(() => {
    const host = visualRef.current;
    if (!host) return;
    const panel = host.querySelector('.lp-wf');
    const floats = host.querySelector('.lp-floats');
    if (!panel || !floats) return;
    const OVERLAP = 6; // just enough to break the panel edge without covering its content
    const align = () => {
      floats.style.marginTop = '';
      // One-column hero: the panel and the cards are stacked and the CSS owns the
      // offset. Measuring across that break produced a huge negative pull that lifted
      // the cards over the header.
      const grid = host.parentElement;
      if (!grid || getComputedStyle(grid).gridTemplateColumns.split(' ').length < 2) return;
      const current = parseFloat(getComputedStyle(floats).marginTop) || 0;
      const delta = panel.getBoundingClientRect().bottom - floats.getBoundingClientRect().top;
      const next = Math.min(240, Math.max(0, Math.round(current + delta - OVERLAP)));
      floats.style.marginTop = next + 'px';
    };
    align();
    // text metrics settle after the webfont swap, so measure again once it is ready
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(align);
    const ro = new ResizeObserver(align);
    ro.observe(panel);
    window.addEventListener('resize', align);
    return () => { ro.disconnect(); window.removeEventListener('resize', align); };
  }, []);
  return (
    <section className="lp-hero" id="top">
      <HeroAtmos />
      <div className="lp-wrap lp-hero-grid">
        <div className="lp-hero-copy">
          <span className="eg-eyebrow">Consultoría de IA · Automatización · Software</span>
          <h1 className="lp-h1">Inteligencia artificial aplicada a <em>operaciones reales.</em></h1>
          <p className="lp-lead">
            Convertimos operaciones manuales en sistemas impulsados por IA.
            Diseñamos agentes, automatizaciones y software para empresas
            con procesos reales, datos reales y necesidad real de ejecutar.
          </p>
          <div className="lp-hero-cta">
            <MetalButton size="lg" iconRight="north_east">Analicemos tu operación</MetalButton>
            <a className="lp-link-cta" href="#casos">Ver casos<span className="eg-icon">chevron_right</span></a>
          </div>
          <div className="lp-metrics">
            {[['23', 'sistemas en producción'], ['6', 'sectores'], ['4–8', 'semanas por implementación']].map(([n, l]) => (
              <div className="lp-metric" key={l}>
                <span className="lp-metric-n">{n}<span className="lp-metric-dot" /></span>
                <span className="lp-metric-l">{l}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="lp-hero-visual" ref={visualRef}>
          <WorkflowPanel />
          <FloatingCards />
        </div>
      </div>
    </section>
  );
}

// Social proof. Deliberately restrained: sectors and outcomes, not a wall of borrowed
// logos. The four slots accept client marks when they clear.
function Proof() {
  const { Badge } = window.EG;
  return (
    <section className="lp-section--tight" style={{ borderTop: '1px solid var(--border-subtle)', borderBottom: '1px solid var(--border-subtle)', background: 'var(--bg-base)' }}>
      <div className="lp-wrap" style={{ display: 'flex', alignItems: 'center', gap: 40, flexWrap: 'wrap', justifyContent: 'space-between' }}>
        <span style={{ font: 'var(--type-mono-sm)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-label)' }}>Sectores donde operamos</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          {['Distribución industrial', 'Servicios financieros', 'Salud privada', 'Logística', 'Retail'].map(s => (
            <Badge key={s} variant="outline">{s}</Badge>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, Proof, HeroVisual: WorkflowPanel });
