function N8NNode({ x, y, icon, label, color, delay = 0 }) {
  return (
    <g transform={`translate(${x}, ${y})`}>
      <g style={{ animation: `nodePulse 3s ease-in-out infinite`, animationDelay: `${delay}s`, transformOrigin: 'center' }}>
        <rect x="-42" y="-30" width="84" height="60" rx="14" fill="#14162a" stroke="rgba(255,255,255,0.14)" />
        <circle cx="0" cy="-6" r="14" fill={color} />
        <text x="0" y="-2" textAnchor="middle" fontSize="14" fill="#0a0b16" fontWeight="600" fontFamily="var(--font-mono)">{icon}</text>
        <text x="0" y="22" textAnchor="middle" fontSize="9" fill="#a5a8b8" fontFamily="var(--font-mono)" letterSpacing="0.05em">{label}</text>
      </g>
    </g>
  );
}

function FlowLine({ from, to, delay = 0 }) {
  const d = `M${from.x + 42} ${from.y} C ${from.x + 80} ${from.y}, ${to.x - 80} ${to.y}, ${to.x - 42} ${to.y}`;
  return (
    <>
      <path d={d} fill="none" stroke="rgba(124,140,255,0.25)" strokeWidth="2" strokeDasharray="4 4" />
      <circle r="4" fill="#22d3ee" style={{ filter: 'drop-shadow(0 0 6px #22d3ee)' }}>
        <animateMotion dur="3s" repeatCount="indefinite" begin={`${delay}s`} path={d} />
      </circle>
    </>
  );
}

function AutomationSection() {
  const useCases = [
    { t: 'Lead automático a CRM', d: 'Captura del formulario → valida → enriquece → CRM → email de bienvenida.', save: '6 h/semana' },
    { t: 'Sincronización de stock', d: 'Tienda ↔ proveedor ↔ almacén. Un cambio, todo el sistema actualizado.', save: '12 h/semana' },
    { t: 'Facturación sin tocar Excel', d: 'Venta → factura PDF → envía por email → archiva en Drive → anota en contabilidad.', save: '8 h/semana' },
    { t: 'Atención 24/7 con IA', d: 'WhatsApp + email → IA clasifica → responde o deriva al humano según urgencia.', save: '20 h/semana' },
  ];

  return (
    <section id="automation" className="shell" style={{ position: 'relative' }}>
      {/* Accent bg */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse 70% 60% at 50% 40%, rgba(34,211,238,0.08), transparent 60%)'
      }} />
      <div className="container" style={{ position: 'relative' }}>
        <div className="sh reveal" style={{ textAlign: 'center', margin: '0 auto 64px' }}>
          <span className="eyebrow"><span className="dot"/>n8n · Automatizaciones</span>
          <h2 className="h-section" style={{ marginTop: 20 }}>Deja que los flujos<br/><span className="grad-text">hagan el trabajo repetitivo.</span></h2>
          <p className="h-sub" style={{ margin: '20px auto 0' }}>Conectamos tus herramientas con n8n para que tu equipo se dedique a lo que importa. Tu negocio funciona solo, tú descansas mejor.</p>
        </div>

        {/* Workflow diagram */}
        <div className="reveal" style={{
          background: 'linear-gradient(180deg, rgba(14,16,32,0.9), rgba(8,9,18,0.9))',
          border: '1px solid var(--border-2)',
          borderRadius: 24,
          padding: 48,
          marginBottom: 48,
          position: 'relative',
          overflow: 'hidden'
        }}>
          {/* Top chrome */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 28, paddingBottom: 20, borderBottom: '1px solid var(--border)' }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: '#ea4b71', display:'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 700, color: '#fff' }}>n8n</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>lead-to-crm.workflow</div>
                <div style={{ fontSize: 11, color: 'var(--text-mute)', fontFamily: 'var(--font-mono)' }}>Activo · ejecutado 2,341 veces</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#22d3ee', boxShadow: '0 0 10px #22d3ee' }} />
              <span style={{ fontSize: 12, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>Live</span>
            </div>
          </div>

          {/* SVG flow */}
          <svg viewBox="0 0 900 260" style={{ width: '100%', height: 'auto' }}>
            <FlowLine from={{x:80,y:130}} to={{x:260,y:80}} delay={0} />
            <FlowLine from={{x:80,y:130}} to={{x:260,y:180}} delay={0.3} />
            <FlowLine from={{x:260,y:80}} to={{x:460,y:130}} delay={0.6} />
            <FlowLine from={{x:260,y:180}} to={{x:460,y:130}} delay={0.9} />
            <FlowLine from={{x:460,y:130}} to={{x:660,y:80}} delay={1.2} />
            <FlowLine from={{x:460,y:130}} to={{x:660,y:180}} delay={1.5} />
            <FlowLine from={{x:660,y:80}} to={{x:840,y:130}} delay={1.8} />
            <FlowLine from={{x:660,y:180}} to={{x:840,y:130}} delay={2.1} />

            <N8NNode x={80} y={130} icon="→" label="FORM" color="#7c8cff" />
            <N8NNode x={260} y={80} icon="✓" label="VALIDATE" color="#22d3ee" delay={0.2} />
            <N8NNode x={260} y={180} icon="◎" label="ENRICH" color="#22d3ee" delay={0.3} />
            <N8NNode x={460} y={130} icon="⬡" label="LOGIC" color="#c4b5fd" delay={0.5} />
            <N8NNode x={660} y={80} icon="▤" label="CRM" color="#fbbf24" delay={0.7} />
            <N8NNode x={660} y={180} icon="✉" label="EMAIL" color="#fbbf24" delay={0.8} />
            <N8NNode x={840} y={130} icon="✦" label="DONE" color="#86efac" delay={1} />
          </svg>

          {/* Bottom stats */}
          <div className="automation-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24, marginTop: 32, paddingTop: 28, borderTop: '1px solid var(--border)' }}>
            {[
              ['47', 'Integraciones activas'],
              ['2.3k', 'Ejecuciones / mes'],
              ['180h', 'Ahorradas / mes'],
              ['99.8%', 'Fiabilidad'],
            ].map(([v, l]) => (
              <div key={l}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em' }}>{v}</div>
                <div style={{ fontSize: 11, color: 'var(--text-mute)', fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: 4 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Use cases */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
          {useCases.map((uc, i) => (
            <div key={uc.t} className={`card reveal d${i%4}`} style={{ padding: 24 }}>
              <div style={{
                display: 'inline-block', fontFamily: 'var(--font-mono)', fontSize: 10,
                letterSpacing: '0.1em', textTransform: 'uppercase',
                color: '#86efac', padding: '4px 10px',
                background: 'rgba(134,239,172,0.08)', border: '1px solid rgba(134,239,172,0.2)',
                borderRadius: 999, marginBottom: 16
              }}>Ahorra {uc.save}</div>
              <h4 style={{ fontSize: 17, fontWeight: 500, marginBottom: 8, letterSpacing: '-0.01em' }}>{uc.t}</h4>
              <p style={{ fontSize: 13.5, color: 'var(--text-dim)', lineHeight: 1.55 }}>{uc.d}</p>
            </div>
          ))}
        </div>

        <style>{`
          @keyframes nodePulse {
            0%,100% { transform: scale(1); }
            50% { transform: scale(1.03); }
          }
        `}</style>
      </div>
    </section>
  );
}
window.AutomationSection = AutomationSection;
