// nexa-sections-2.jsx — Sistemas, Proceso, CTA, Footer

// ---------- Sistemas ----------
const Sistemas = () => {
  const [active, setActive] = React.useState(0);
  const items = [
    {
      tag: "WhatsApp",
      t: "WhatsApp centralizado",
      d: "Todas las consultas en un solo lugar. Nada se pierde entre teléfonos.",
      mock: <MockChat />,
    },
    {
      tag: "Pipeline",
      t: "Pipeline industrial",
      d: "Qué trabajos están cotizados, aprobados o pendientes. En una pantalla.",
      mock: <MockPipeline />,
    },
    {
      tag: "Panel",
      t: "Panel comercial",
      d: "Consultas, cierres y facturación en tiempo real.",
      mock: <MockDashboard />,
    },
    {
      tag: "Clientes",
      t: "Clientes y presupuestos",
      d: "Historial de cada cliente, cada trabajo, cada presupuesto.",
      mock: <MockCRM />,
    },
  ];
  return (
    <section id="sistemas" className="section" style={{ position: 'relative' }}>
      <div className="container">
        <div className="reveal" style={{ marginBottom: 64, maxWidth: 760, marginLeft: 'auto', marginRight: 'auto', textAlign: 'center' }}>
          <span className="eyebrow">04 · El sistema</span>
          <h2 className="h2" style={{ marginTop: 22 }}>
            Así se ve <span style={{ fontStyle: 'italic', color: 'var(--fg-2)' }}>funcionando.</span>
          </h2>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.3fr)', gap: 48, alignItems: 'start' }} className="sistemas-grid">
          {/* List */}
          <div className="reveal" style={{ display: 'flex', flexDirection: 'column' }}>
            {items.map((it, i) => (
              <button key={i} onClick={() => setActive(i)} style={{
                textAlign: 'left', padding: '24px 0',
                borderBottom: '1px solid var(--border)',
                display: 'flex', alignItems: 'flex-start', gap: 20,
                opacity: active === i ? 1 : 0.5,
                transition: 'opacity .3s',
                flexWrap: 'wrap',
              }}>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.18em', color: 'var(--fg-3)', minWidth: 28, paddingTop: 8 }}>0{i+1}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--accent-2)', marginBottom: 6 }}>{it.tag}</div>
                  <div className="h3" style={{ marginBottom: active === i ? 10 : 0 }}>{it.t}</div>
                  <div style={{
                    maxHeight: active === i ? 600 : 0,
                    opacity: active === i ? 1 : 0,
                    overflow: 'hidden',
                    transition: 'max-height .5s cubic-bezier(.2,.8,.2,1), opacity .4s',
                  }}>
                    <p className="body" style={{ paddingTop: 4 }}>{it.d}</p>
                    <div className="sistema-mock-mobile" style={{ marginTop: 18, padding: 16, background: 'linear-gradient(135deg, #0B121F, #131C2E)', border: '1px solid var(--border-2)', borderRadius: 16, display: 'none' }}>
                      {it.mock}
                    </div>
                  </div>
                </div>
                <span style={{
                  width: 32, height: 32, borderRadius: '50%',
                  border: '1px solid var(--border-2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--fg-2)',
                  background: active === i ? 'var(--accent)' : 'transparent',
                  borderColor: active === i ? 'var(--accent)' : 'var(--border-2)',
                  transition: 'all .3s',
                  flexShrink: 0,
                }}>
                  <ArrowR size={12} />
                </span>
              </button>
            ))}
          </div>

          {/* Mock viewer */}
          <div className="reveal d2" style={{
            position: 'sticky', top: 100,
            background: 'linear-gradient(135deg, #0B121F, #131C2E)',
            border: '1px solid var(--border-2)',
            borderRadius: 24,
            padding: 32, minHeight: 520,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            overflow: 'hidden',
            boxShadow: '0 30px 80px rgba(0,0,0,0.5)',
          }} className="mock-viewer">
            {items.map((it, i) => (
              <div key={i} style={{
                position: 'absolute', inset: 32, padding: 8,
                opacity: active === i ? 1 : 0,
                transform: `translateY(${active === i ? 0 : 20}px) scale(${active === i ? 1 : 0.96})`,
                transition: 'opacity .5s, transform .5s cubic-bezier(.2,.8,.2,1)',
                pointerEvents: active === i ? 'auto' : 'none',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {it.mock}
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// --- Animated counter hook ---
const useCounter = (target, { duration = 1500, decimals = 0, suffix = '', prefix = '' } = {}) => {
  const [val, setVal] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    let started = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !started) {
          started = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(target * eased);
            if (t < 1) requestAnimationFrame(tick);
            else setVal(target);
          };
          requestAnimationFrame(tick);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [target, duration]);
  const formatted = decimals === 0
    ? Math.floor(val).toLocaleString('es-AR')
    : val.toFixed(decimals);
  return { ref, text: prefix + formatted + suffix };
};

// --- MockChat: animated typing conversation ---
const MockChat = () => {
  const [step, setStep] = React.useState(0);
  const visibleRef = React.useRef(null);
  const [active, setActive] = React.useState(false);
  React.useEffect(() => {
    const el = visibleRef.current; if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) setActive(true); });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  React.useEffect(() => {
    if (!active) return;
    // pasos 0..6 normales, 7 = pausa de 3.5s antes de reset
    const seq = [800, 1400, 1100, 1600, 1300, 1500, 3500];
    let i = 0;
    let id;
    const tick = () => {
      setStep(s => (s + 1) % 8);
      i++;
      id = setTimeout(tick, seq[i % seq.length]);
    };
    id = setTimeout(tick, 600);
    return () => clearTimeout(id);
  }, [active]);

  const showMsg1 = step >= 2 && step <= 7;
  const showMsg2 = step >= 4 && step <= 7;
  const showMsg3 = step >= 5 && step <= 7;
  const showMsg4 = step >= 6 && step <= 7;
  const typingThem = step === 1;
  const typingMe = step === 3;

  return (
    <div ref={visibleRef} style={{ width: '100%', maxWidth: 380, fontFamily: 'var(--sans)' }}>
      <div style={{ background: '#0E1726', borderRadius: 18, overflow: 'hidden', border: '1px solid var(--border)' }}>
        <div style={{ padding: '14px 18px', background: '#0A101C', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--serif-wordmark)', fontWeight: 500, fontSize: 13, letterSpacing: 1 }}>N</div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Nexa Bot</div>
            <div style={{ fontSize: 10.5, color: 'var(--whatsapp)', display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--whatsapp)' }} /> En línea
            </div>
          </div>
        </div>
        <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 8, minHeight: 280 }}>
          {showMsg1 && <Msg side="them">Hola, quería un presupuesto para una estructura metálica.</Msg>}
          {typingMe && <TypingDots side="me" />}
          {showMsg2 && <Msg side="me">¡Hola! Perfecto. ¿Podés enviarnos medidas o foto de referencia?</Msg>}
          {showMsg3 && <Msg side="them">Sí, te paso ahora.</Msg>}
          {showMsg4 && <Msg side="me">Genial. Registramos tu consulta y un asesor te envía el presupuesto.</Msg>}
          {typingThem && <TypingDots side="them" />}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--fg-3)', fontSize: 11, marginTop: 'auto', paddingTop: 8 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 8px var(--accent)' }} />
            IA respondiendo · derivá si necesita
          </div>
        </div>
      </div>
    </div>
  );
};
const Msg = ({ side, children }) => (
  <div style={{
    alignSelf: side === 'me' ? 'flex-end' : 'flex-start',
    maxWidth: '80%',
    padding: '9px 13px',
    borderRadius: side === 'me' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
    background: side === 'me' ? 'var(--accent)' : '#1A2236',
    color: side === 'me' ? '#04080F' : 'var(--fg)',
    fontSize: 13, lineHeight: 1.42,
    animation: 'msgIn .45s cubic-bezier(0.16,1,0.3,1) both',
  }}>{children}</div>
);
const TypingDots = ({ side }) => (
  <div style={{
    alignSelf: side === 'me' ? 'flex-end' : 'flex-start',
    padding: '10px 14px',
    borderRadius: 14,
    background: side === 'me' ? 'rgba(77,124,254,0.4)' : '#1A2236',
    display: 'flex', gap: 4,
    animation: 'msgIn .35s cubic-bezier(0.16,1,0.3,1) both',
  }}>
    {[0, 1, 2].map(i => (
      <span key={i} style={{
        width: 5, height: 5, borderRadius: '50%',
        background: side === 'me' ? '#04080F' : 'var(--fg-2)',
        animation: `typingDot 1.2s ease-in-out ${i * 0.18}s infinite`,
      }} />
    ))}
  </div>
);

