// pricing-footer.jsx — PricingSection, FAQ, CTAFinal, FooterSection (LIGHT THEME)

// NumberFlow port — animated count-up between price values
function useAnimatedNumber(target, duration = 520) {
  const [value, setValue] = React.useState(target);
  const fromRef = React.useRef(target);
  const lastTargetRef = React.useRef(target);
  React.useEffect(() => {
    if (target === lastTargetRef.current) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setValue(target);
      lastTargetRef.current = target;
      return;
    }
    fromRef.current = value;
    lastTargetRef.current = target;
    let raf;
    let startT;
    const tick = (t) => {
      if (startT === undefined) startT = t;
      const progress = Math.min(1, (t - startT) / duration);
      // ease-out cubic
      const eased = 1 - Math.pow(1 - progress, 3);
      const v = fromRef.current + (target - fromRef.current) * eased;
      setValue(Math.round(v));
      if (progress < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return value;
}

function AnimatedPrice({ value }) {
  const display = useAnimatedNumber(value);
  return display.toLocaleString('en-US');
}

function PricingSection() {
  const [annual, setAnnual] = React.useState(true);

  // Inline Lucide-style icons (replaces Briefcase, Database, Server from lucide-react)
  const IconPhone = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
    </svg>
  );
  const IconWhatsapp = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
      <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981z"/>
    </svg>
  );
  const IconUsers = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
      <circle cx="9" cy="7" r="4"/>
      <path d="M22 21v-2a4 4 0 0 0-3-3.87"/>
      <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
    </svg>
  );
  const IconCheckCheck = () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 6 7 17l-5-5"/>
      <path d="m22 10-7.5 7.5L13 16"/>
    </svg>
  );

  const plans = [
    {
      name: 'Starter',
      // Internal key — maps to the workspace_plan enum + Polar product lookup.
      // Scale is the top tier so it maps to `enterprise` even though the
      // marketing name is "Scale" (legacy from the Stripe schema).
      planKey: 'starter',
      description: 'Para empezar a probar tu sistema con clientes reales sin compromisos.',
      price: 79,
      yearlyPrice: 760,
      buttonText: 'Empezar gratis',
      buttonVariant: 'outline',
      features: [
        { text: 'Hasta 20 números de WhatsApp', Icon: IconWhatsapp },
        { text: '200 minutos de voz al mes', Icon: IconPhone },
        { text: 'Hasta 20 usuarios del equipo', Icon: IconUsers },
      ],
      includes: [
        'Lo básico incluye:',
        'Conexión oficial con Meta',
        'CRM integrado',
        'Agentes WhatsApp + voz ilimitados',
      ],
    },
    {
      name: 'Scale',
      planKey: 'enterprise',
      description: 'Sin límites. Para operaciones de volumen alto que necesitan escalar rápido.',
      price: 129,
      yearlyPrice: 1240,
      buttonText: 'Empezar gratis',
      buttonVariant: 'default',
      popular: true,
      features: [
        { text: 'Números de WhatsApp ilimitados', Icon: IconWhatsapp },
        { text: '700 minutos de voz al mes', Icon: IconPhone },
        { text: 'Hasta 50 usuarios del equipo', Icon: IconUsers },
      ],
      includes: [
        'Todo lo de Starter, más:',
        'Campañas de remarketing ilimitadas',
        'Números de WhatsApp sin tope',
        'Soporte prioritario',
      ],
    },
    {
      name: 'Pro',
      planKey: 'pro',
      description: 'Cuando tu operación empieza a crecer y necesitas más capacidad.',
      price: 99,
      yearlyPrice: 950,
      buttonText: 'Empezar gratis',
      buttonVariant: 'outline',
      features: [
        { text: 'Hasta 50 números de WhatsApp', Icon: IconWhatsapp },
        { text: '500 minutos de voz al mes', Icon: IconPhone },
        { text: 'Hasta 35 usuarios del equipo', Icon: IconUsers },
      ],
      includes: [
        'Todo lo de Starter, más:',
        'Más capacidad de números',
        'Más minutos de voz',
        'Equipo más grande',
      ],
    },
  ];

  return (
    <section id="precios" className="section-pad" style={{ position: 'relative' }}>
      {/* Radial blue glow background */}
      <div className="pricing-glow" aria-hidden></div>

      <div className="section-inner" style={{ position: 'relative', zIndex: 1 }}>
        {/* Headline + highlighted word */}
        <div style={{ textAlign: 'center', marginBottom: 32, maxWidth: 820, marginLeft: 'auto', marginRight: 'auto' }}>
          <RevealOnScroll>
            <h2 className="heading-display" style={{
              fontSize: 'clamp(34px, 5.5vw, 60px)',
              textWrap: 'balance',
              lineHeight: 1.06,
              letterSpacing: '-0.025em',
              color: '#0A0A0F',
            }}>
              Crece sin contratar{' '}
              <span className="pricing-headline-highlight">más</span>
            </h2>
          </RevealOnScroll>
          <RevealOnScroll delay={120}>
            <p style={{
              fontSize: 'clamp(15px, 1.6vw, 17px)',
              color: 'rgba(10,10,15,0.55)',
              lineHeight: 1.6, marginTop: 18, textWrap: 'pretty',
              maxWidth: 540, marginLeft: 'auto', marginRight: 'auto',
            }}>
              14 días gratis. Sin tarjeta. Cancelas cuando quieras. El plan que elijas se adapta a tu volumen real.
            </p>
          </RevealOnScroll>
        </div>

        {/* Animated pill toggle */}
        <RevealOnScroll delay={200}>
          <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'center',
            marginBottom: 40,
          }}>
            <div className="pricing-toggle">
              <span className={`pricing-toggle-pill${annual ? ' is-annual' : ''}`} aria-hidden></span>
              <button
                onClick={() => setAnnual(false)}
                className={`pricing-toggle-btn${!annual ? ' active' : ''}`}
                type="button">
                Mensual
              </button>
              <button
                onClick={() => setAnnual(true)}
                className={`pricing-toggle-btn${annual ? ' active' : ''}`}
                type="button">
                Anual
                <span className="pricing-toggle-save">Ahorra 20%</span>
              </button>
            </div>
          </div>
        </RevealOnScroll>

        {/* 3 cards grid */}
        <div className="pricing-grid">
          {plans.map((plan, i) => {
            // When annual is selected, show the discounted MONTHLY equivalent
            // (yearly total divided by 12) rather than the full annual price —
            // easier to compare against the monthly tier at a glance.
            const displayPrice = annual
              ? Math.round(plan.yearlyPrice / 12)
              : plan.price;
            const period = 'mes';
            const isPopular = !!plan.popular;
            const buttonClass = isPopular ? 'popular' : 'outline';
            return (
              <RevealOnScroll key={plan.name} delay={300 + i * 80}>
                <div className={`pricing-card-21${isPopular ? ' popular' : ''}`}>
                  {/* Header */}
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                    <h3 className="pricing-card-21-name">{plan.name}</h3>
                    {isPopular && (
                      <span className="pricing-card-21-popular-badge">Popular</span>
                    )}
                  </div>
                  <p className="pricing-card-21-desc">{plan.description}</p>

                  {/* Price */}
                  <div className="pricing-card-21-price-row">
                    <span className="pricing-card-21-price">$<AnimatedPrice value={displayPrice}/></span>
                    <span className="pricing-card-21-period">/{period}</span>
                  </div>

                  {/* CTA — selects the plan + persists it so onboarding can
                      route to /checkout/start after the trial workspace is
                      created. Cookie survives across signup + onboarding;
                      the onboarding wizard clears it once consumed. */}
                  <a
                    href={`/register?plan=${plan.planKey}&period=${annual ? 'year' : 'month'}`}
                    onClick={(e) => {
                      try {
                        const value = `${plan.planKey}:${annual ? 'year' : 'month'}`;
                        document.cookie = `alvex_pending_plan=${encodeURIComponent(value)}; max-age=${60 * 60 * 24 * 30}; path=/; samesite=lax`;
                      } catch (_) {}
                    }}
                    className={`pricing-card-21-cta ${buttonClass}`}
                    style={{ textAlign: 'center', textDecoration: 'none', display: 'inline-block' }}
                  >
                    {plan.buttonText}
                  </a>

                  {/* Features list */}
                  <ul className="pricing-card-21-features">
                    {plan.features.map((f, j) => (
                      <li key={j} className="pricing-card-21-feature">
                        <span className="pricing-card-21-feature-icon"><f.Icon/></span>
                        <span>{f.text}</span>
                      </li>
                    ))}
                  </ul>

                  {/* Includes section */}
                  <div className="pricing-card-21-includes-section">
                    <h4 className="pricing-card-21-includes-title">{plan.includes[0]}</h4>
                    <ul className="pricing-card-21-includes">
                      {plan.includes.slice(1).map((inc, k) => (
                        <li key={k} className="pricing-card-21-include">
                          <span className="pricing-card-21-include-check"><IconCheckCheck/></span>
                          <span>{inc}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </RevealOnScroll>
            );
          })}
        </div>

        {/* Trust row */}
        <RevealOnScroll delay={620}>
          <div className="pricing-trust">
            {[
              '14 días gratis',
              'Sin tarjeta de crédito',
              'Cancela cuando quieras',
              'Te llevas tus datos',
            ].map(label => (
              <div key={label} style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '10px 16px', borderRadius: 999,
                background: 'rgba(20,184,112,0.06)',
                border: '1px solid rgba(20,184,112,0.16)',
                fontSize: 13, fontWeight: 500,
                color: 'rgba(10,10,15,0.72)',
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                  stroke="#14B870" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 13l4 4L19 7"/>
                </svg>
                {label}
              </div>
            ))}
          </div>
        </RevealOnScroll>
      </div>
    </section>
  );
}


function FAQ() {
  const [openIdx, setOpenIdx] = React.useState(0);
  const groups = [
    {
      header: 'Producto',
      items: [
        { q: '¿Necesito un número aparte para mi agente?', a: 'No. Tu agente atiende el mismo número que ya usas para WhatsApp y llamadas. Lo conectas en un clic, sin configuraciones técnicas.' },
        { q: '¿El cliente sabe que habla con IA?', a: 'Tú decides. Por defecto el agente se presenta como tu equipo; si quieres transparencia total, lo activas con un check.' },
        { q: '¿Qué pasa si el agente no sabe responder?', a: 'Te pasa la conversación. Recibes un aviso por WhatsApp o email y respondes tú o tu equipo.' },
        { q: '¿Cuánto tarda dejarlo listo?', a: 'Una tarde. Conectar el número son 2 minutos y enseñarle tu negocio toma 15 a 20 minutos.' },
        { q: '¿Y si no estoy disponible cuando el agente necesita escalar?', a: 'No para. Mientras tú estás ocupado, el agente sigue atendiendo todo lo demás. Cuando una conversación necesita un humano, te queda en cola con todo el contexto: quién es el cliente, qué pidió y por qué lo escaló. Respondes cuando puedas y el agente sigue donde lo dejaste.' },
        { q: '¿Si se me acaba el stock o un servicio?', a: 'Le avisas al agente desde el dashboard (toma 10 segundos). A partir de ese momento deja de ofrecerlo, le dice al cliente con tus palabras, y opcionalmente le sugiere una alternativa o le agenda para cuando vuelvas a tenerlo. No hay riesgo de prometer algo que no puedes cumplir.' },
        { q: '¿Si el cliente pide algo que mi negocio no ofrece?', a: 'El agente lo reconoce y maneja la situación con tu tono. Puedes configurar tres comportamientos: decir amablemente que no se ofrece, sugerir lo más cercano que sí tienes, o pasarte la conversación para que tú veas si vale la pena la oportunidad.' },
        { q: '¿Qué pasa si supero los minutos de voz incluidos?', a: 'Te avisamos antes de llegar al límite. Puedes comprar paquetes adicionales de minutos al instante desde tu dashboard, sin interrumpir el servicio.' },
        { q: '¿Si necesito que el agente no responda en cierto horario?', a: 'Sí, configurable. Puedes definir horarios diferentes por canal (voz solo de 9 a 18h, WhatsApp 24/7) o un mensaje automático fuera de horario que pida los datos del cliente para que tú los contactes cuando abras.' },
        { q: '¿Si el agente se equivoca con un precio o promete algo erróneo?', a: 'Pasa muy poco, pero pasa. Cuando lo detectes (te avisamos si hay quejas), entras al dashboard, revisas la conversación y desde ahí mismo le contestas al cliente con la versión correcta. El agente aprende del error para no repetirlo. Tú decides si honras la oferta como gesto comercial o si le explicas la situación.' },
        { q: '¿Si tengo varios negocios o sucursales?', a: 'Cada negocio o sucursal puede tener su propio agente con personalidad, catálogo y reglas propias, todo desde una sola cuenta. Compartes los usuarios del equipo entre todos o los mantienes separados según prefieras. Funciona igual de bien para una pizzería con 3 locales que para una franquicia con 50.' },
        { q: '¿Si quiero cambiar cómo habla el agente después de un mes?', a: 'Lo cambias en minutos desde el dashboard. Editas el tono, las respuestas, los precios, la información del negocio o lo que necesites. Los cambios se aplican al instante en todas las conversaciones nuevas. No tienes que reentrenar nada ni esperar.' },
        { q: '¿Si el cliente quiere hablar con una persona específica?', a: 'El agente lo identifica y reacciona. Si esa persona está disponible, le pasa la conversación con todo el contexto. Si no, pregunta cuándo es buena hora para devolverle la llamada o mensaje, registra la solicitud y le avisa a la persona por WhatsApp o email.' },
      ],
    },
    {
      header: 'WhatsApp y Meta',
      items: [
        { q: '¿Cómo se conecta ALVEX con WhatsApp?', a: 'Usamos la conexión oficial de Meta (WhatsApp Cloud API). Esto significa que tu cuenta es legítima ante Meta, tus mensajes no se marcan como spam y cumple con todas las políticas de WhatsApp Business.' },
        { q: '¿Tengo que pedirle permiso a Meta para usar ALVEX?', a: 'Nosotros nos encargamos de la verificación de Meta. Te guiamos paso a paso en el proceso de Business Verification, que toma entre 1 y 3 días. Solo necesitas tener tu negocio registrado.' },
        { q: '¿Puedo enviar mensajes masivos o de marketing?', a: 'Sí, dentro de las reglas de Meta. Para mensajes que tú inicias necesitas plantillas pre-aprobadas por Meta y consentimiento del cliente. Te ayudamos a configurarlas correctamente.' },
        { q: '¿Qué pasa si Meta suspende mi cuenta de WhatsApp?', a: 'No te dejamos solo. Si recibes una advertencia o restricción, nuestro equipo te ayuda a apelar y resolver con Meta. La mejor protección es seguir las políticas: usamos solo conexión oficial y respetamos opt-outs automáticamente.' },
        { q: '¿Cómo manejan el opt-out de los usuarios?', a: 'Si un cliente envía "STOP", "BAJA", o cualquier variante, el agente lo detecta automáticamente, deja de enviar mensajes a ese número y lo registra en tu lista de no-contactar. Cumple con WhatsApp Business Policy y leyes locales de privacidad.' },
      ],
    },
    {
      header: 'Datos y privacidad',
      items: [
        { q: '¿Dónde se guardan las conversaciones?', a: 'En servidores con cifrado en reposo y en tránsito. Cumplimos con GDPR y leyes equivalentes en LATAM. Nunca compartimos tus datos ni los de tus clientes con terceros para fines comerciales.' },
        { q: '¿Puedo borrar los datos de un cliente?', a: 'Sí. Desde tu dashboard puedes solicitar la eliminación completa de un contacto y todo su historial. También respondemos solicitudes de borrado por parte de tus clientes directamente a alvexworkspace@gmail.com en máximo 30 días.' },
        { q: '¿Quién es dueño de los datos?', a: 'Tú. Las conversaciones, los contactos y los flujos que configures son tuyos. Si cancelas el servicio, te exportamos todo en formatos estándar (CSV, JSON) y eliminamos nuestra copia.' },
        { q: '¿Usan mis conversaciones para entrenar IA?', a: 'No. Tus datos y los de tus clientes nunca entran en modelos de entrenamiento públicos ni se comparten con OpenAI, Anthropic, Google o cualquier proveedor externo más allá de lo estrictamente necesario para responder en tiempo real.' },
      ],
    },
    {
      header: 'Suscripción y soporte',
      items: [
        { q: '¿Puedo cancelar cuando quiera?', a: 'Sí. Sin permanencia ni letra chica. Si cancelas, sigues teniendo acceso hasta el final del período pagado y te llevas todas tus conversaciones y datos exportados.' },
        { q: '¿Ofrecen soporte en español?', a: 'Sí, soporte 100% en español por WhatsApp y correo. Tiempo de respuesta promedio: menos de 4 horas en horario hábil.' },
        { q: '¿Hay reembolsos?', a: 'Tienes 14 días gratis sin tarjeta para probar. Si ya pagaste y te arrepientes en los primeros 7 días, te devolvemos el dinero sin preguntas.' },
        { q: '¿Cambiar de plan es fácil?', a: 'Sí, desde tu dashboard en cualquier momento. Los cambios se aplican al instante y solo pagas la diferencia prorrateada.' },
      ],
    },
  ];

  // Flatten with group references for stable indexes
  const flatItems = [];
  groups.forEach((g, gi) => {
    g.items.forEach((it, ii) => {
      flatItems.push({ ...it, group: g.header, gi, ii });
    });
  });

  return (
    <section id="faq" className="section-pad">
      <div className="section-inner" style={{ maxWidth: 820, margin: '0 auto' }}>
        <SectionHeader title="Preguntas que nos hacen todos los días"
          sub="Si tienes una que no está aquí, escríbenos a alvexworkspace@gmail.com y la respondemos personalmente" />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 36 }}>
          {groups.map((group, gi) => (
            <div key={group.header}>
              <RevealOnScroll>
                <h3 style={{
                  fontFamily: "'JetBrains Mono', monospace",
                  fontSize: 11, fontWeight: 700,
                  letterSpacing: '0.18em', textTransform: 'uppercase',
                  color: 'var(--accent)',
                  marginBottom: 16,
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                  <span style={{
                    width: 24, height: 1.5, background: 'var(--accent)', borderRadius: 1,
                  }} />
                  {group.header}
                </h3>
              </RevealOnScroll>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {group.items.map((item, ii) => {
                  const idx = `${gi}-${ii}`;
                  const isOpen = openIdx === idx;
                  return (
                    <RevealOnScroll key={idx} delay={ii * 40}>
                      <div style={{
                        background: 'rgba(255,255,255,0.7)',
                        backdropFilter: 'blur(12px)',
                        border: isOpen ? '1px solid var(--accent-a25)' : '1px solid rgba(10,10,15,0.07)',
                        borderRadius: 14,
                        overflow: 'hidden',
                        transition: 'border-color 200ms var(--ease-out)',
                      }}>
                        <button onClick={() => setOpenIdx(isOpen ? null : idx)} style={{
                          width: '100%', textAlign: 'left', background: 'none', border: 'none',
                          padding: '18px 22px', cursor: 'pointer', color: '#0A0A0F',
                          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
                          fontFamily: "'General Sans', 'Inter', sans-serif", fontWeight: 600, fontSize: 15,
                        }}>
                          <span style={{ lineHeight: 1.4 }}>{item.q}</span>
                          <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
                            stroke={isOpen ? 'var(--accent)' : 'rgba(10,10,15,0.35)'} strokeWidth="2" strokeLinecap="round"
                            style={{
                              flexShrink: 0,
                              transition: 'transform 250ms var(--ease-out), stroke 200ms var(--ease-out)',
                              transform: isOpen ? 'rotate(45deg)' : 'rotate(0deg)',
                            }}>
                            <path d="M12 5v14M5 12h14" />
                          </svg>
                        </button>
                        <div style={{
                          maxHeight: isOpen ? 600 : 0,
                          overflow: 'hidden',
                          transition: 'max-height 380ms var(--ease-out)',
                        }}>
                          <p style={{
                            padding: '0 22px 20px',
                            fontSize: 14.5, color: 'rgba(10,10,15,0.62)', lineHeight: 1.65,
                          }}>{item.a}</p>
                        </div>
                      </div>
                    </RevealOnScroll>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function CTAFinal() {
  const steps = [
    { n: '01', title: 'Conectas tu número', body: 'en 5 minutos.' },
    { n: '02', title: 'El agente empieza', body: 'a responder hoy mismo.' },
    { n: '03', title: 'Cancelas si no funciona.', body: 'Sin preguntas.' },
  ];

  const ArrowRightIcon = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
      <line x1="5" y1="12" x2="19" y2="12"/>
      <polyline points="12 5 19 12 12 19"/>
    </svg>
  );

  const ArrowIcon = () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
      <line x1="5" y1="12" x2="19" y2="12"/>
      <polyline points="12 5 19 12 12 19"/>
    </svg>
  );

  const ShieldIcon = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
      <polyline points="9 12 11 14 15 10"/>
    </svg>
  );

  return (
    <section className="section-pad" id="empezar">
      <div className="section-inner">
        <RevealOnScroll>
          <div style={{
            position: 'relative',
            borderRadius: 32,
            padding: 'clamp(56px, 7vw, 104px) clamp(28px, 5vw, 80px)',
            background: 'linear-gradient(135deg, #fff 0%, rgba(47,125,255,0.05) 55%, rgba(124,92,255,0.06) 100%)',
            border: '1px solid var(--accent-a20)',
            textAlign: 'center',
            overflow: 'hidden',
            boxShadow: '0 30px 80px -30px rgba(47,125,255,0.20)',
          }}>
            {/* Corner glows */}
            <div style={{
              position: 'absolute', top: '-30%', right: '-15%',
              width: '60%', height: '85%',
              background: 'radial-gradient(circle, rgba(47,125,255,0.22), transparent 60%)',
              pointerEvents: 'none',
            }} />
            <div style={{
              position: 'absolute', bottom: '-30%', left: '-15%',
              width: '60%', height: '85%',
              background: 'radial-gradient(circle, rgba(124,92,255,0.20), transparent 60%)',
              pointerEvents: 'none',
            }} />

            <div style={{ position: 'relative' }}>
              <Pill>TU TIEMPO NO TIENE PRECIO</Pill>

              <h2 className="heading-display" style={{
                fontSize: 'clamp(38px, 6.2vw, 76px)',
                color: '#0A0A0F',
                lineHeight: 1.02,
                letterSpacing: '-0.025em',
                textWrap: 'balance',
                maxWidth: 880,
                margin: '28px auto 0',
              }}>
                Tu tiempo no tiene precio.{' '}
                <span style={{ color: 'var(--accent)' }}>Pero llevas años regalándolo</span>
              </h2>

              <p style={{
                fontSize: 'clamp(15px, 1.8vw, 20px)',
                color: 'rgba(10,10,15,0.62)',
                lineHeight: 1.55,
                maxWidth: 640,
                margin: '24px auto 0',
              }}>
                Domingos interrumpidos, noches sin dormir, vacaciones que nunca son vacaciones. Cada mensaje que respondes son minutos de tu vida que no vuelven.{' '}
                <span style={{ color: '#0A0A0F', fontWeight: 500 }}>Tu agente sí puede contestar. Tú no deberías tener que hacerlo</span>
              </p>

              {/* What happens next — 3 steps */}
              <div className="cta-steps">
                {steps.map((s, i) => (
                  <React.Fragment key={s.n}>
                    <div className="cta-step">
                      <div style={{
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        width: 56, height: 56, borderRadius: 999,
                        background: '#fff',
                        border: '1px solid var(--accent-a25)',
                        fontFamily: "'JetBrains Mono', monospace",
                        fontWeight: 700, fontSize: 16,
                        color: 'var(--accent)',
                        letterSpacing: '-0.02em',
                        boxShadow: '0 4px 12px rgba(47,125,255,0.10)',
                        marginBottom: 14,
                      }}>{s.n}</div>
                      <div style={{
                        fontFamily: "'Cabinet Grotesk', 'Outfit', sans-serif",
                        fontWeight: 600, fontSize: 15.5,
                        color: '#0A0A0F', lineHeight: 1.3,
                      }}>
                        {s.title}<br/>
                        <span style={{ fontWeight: 400, color: 'rgba(10,10,15,0.58)' }}>{s.body}</span>
                      </div>
                    </div>
                    {i < steps.length - 1 && (
                      <div className="cta-step-arrow" style={{
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        color: 'rgba(10,10,15,0.25)',
                      }}>
                        <ArrowRightIcon/>
                      </div>
                    )}
                  </React.Fragment>
                ))}
              </div>

              {/* CTAs */}
              <div style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
                marginTop: 44,
              }}>
                <a
                  href="/register?plan=starter&period=year"
                  onClick={(e) => {
                    // CTAFinal is rendered outside PricingSection, so we
                    // don't share its `annual` state. Read the toggle from
                    // the DOM to honor whatever the visitor picked. Default
                    // is "year" because the pricing toggle defaults to Anual.
                    try {
                      const isAnnual = !!document.querySelector(
                        '.pricing-toggle-btn.active.is-annual, .pricing-toggle-pill.is-annual'
                      ) || /Anual/i.test(
                        document.querySelector('.pricing-toggle-btn.active')?.textContent || ''
                      );
                      const period = isAnnual ? 'year' : 'month';
                      e.currentTarget.href = `/register?plan=starter&period=${period}`;
                      document.cookie = `alvex_pending_plan=${encodeURIComponent(`starter:${period}`)}; max-age=${60 * 60 * 24 * 30}; path=/; samesite=lax`;
                    } catch (_) {}
                  }}
                  className="btn-primary"
                  style={{
                    padding: '20px 40px', fontSize: 16, fontWeight: 600,
                    display: 'inline-flex', alignItems: 'center', gap: 12,
                    boxShadow: '0 14px 36px rgba(47,125,255,0.32), 0 4px 12px rgba(47,125,255,0.18)',
                    letterSpacing: '-0.005em',
                    textDecoration: 'none',
                  }}
                >
                  Probar gratis 14 días
                  <ArrowIcon/>
                </a>
              </div>

              {/* Risk reversal */}
              <div style={{
                marginTop: 52, paddingTop: 28,
                borderTop: '1px solid rgba(10,10,15,0.08)',
                maxWidth: 540, margin: '52px auto 0',
              }}>
                <div style={{
                  display: 'inline-flex', alignItems: 'flex-start', gap: 12,
                  fontSize: 13.5, color: 'rgba(10,10,15,0.62)',
                  lineHeight: 1.55, textAlign: 'left',
                }}>
                  <span style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 1 }}><ShieldIcon/></span>
                  <span>
                    <strong style={{ color: '#0A0A0F', fontWeight: 600 }}>Sin riesgo.</strong> No pedimos tarjeta. Si decides no continuar, cancelas con 1 clic y te llevas todos tus datos.
                  </span>
                </div>
              </div>
            </div>
          </div>
        </RevealOnScroll>
      </div>
    </section>
  );
}

function FooterSection() {
  const cols = [
    {
      title: 'PRODUCTO',
      links: [
        { label: 'Agentes de WhatsApp', href: '#producto' },
        { label: 'Agentes de voz', href: '#producto' },
        { label: 'Calculadora ROI', href: '#calculadora' },
        { label: 'Industrias', href: '#industrias' },
        { label: 'Precios', href: '#precios' },
      ],
    },
    {
      title: 'EMPRESA',
      links: [
        { label: 'Sobre ALVEX', href: '#' },
        { label: 'Contacto', href: 'mailto:alvexworkspace@gmail.com' },
        { label: 'Soporte', href: 'mailto:alvexworkspace@gmail.com' },
        { label: 'Estatus del servicio', href: '#' },
      ],
    },
    {
      title: 'LEGAL',
      links: [
        { label: 'Política de privacidad', href: 'privacy.html' },
        { label: 'Términos de servicio', href: 'terms.html' },
        { label: 'Política de cookies', href: 'cookies.html' },
        { label: 'Política de reembolsos', href: 'refunds.html' },
        { label: 'Uso aceptable', href: 'acceptable-use.html' },
      ],
    },
    {
      title: 'COMPLIANCE',
      links: [
        { label: 'Eliminación de datos', href: 'data-deletion.html' },
        { label: 'Acuerdo de procesamiento (DPA)', href: 'data-processing.html' },
        { label: 'WhatsApp Business Policy', href: 'https://www.whatsapp.com/legal/business-policy', external: true },
        { label: 'Tech Provider Meta', href: 'https://developers.facebook.com/docs/whatsapp/business-management-api/tech-provider', external: true },
      ],
    },
  ];

  return (
    <footer style={{ borderTop: '1px solid rgba(10,10,15,0.06)', padding: '72px 24px 32px' }}>
      <div className="section-inner">
        {/* Brand strip + business info */}
        <div className="footer-brand-row">
          <div style={{ maxWidth: 360 }}>
            <div style={{ marginBottom: 18 }}>
              <img src="/v2/assets/alvex-logo.png" style={{ height: 36, display: 'block' }} alt="ALVEX" />
            </div>
            <p style={{ fontSize: 14, color: 'rgba(10,10,15,0.55)', lineHeight: 1.65, marginBottom: 18 }}>
              Agentes de IA que atienden, agendan y cobran por ti. 24/7, en cualquier idioma.
            </p>

            <a href="mailto:alvexworkspace@gmail.com" style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              color: 'var(--accent)', textDecoration: 'none', fontWeight: 500,
              fontSize: 13.5,
            }}>
              alvexworkspace@gmail.com
            </a>
          </div>

          {/* Columns */}
          <div className="footer-cols-grid">
            {cols.map(c => (
              <div key={c.title}>
                <div style={{
                  fontFamily: "'JetBrains Mono', monospace",
                  fontSize: 10.5, fontWeight: 700,
                  letterSpacing: '0.18em', textTransform: 'uppercase',
                  color: 'rgba(10,10,15,0.50)',
                  marginBottom: 18,
                }}>{c.title}</div>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
                  {c.links.map(l => (
                    <li key={l.label}>
                      <a href={l.href}
                        target={l.external ? '_blank' : undefined}
                        rel={l.external ? 'noopener noreferrer' : undefined}
                        style={{
                          color: 'rgba(10,10,15,0.62)', fontSize: 13.5,
                          textDecoration: 'none',
                          transition: 'color 150ms var(--ease-out)',
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                        }}
                        onMouseEnter={e => e.currentTarget.style.color = '#0A0A0F'}
                        onMouseLeave={e => e.currentTarget.style.color = 'rgba(10,10,15,0.62)'}
                      >
                        {l.label}
                        {l.external && (
                          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M7 17L17 7" /><path d="M7 7h10v10" />
                          </svg>
                        )}
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* Compliance badges row — visual trust signals */}
        <div style={{
          marginTop: 56, paddingTop: 28,
          borderTop: '1px solid rgba(10,10,15,0.06)',
          display: 'flex', flexWrap: 'wrap',
          alignItems: 'center', justifyContent: 'space-between',
          gap: 24,
        }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'center' }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              fontSize: 12, color: 'rgba(10,10,15,0.55)',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="#25D366">
                <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z"/>
              </svg>
              Conexión oficial con Meta
            </span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              fontSize: 12, color: 'rgba(10,10,15,0.55)',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#14B870" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
              </svg>
              GDPR ready
            </span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              fontSize: 12, color: 'rgba(10,10,15,0.55)',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(10,10,15,0.55)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
              </svg>
              Cifrado en tránsito y reposo
            </span>
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 16,
            fontSize: 12.5, color: 'rgba(10,10,15,0.40)',
          }}>
            <span>© 2026 ALVEX SAAS · Todos los derechos reservados</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { PricingSection, FAQ, CTAFinal, FooterSection });