// --- MockPipeline: lead moves from Nuevos → Contactados → Cerrados ---
const MockPipeline = () => {
  const [phase, setPhase] = React.useState(0); // 0=Nuevos, 1=Contactados, 2=Cerrados
  const [counts, setCounts] = React.useState([12, 8, 5]);
  const [activeRef, setActiveRef] = React.useState(false);
  const rootRef = React.useRef(null);
  React.useEffect(() => {
    const el = rootRef.current; if (!el) return;
    const io = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) setActiveRef(true); }), { threshold: 0.3 });
    io.observe(el); return () => io.disconnect();
  }, []);
  React.useEffect(() => {
    if (!activeRef) return;
    let i = 0;
    let id;
    const tick = () => {
      setPhase(p => {
        const next = (p + 1) % 3;
        if (next === 1) setCounts(c => [c[0] - 1, c[1] + 1, c[2]]);
        else if (next === 2) setCounts(c => [c[0], c[1] - 1, c[2] + 1]);
        else setCounts([12, 8, 5]);
        return next;
      });
      i++;
      // después de completar el ciclo (3 fases) deja 3s antes de seguir
      const delay = (i % 3 === 0) ? 5200 : 2200;
      id = setTimeout(tick, delay);
    };
    id = setTimeout(tick, 2200);
    return () => clearTimeout(id);
  }, [activeRef]);

  const cols = [
    { t: "Consulta", c: "#7AA0FF" },
    { t: "Cotizado", c: "#F5C26B" },
    { t: "Aprobado", c: "#5BD9A6" },
  ];

  return (
    <div ref={rootRef} className="mock-pipeline-grid" style={{ width: '100%', display: 'flex', gap: 12, position: 'relative' }}>
      {cols.map((col, i) => (
        <div key={i} style={{ flex: 1, background: '#0E1726', borderRadius: 14, padding: 14, border: phase === i ? '1px solid rgba(122,160,255,0.4)' : '1px solid var(--border)', transition: 'border-color .4s', position: 'relative' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <span style={{ fontSize: 10.5, fontFamily: 'var(--mono)', letterSpacing: '0.12em', color: 'var(--fg-2)', textTransform: 'uppercase' }}>{col.t}</span>
            <span style={{ fontSize: 11, color: col.c, fontFamily: 'var(--mono)', fontWeight: 500 }}>{counts[i]}</span>
          </div>
          <div className="pipeline-cards" style={{ display: 'flex', flexDirection: 'column', gap: 8, minHeight: 140 }}>
            {Array.from({ length: 3 }).map((_, j) => {
              const isActive = phase === i && j === 0;
              return (
                <div key={`${i}-${j}-${phase}`} style={{
                  background: isActive ? 'rgba(77,124,254,0.12)' : '#131C2E',
                  borderRadius: 8, padding: '10px 12px',
                  border: isActive ? '1px solid rgba(122,160,255,0.45)' : '1px solid var(--border)',
                  transition: 'all .4s cubic-bezier(0.16,1,0.3,1)',
                  transform: isActive ? 'translateX(0) scale(1.02)' : 'translateX(0) scale(1)',
                  boxShadow: isActive ? '0 8px 24px rgba(77,124,254,0.2)' : 'none',
                  animation: isActive ? 'msgIn .5s cubic-bezier(0.16,1,0.3,1) both' : 'none',
                }}>
                  <div style={{ height: 8, width: '70%', borderRadius: 3, background: isActive ? 'rgba(122,160,255,0.5)' : 'rgba(255,255,255,0.12)', marginBottom: 6, transition: 'background .4s' }} />
                  <div style={{ height: 6, width: '50%', borderRadius: 3, background: 'rgba(255,255,255,0.06)' }} />
                  <div style={{ display: 'flex', gap: 5, marginTop: 8, alignItems: 'center' }}>
                    <div style={{ width: 6, height: 6, borderRadius: '50%', background: col.c, boxShadow: isActive ? `0 0 8px ${col.c}` : 'none' }} />
                    <div style={{ height: 6, width: 24, borderRadius: 3, background: 'rgba(255,255,255,0.08)' }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
};

// --- MockDashboard: counters + drawing chart + bars ---
const MockDashboard = () => {
  const sales    = useCounter(2890000, { duration: 2000, prefix: '$ ' });
  const orders   = useCounter(10,   { duration: 1400 });
  const contacts = useCounter(78,   { duration: 1600 });
  const closed   = useCounter(10,   { duration: 1500 });
  const today    = useCounter(327,  { duration: 1700 });

  return (
    <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Hero stat: ventas hoy big */}
      <div ref={sales.ref} style={{ background: 'linear-gradient(135deg, #0E1726, #131C2E)', border: '1px solid var(--border-2)', borderRadius: 14, padding: '20px 22px', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: 0, right: 0, width: 180, height: 180, background: 'radial-gradient(circle, rgba(91,217,166,0.18), transparent 70%)' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', position: 'relative' }}>
          <div>
            <div style={{ fontSize: 11, fontFamily: 'var(--mono)', letterSpacing: '0.16em', color: 'var(--fg-3)', textTransform: 'uppercase' }}>Facturado hoy</div>
            <div style={{ fontSize: 44, fontFamily: 'var(--serif-display)', color: 'var(--fg)', marginTop: 6, letterSpacing: '-0.02em', lineHeight: 1 }} className="mock-dash-hero-num">{sales.text}</div>
            <div style={{ display: 'flex', gap: 18, marginTop: 14 }}>
              <span ref={orders.ref} style={{ fontSize: 12, color: 'var(--fg-2)' }}>
                <span style={{ fontFamily: 'var(--mono)', color: 'var(--fg)', fontSize: 14, marginRight: 4 }}>{orders.text}</span>
                ventas
              </span>
              <span style={{ fontSize: 12, color: '#5BD9A6', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span style={{ fontFamily: 'var(--mono)' }}>↑ +24%</span> vs ayer
              </span>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10.5, fontFamily: 'var(--mono)', color: '#5BD9A6', letterSpacing: '0.14em' }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#5BD9A6', animation: 'pulse 1.6s ease-in-out infinite' }} />
            EN VIVO
          </div>
        </div>
      </div>

      {/* Secondary stats row */}
      <div className="mock-dash-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        <div ref={contacts.ref} style={{ background: '#0E1726', border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--mono)', letterSpacing: '0.14em', color: 'var(--fg-3)', textTransform: 'uppercase' }}>Contactados</div>
          <div style={{ fontSize: 28, fontFamily: 'var(--serif-display)', color: 'var(--fg)', marginTop: 4 }}>{contacts.text}</div>
          <div style={{ fontSize: 10.5, color: '#5BD9A6', marginTop: 2, fontFamily: 'var(--mono)' }}>+18 hoy</div>
        </div>
        <div ref={closed.ref} style={{ background: '#0E1726', border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--mono)', letterSpacing: '0.14em', color: 'var(--fg-3)', textTransform: 'uppercase' }}>Cerrados</div>
          <div style={{ fontSize: 28, fontFamily: 'var(--serif-display)', color: 'var(--fg)', marginTop: 4 }}>{closed.text}</div>
          <div style={{ fontSize: 10.5, color: '#5BD9A6', marginTop: 2, fontFamily: 'var(--mono)' }}>+9% sem.</div>
        </div>
        <div ref={today.ref} style={{ background: '#0E1726', border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--mono)', letterSpacing: '0.14em', color: 'var(--fg-3)', textTransform: 'uppercase' }}>Msj contestados</div>
          <div style={{ fontSize: 28, fontFamily: 'var(--serif-display)', color: 'var(--fg)', marginTop: 4 }}>{today.text}</div>
          <div style={{ fontSize: 10.5, color: 'var(--accent-2)', marginTop: 2, fontFamily: 'var(--mono)' }}>último: 2m</div>
        </div>
      </div>

      {/* Chart with growing line + bars */}
      <div style={{ background: '#0E1726', border: '1px solid var(--border)', borderRadius: 12, padding: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14, alignItems: 'baseline' }}>
          <span style={{ fontSize: 12, color: 'var(--fg-2)', fontFamily: 'var(--mono)' }}>Ventas / día</span>
          <span style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily: 'var(--mono)' }}>últimos 30d</span>
        </div>
        <svg viewBox="0 0 320 110" style={{ width: '100%', height: 110, overflow: 'visible' }}>
          <defs>
            <linearGradient id="dashGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="#4D7CFE" stopOpacity="0.4"/>
              <stop offset="100%" stopColor="#4D7CFE" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {[
            { x: 10, h: 30 }, { x: 30, h: 38 }, { x: 50, h: 28 }, { x: 70, h: 50 },
            { x: 90, h: 42 }, { x: 110, h: 60 }, { x: 130, h: 52 }, { x: 150, h: 70 },
            { x: 170, h: 64 }, { x: 190, h: 78 }, { x: 210, h: 70 }, { x: 230, h: 86 },
            { x: 250, h: 80 }, { x: 270, h: 92 }, { x: 290, h: 100 },
          ].map((b, i) => (
            <rect key={i} x={b.x} y={110 - b.h} width="10" height={b.h} rx="2" fill="rgba(122,160,255,0.18)" style={{ transformOrigin: `${b.x + 5}px 110px`, animation: `barGrow .8s cubic-bezier(0.16,1,0.3,1) ${i * 0.04}s both` }} />
          ))}
          <path d="M0 85 L20 80 L40 70 L60 75 L80 60 L100 65 L120 50 L140 55 L160 40 L180 45 L200 35 L220 40 L240 28 L260 32 L280 22 L300 26 L320 14"
            stroke="#7AA0FF" strokeWidth="1.6" fill="none"
            strokeDasharray="800" strokeDashoffset="800"
            style={{ animation: 'drawLine 2.2s cubic-bezier(0.16,1,0.3,1) .3s forwards' }}/>
          <circle cx="320" cy="14" r="3.5" fill="#7AA0FF" style={{ animation: 'msgIn .5s ease 2.4s both' }}/>
          <circle cx="320" cy="14" r="6" fill="#7AA0FF" opacity="0.3" style={{ animation: 'pulse 1.6s ease-in-out 2.4s infinite' }}/>
        </svg>
      </div>
    </div>
  );
};

// --- MockCRM: animated rows with live updates ---
const MockCRM = () => {
  const [tick, setTick] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    let id;
    const io = new IntersectionObserver(es => es.forEach(e => {
      if (e.isIntersecting) {
        let count = 0;
        const next = () => {
          setTick(t => t + 1);
          count++;
          const delay = (count % 5 === 0) ? 5800 : 2400;
          id = setTimeout(next, delay);
        };
        id = setTimeout(next, 2400);
      } else if (id) { clearTimeout(id); id = null; }
    }), { threshold: 0.3 });
    io.observe(el);
    return () => { if (id) clearTimeout(id); io.disconnect(); };
  }, []);

  const rowsData = [
    { name: "Estructura Galpón",     baseAmount: 8400,  status: ["En curso", "Activo", "Activo"],   c: "#5BD9A6" },
    { name: "Corte Láser CNC",       baseAmount: 1850,  status: ["Activo", "Activo", "Activo"],     c: "#5BD9A6" },
    { name: "Reja Industrial 12m",   baseAmount: 3200,  status: ["Activo", "En curso", "Activo"],   c: "#F5C26B" },
    { name: "Plegado Chapa 4mm",     baseAmount: 920,   status: ["Cotizado", "En curso", "Activo"], c: "#7AA0FF" },
    { name: "Soldadura Pampa SA",    baseAmount: 14500, status: ["Activo", "Activo", "Activo"],     c: "#5BD9A6" },
  ];
  const fmt = (n) => n === 0 ? '—' : `$ ${n.toLocaleString('es-AR')}`;
  const statusColor = (s) => s === 'Activo' ? '#5BD9A6' : s === 'En curso' ? '#F5C26B' : '#7AA0FF';
  const statusBg = (s) => s === 'Activo' ? 'rgba(91,217,166,0.12)' : s === 'En curso' ? 'rgba(245,194,107,0.12)' : 'rgba(122,160,255,0.12)';
  const statusBorder = (s) => s === 'Activo' ? 'rgba(91,217,166,0.25)' : s === 'En curso' ? 'rgba(245,194,107,0.25)' : 'rgba(122,160,255,0.25)';

  // Live "new lead" indicator that pulses each tick
  const liveIdx = tick % rowsData.length;

  return (
    <div ref={ref} className="mock-crm-wrap" style={{ width: '100%', background: '#0E1726', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden' }}>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ display: 'flex', gap: 5 }}>
          <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#FF5F57' }}/>
          <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#FEBC2E' }}/>
          <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#28C840' }}/>
        </div>
        <span style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--fg-3)', marginLeft: 6 }}>nexa.crm / presupuestos</span>
        <span style={{ marginLeft: 'auto', fontSize: 10.5, fontFamily: 'var(--mono)', color: '#5BD9A6', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#5BD9A6', animation: 'pulse 1.6s ease-in-out infinite' }} /> EN VIVO
        </span>
      </div>
      <div style={{ padding: 16 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
          <thead>
            <tr style={{ color: 'var(--fg-3)', fontFamily: 'var(--mono)', textAlign: 'left', fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
              <th style={{ padding: '0 0 12px', fontWeight: 400 }}>Presupuesto</th>
              <th style={{ padding: '0 0 12px', fontWeight: 400 }}>Estado</th>
              <th style={{ padding: '0 0 12px', fontWeight: 400, textAlign: 'right', paddingRight: 16 }}>Monto</th>
              <th style={{ padding: '0 0 12px', fontWeight: 400, textAlign: 'right' }}>Últ. acción</th>
            </tr>
          </thead>
          <tbody>
            {rowsData.map((r, i) => {
              const status = r.status[tick % r.status.length];
              const amount = r.baseAmount + (i + tick) * 37 * (i % 2 === 0 ? 1 : -1) + tick * 12;
              const isLive = i === liveIdx;
              return (
                <tr key={i} style={{ borderTop: '1px solid var(--border)', transition: 'background .4s', background: isLive ? 'rgba(77,124,254,0.06)' : 'transparent' }}>
                  <td style={{ padding: '11px 0' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'rgba(122,160,255,0.15)', border: '1px solid rgba(122,160,255,0.3)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--accent-2)' }}>
                        {r.name.split(' ').map(s => s[0]).join('').slice(0, 2)}
                      </span>
                      {r.name}
                      {isLive && <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#5BD9A6', boxShadow: '0 0 8px #5BD9A6', animation: 'pulse 1.4s infinite' }} />}
                    </span>
                  </td>
                  <td>
                    <span key={`${i}-${tick}`} style={{ display: 'inline-block', fontSize: 10.5, padding: '3px 8px', borderRadius: 999, background: statusBg(status), color: statusColor(status), border: `1px solid ${statusBorder(status)}`, animation: 'msgIn .4s cubic-bezier(0.16,1,0.3,1) both' }}>{status}</span>
                  </td>
                  <td key={`a-${i}-${tick}`} style={{ color: 'var(--fg)', fontFamily: 'var(--mono)', fontSize: 12, textAlign: 'right', paddingRight: 16, animation: 'msgIn .35s cubic-bezier(0.16,1,0.3,1) both' }}>
                    {fmt(Math.max(0, amount))}
                  </td>
                  <td style={{ color: 'var(--fg-3)', fontSize: 11, textAlign: 'right', whiteSpace: 'nowrap' }}>
                    {isLive ? 'ahora' : `${(i + 1) * 4 + (tick % 5)}m`}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ---------- Proceso ----------
const Proceso = () => {
  const steps = [
    { n: "01", t: "Diagnóstico", d: "Detectamos dónde se pierden oportunidades." },
    { n: "02", t: "Captura y Organización", d: "Ordenamos consultas y presupuestos." },
    { n: "03", t: "Seguimiento Inteligente", d: "Ningún presupuesto queda olvidado." },
    { n: "04", t: "Conversión", d: "Más presupuestos convertidos en trabajos." },
    { n: "05", t: "Control y Mejora", d: "Métricas claras para mejorar decisiones." },
  ];
  const [reached, setReached] = React.useState(-1);
  const rootRef = React.useRef(null);
  React.useEffect(() => {
    const el = rootRef.current; if (!el) return;
    const io = new IntersectionObserver(es => es.forEach(e => {
      if (e.isIntersecting) {
        steps.forEach((_, i) => setTimeout(() => setReached(r => Math.max(r, i)), 400 + i * 700));
        io.unobserve(el);
      }
    }), { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <section id="proceso" className="section" style={{ background: 'var(--bg-2)', borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)' }}>
      <div className="container">
        <div className="reveal" style={{ marginBottom: 80, maxWidth: 720, marginLeft: 'auto', marginRight: 'auto', textAlign: 'center' }}>
          <span className="eyebrow">02 · Método</span>
          <h2 className="h2" style={{ marginTop: 22 }}>
            Método <span style={{ fontStyle: 'italic', color: 'var(--accent-2)' }}>FCI™</span>
          </h2>
          <p className="body" style={{ marginTop: 18, maxWidth: 440, marginLeft: 'auto', marginRight: 'auto' }}>
            Flujo Comercial Inteligente. 5 fases.
          </p>
        </div>
        <div ref={rootRef} className="proceso-grid">
          {steps.map((s, i) => {
            const on = reached >= i;
            return (
              <div key={i} className="proceso-step" style={{
                opacity: on ? 1 : 0.25,
                transform: on ? 'translateY(0)' : 'translateY(20px)',
                transition: 'opacity .8s cubic-bezier(0.16,1,0.3,1), transform .8s cubic-bezier(0.16,1,0.3,1)',
                textAlign: 'center',
                padding: '32px 18px',
                background: on ? 'rgba(255,255,255,0.02)' : 'transparent',
                border: '1px solid var(--border)',
                borderRadius: 16,
                display: 'flex', flexDirection: 'column', alignItems: 'center',
                minHeight: 240,
              }}>
                <div style={{
                  fontFamily: 'var(--serif-display)', fontSize: 'clamp(48px, 5vw, 68px)',
                  fontStyle: 'italic', lineHeight: 1, marginBottom: 18,
                  color: on ? 'var(--accent-2)' : 'var(--fg-3)',
                  transition: 'color .6s',
                }}>{s.n}</div>
                <h3 style={{ fontFamily: 'var(--serif-display)', fontSize: 19, fontWeight: 500, lineHeight: 1.2, marginBottom: 10, color: 'var(--fg)' }}>{s.t}</h3>
                <p style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.5, maxWidth: 200 }}>{s.d}</p>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};

// ---------- CTA ----------
const CTA = () => (
  <section className="section" style={{ position: 'relative', overflow: 'hidden' }}>
    <div className="orb" style={{ width: 480, height: 480, background: 'radial-gradient(circle, #4D7CFE 0%, transparent 60%)', top: '20%', left: '50%', transform: 'translateX(-50%)', opacity: 0.35 }} />
    <div className="container" style={{ position: 'relative', textAlign: 'center' }}>
      <div className="reveal" style={{ display: 'inline-flex', justifyContent: 'center', marginBottom: 40 }}>
        <NexaMark size={56} />
      </div>
      <h2 className="display reveal d1" style={{ marginBottom: 28, fontSize: 'clamp(40px, 7vw, 88px)' }}>
        Cada presupuesto sin <span style={{ fontStyle: 'italic', color: 'var(--fg-2)' }}>seguimiento</span><br/>es una oportunidad <span style={{ fontStyle: 'italic', color: 'var(--accent-2)' }}>perdida.</span>
      </h2>
      <p className="lead reveal d2" style={{ margin: '0 auto 48px', maxWidth: 520 }}>
        Analizamos tu operación comercial en 30 minutos. Cupos limitados por mes.
      </p>
      <div className="reveal d3" style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a href={CAL_URL} className="btn primary" style={{ padding: '16px 26px', fontSize: 15 }}>
          <CalendarIcon size={16} /> Agendar diagnóstico
          <ArrowUR size={14} />
        </a>
        <a href={WSP_URL} target="_blank" rel="noopener" className="btn wsp" style={{ padding: '16px 26px', fontSize: 15 }}>
          <span className="dot" />
          Hablar por WhatsApp
        </a>
      </div>
    </div>
  </section>
);

// ---------- Footer ----------
const Footer = () => (
  <footer style={{ borderTop: '1px solid var(--border)', padding: '64px 0 32px' }}>
    <div className="container">
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 48, justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 64 }}>
        <div style={{ maxWidth: 360 }}>
          <Logo markSize={40} wordSize={32} eb={10} trk={4} />
          <p style={{ fontFamily: 'var(--serif-display)', fontStyle: 'italic', fontSize: 18, color: 'var(--fg-2)', marginTop: 24 }}>
            Ayudamos a escalar negocios.
          </p>
        </div>
        <div style={{ display: 'flex', gap: 64, flexWrap: 'wrap' }}>
          <FooterCol t="Hablemos" links={[
            { l: "WhatsApp", h: WSP_URL, x: true },
            { l: "Agendar llamada", h: CAL_URL },
            { l: "Instagram @nexa.bg", h: IG_URL, x: true },
          ]} />
          <FooterCol t="Web" links={[
            { l: "Servicios", h: "#servicios" },
            { l: "Sistemas", h: "#sistemas" },
            { l: "Proceso", h: "#proceso" },
          ]} />
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16, paddingTop: 24, borderTop: '1px solid var(--border)', fontSize: 12, color: 'var(--fg-3)', fontFamily: 'var(--mono)', letterSpacing: '0.06em' }}>
        <span>© 2026 Nexa Business Growth · Argentina · LATAM</span>
        <span>Hecho con ☕ y código.</span>
      </div>
    </div>
  </footer>
);
const FooterCol = ({ t, links }) => (
  <div>
    <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.16em', color: 'var(--fg-3)', textTransform: 'uppercase', marginBottom: 18 }}>{t}</div>
    <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 12 }}>
      {links.map((l, i) => (
        <li key={i}>
          <a href={l.h} target={l.x ? '_blank' : undefined} rel={l.x ? 'noopener' : undefined} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--fg)', fontSize: 14, transition: 'color .2s' }}
             onMouseEnter={(e) => e.currentTarget.style.color = 'var(--accent-2)'}
             onMouseLeave={(e) => e.currentTarget.style.color = 'var(--fg)'}>
            {l.l} {l.x && <ArrowUR size={11} />}
          </a>
        </li>
      ))}
    </ul>
  </div>
);

const FabWsp = () => {
  const onClick = (e) => {
    e.preventDefault();
    window.open(WSP_URL, '_blank', 'noopener');
  };
  return (
    <a href={WSP_URL} onClick={onClick} target="_blank" rel="noopener noreferrer" className="fab-wsp" aria-label="WhatsApp">
      <WspIcon size={26} />
    </a>
  );
};

Object.assign(window, { Sistemas, Proceso, CTA, Footer, FabWsp });
