// Page Precios — composants spécifiques (Hero, Tabla comparativa, Qué incluye)

// Send the visitor to the app's Paddle checkout endpoint, which creates a
// transaction server-side then redirects to /billing/checkout/ on this site.
const APP_URL = 'https://app.closerbroker.com';
const goPaddleCheckout = ({ plan, users, currency }) => {
  const cycle = plan === 'annual' ? 'yearly' : 'monthly';
  const u = Math.max(1, Math.min(500, Number(users) || 1));
  const c = (currency === 'USD' || currency === 'MXN' || currency === 'COP') ? currency : 'MXN';
  window.location.href = `${APP_URL}/api/paddle/checkout?plan=${cycle}&users=${u}&currency=${c}`;
};

const PreciosHero = () => (
  <section style={{ paddingTop: 140, paddingBottom: 24, position: 'relative', overflow: 'hidden' }}>
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -300, left: '20%', width: 600, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, rgba(84,181,227,0.18) 0%, transparent 70%)', filter: 'blur(40px)' }} />
      <div style={{ position: 'absolute', top: -200, right: '15%', width: 500, height: 500, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,156,255,0.18) 0%, transparent 70%)', filter: 'blur(40px)' }} />
    </div>
    <div className="container" style={{ position: 'relative' }}>
      <div style={{ textAlign: 'center', maxWidth: 820, margin: '0 auto' }}>
        <div className="reveal in" style={{ marginBottom: 28 }}>
          <div className="eyebrow"><span className="eyebrow-dot" />Precios</div>
        </div>
        <h1 className="h1 reveal in reveal-delay-1" style={{ marginBottom: 22, textWrap: 'balance', fontSize: 'clamp(36px, 5.2vw, 64px)' }}>
          Un solo plan. <span className="serif" style={{ fontStyle: 'italic' }}>Todo incluido.</span>
        </h1>
        <p className="reveal in reveal-delay-2" style={{ fontSize: 18, color: 'var(--fg-soft)', textWrap: 'pretty', maxWidth: 640, margin: '0 auto 28px' }}>
          CRM, sitio web, bolsa inmobiliaria, IA, WhatsApp, portal Ogarom — todo dentro de la misma suscripción. Sin add-ons obligatorios, sin sorpresas en la factura.
        </p>
        <div className="reveal in reveal-delay-3" style={{ display: 'flex', gap: 20, justifyContent: 'center', flexWrap: 'wrap', fontSize: 13, color: 'var(--fg-muted)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={14} color="#54B5E3" /> Sin compromiso · Cancela cuando quieras</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={14} color="#54B5E3" /> Migración en 5 minutos</div>
        </div>
      </div>
    </div>
  </section>
);

// ────────────────────────────────────────────────────────────
// Tabla comparativa detallada por categoría
// ────────────────────────────────────────────────────────────

const FEATURE_GROUPS = [
  {
    cat: 'CRM Inmobiliario',
    items: [
      { f: 'Lead scoring automático', m: true, a: true },
      { f: 'Atribución automática de leads', m: true, a: true },
      { f: 'Pipelines separados por tipo de cliente', m: true, a: true },
      { f: 'Matching inteligente propiedad ↔ lead', m: true, a: true },
      { f: 'Selecciones personalizadas en un click', m: true, a: true },
      { f: 'Historial completo de conversaciones', m: true, a: true },
      { f: 'Importación desde EasyBroker / Wasi / Tokko', m: true, a: true },
    ],
  },
  {
    cat: 'Sitio web incluido',
    items: [
      { f: 'Hosting y SSL incluidos', m: true, a: true },
      { f: 'Dominio personalizado', m: true, a: true },
      { f: 'Templates premium optimizados para conversión', m: true, a: true },
      { f: 'Editor visual sin código', m: true, a: true },
      { f: 'SEO técnico optimizado', m: true, a: true },
      { f: 'Blog con IA integrado', m: true, a: true },
      { f: 'Formularios conectados al CRM', m: true, a: true },
    ],
  },
  {
    cat: 'IA generativa',
    items: [
      { f: 'Redacción de descripciones de propiedades', m: true, a: true },
      { f: 'Artículos de blog con IA', m: true, a: true },
      { f: 'Sugerencias de respuesta a prospectos', m: true, a: true },
      { f: 'Detección de intención de compra', m: true, a: true },
      { f: 'Adaptada a vocabulario LATAM (MX, CO, AR, CL, PE)', m: true, a: true },
    ],
  },
  {
    cat: 'Portal Ogarom incluido',
    items: [
      { f: 'Propiedades activas en Ogarom', m: '10', a: '10' },
      { f: 'Búsqueda inteligente por IA para compradores', m: true, a: true },
      { f: 'Leads de Ogarom directos al CRM', m: true, a: true },
    ],
  },
  {
    cat: 'Portales y publicación',
    items: [
      { f: 'Inmuebles24, Mercado Libre, Lamudi, Vivanuncios', m: true, a: true },
      { f: 'Metrocuadrado, Properati y otros portales LATAM', m: true, a: true },
      { f: 'Publicación en un click multi-portal', m: true, a: true },
    ],
  },
  {
    cat: 'WhatsApp y comunicación',
    items: [
      { f: 'WhatsApp Business integrado', m: true, a: true },
      { f: 'Plantillas de mensajes', m: true, a: true },
      { f: 'Notificaciones automáticas a leads', m: true, a: true },
    ],
  },
  {
    cat: 'Equipo y permisos',
    items: [
      { f: 'Usuarios incluidos', m: '2', a: '4' },
      { f: 'Costo por usuario adicional', m: '$9 USD/mes', a: '$7 USD/mes' },
      { f: 'Roles y permisos granulares', m: true, a: true },
      { f: 'Round-robin ponderado para asignar leads', m: true, a: true },
    ],
  },
  {
    cat: 'Soporte y migración',
    items: [
      { f: 'Soporte 24/7 por WhatsApp, email y chat', m: true, a: true },
      { f: 'Migración asistida desde tu CRM actual', m: true, a: true },
      { f: 'Soporte prioritario', m: false, a: true },
      { f: 'Migración prioritaria', m: false, a: true },
    ],
  },
  {
    cat: 'Seguridad',
    items: [
      { f: 'Encriptación HTTPS/TLS', m: true, a: true },
      { f: 'Copias de seguridad diarias', m: true, a: true },
      { f: 'Exportación completa de datos en cualquier momento', m: true, a: true },
    ],
  },
];

const Cell = ({ v, accent }) => {
  if (v === true) return <Icon name="check" size={16} color={accent ? '#54B5E3' : '#16a34a'} />;
  if (v === false) return <span style={{ color: 'var(--fg-faint)', fontSize: 18 }}>—</span>;
  return <span style={{ fontSize: 14, color: 'var(--fg)', fontWeight: 500 }}>{v}</span>;
};

const ComparisonTable = () => {
  const [openCat, setOpenCat] = React.useState(0);
  const ctx = (typeof useCountry === 'function') ? useCountry() : { country: 'co' };
  const primaryCurrency = ctx.country === 'mx' ? 'MXN' : 'COP';

  const featureGroups = React.useMemo(() => FEATURE_GROUPS.map(group => {
    if (group.cat !== 'Equipo y permisos') return group;
    return {
      ...group,
      items: group.items.map(it => {
        if (it.f !== 'Costo por usuario adicional') return it;
        return {
          ...it,
          m: `${fmt(PRICING.monthly.addUser[primaryCurrency], primaryCurrency)} ${primaryCurrency}/mes`,
          a: `${fmt(PRICING.annual.addUser[primaryCurrency], primaryCurrency)} ${primaryCurrency}/mes`,
        };
      }),
    };
  }), [primaryCurrency]);

  return (
    <section style={{ background: 'var(--bg-soft)' }}>
      <div className="container">
        <div style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 56px' }} className="reveal">
          <div className="eyebrow" style={{ marginBottom: 20 }}><span className="eyebrow-dot" />Comparativa detallada</div>
          <h2 className="h2" style={{ marginBottom: 16, textWrap: 'balance' }}>
            Lo que incluye <span className="serif" style={{ fontStyle: 'italic' }}>cada plan.</span>
          </h2>
          <p style={{ fontSize: 16, color: 'var(--fg-soft)', textWrap: 'pretty' }}>
            Mismas funcionalidades en los dos planes — la diferencia está en los usuarios incluidos, el descuento anual, y el soporte prioritario.
          </p>
        </div>

        <div className="reveal cb-compare" style={{ maxWidth: 1080, margin: '0 auto' }}>
          {/* Header sticky */}
          <div className="cb-compare-head">
            <div />
            <div className="cb-compare-plan">
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Mensual</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, justifyContent: 'center' }}>
                <span style={{ fontSize: 22, fontWeight: 600 }}>{fmt(PRICING.monthly.base[primaryCurrency], primaryCurrency)}</span>
                <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{primaryCurrency}/mes</span>
              </div>
            </div>
            <div className="cb-compare-plan cb-compare-plan-highlight">
              <div className="mono" style={{ fontSize: 11, color: '#54B5E3', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4, fontWeight: 600 }}>Anual · −15%</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, justifyContent: 'center' }}>
                <span className="grad-text" style={{ fontSize: 22, fontWeight: 700 }}>{fmt(PRICING.annual.base[primaryCurrency], primaryCurrency)}</span>
                <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{primaryCurrency}/mes</span>
              </div>
            </div>
          </div>

          {/* Categories */}
          <div className="cb-compare-body">
            {featureGroups.map((g, i) => {
              const open = openCat === i;
              return (
                <div key={g.cat} className="cb-compare-cat">
                  <button
                    className="cb-compare-cat-head"
                    onClick={() => setOpenCat(open ? -1 : i)}
                  >
                    <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg)' }}>{g.cat}</span>
                    <span style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span className="mono">{g.items.length} funcionalidad{g.items.length > 1 ? 'es' : ''}</span>
                      <span style={{
                        display: 'inline-flex', width: 22, height: 22, borderRadius: '50%',
                        background: open ? 'var(--grad)' : 'var(--bg-soft)',
                        color: open ? '#fff' : 'var(--fg)',
                        alignItems: 'center', justifyContent: 'center',
                        transform: open ? 'rotate(45deg)' : 'rotate(0)', transition: 'all 0.3s',
                      }}>
                        <Icon name="plus" size={11} />
                      </span>
                    </span>
                  </button>

                  <div className="cb-compare-cat-body" style={{ maxHeight: open ? 1000 : 0 }}>
                    {g.items.map((it, j) => (
                      <div key={j} className="cb-compare-row">
                        <div className="cb-compare-cell-label">{it.f}</div>
                        <div className="cb-compare-cell"><Cell v={it.m} /></div>
                        <div className="cb-compare-cell cb-compare-cell-accent"><Cell v={it.a} accent /></div>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>

          {/* CTA bottom */}
          <div className="cb-compare-cta">
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button
                className="btn btn-primary"
                onClick={() => goPaddleCheckout({ plan: 'monthly', users: 2, currency: primaryCurrency })}
              >Empezar con plan mensual</button>
              <button
                className="btn btn-grad"
                onClick={() => goPaddleCheckout({ plan: 'annual', users: 2, currency: primaryCurrency })}
              ><span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>Empezar con plan anual<Icon name="arrow" size={14} /></span></button>
            </div>
          </div>
        </div>

        <style>{`
          .cb-compare {
            background: #fff;
            border: 1px solid var(--border);
            border-radius: 20px;
            overflow: hidden;
            box-shadow: var(--shadow-sm);
          }
          .cb-compare-head {
            display: grid;
            grid-template-columns: minmax(0, 1.6fr) 1fr 1fr;
            background: #fff;
            border-bottom: 1px solid var(--border);
            position: sticky;
            top: 64px;
            z-index: 5;
          }
          .cb-compare-plan {
            padding: 20px 16px;
            text-align: center;
            border-left: 1px solid var(--border-soft);
          }
          .cb-compare-plan-highlight {
            background: linear-gradient(180deg, rgba(84,181,227,0.04) 0%, rgba(198,156,255,0.04) 100%);
          }
          .cb-compare-cat {
            border-top: 1px solid var(--border-soft);
          }
          .cb-compare-cat:first-child { border-top: none; }
          .cb-compare-cat-head {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 18px 28px;
            background: #fff;
            text-align: left;
            transition: background 0.2s;
          }
          .cb-compare-cat-head:hover { background: var(--bg-soft); }
          .cb-compare-cat-body {
            overflow: hidden;
            transition: max-height 0.4s ease;
          }
          .cb-compare-row {
            display: grid;
            grid-template-columns: minmax(0, 1.6fr) 1fr 1fr;
            align-items: center;
            border-top: 1px solid var(--border-soft);
          }
          .cb-compare-cell-label {
            padding: 14px 28px;
            font-size: 14px;
            color: var(--fg-soft);
          }
          .cb-compare-cell {
            padding: 14px 16px;
            text-align: center;
            border-left: 1px solid var(--border-soft);
            min-height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .cb-compare-cell-accent {
            background: linear-gradient(180deg, rgba(84,181,227,0.025) 0%, rgba(198,156,255,0.025) 100%);
          }
          .cb-compare-cta {
            padding: 28px;
            border-top: 1px solid var(--border);
            background: #fff;
          }

          @media (max-width: 720px) {
            .cb-compare-head { top: 56px; }
            .cb-compare-cat-head { padding: 16px 18px; }
            .cb-compare-cell-label { padding: 12px 18px; font-size: 13px; }
            .cb-compare-cell { padding: 12px 8px; font-size: 12px; }
            .cb-compare-plan { padding: 16px 8px; }
          }
        `}</style>
      </div>
    </section>
  );
};

// ────────────────────────────────────────────────────────────
// Qué incluye realmente todo
// ────────────────────────────────────────────────────────────

const WhatIsIncluded = () => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : { country: 'co' };
  const isCo = ctx.country === 'co';
  const gridRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const el = gridRef.current;
    if (!el) return;
    const compute = () => {
      const max = el.scrollWidth - el.clientWidth;
      if (max <= 0) { setProgress(0); return; }
      setProgress(Math.max(0, Math.min(1, el.scrollLeft / max)));
    };
    el.addEventListener('scroll', compute, { passive: true });
    window.addEventListener('resize', compute);
    compute();
    return () => {
      el.removeEventListener('scroll', compute);
      window.removeEventListener('resize', compute);
    };
  }, []);

  const portals = (ctx.portals && ctx.portals.length)
    ? ctx.portals
    : (isCo
        ? ['Finca Raíz', 'Metrocuadrado', 'Properati', 'Mercado Libre', 'Lamudi']
        : ['Inmuebles24', 'Mercado Libre', 'Lamudi', 'Vivanuncios', 'Metrocuadrado', 'Properati']);
  const agentsCapPlural = (ctx.vocab && ctx.vocab.agentCapPlural) || (isCo ? 'Agentes' : 'Asesores');
  const vocabRegional = isCo ? 'CO/MX/AR/CL/PE' : 'MX/CO/AR/CL/PE';

  const groups = [
    {
      icon: 'check',
      title: 'CRM completo',
      items: ['Leads ilimitados', 'Pipelines configurables', 'Tareas y recordatorios', 'Lead scoring automático', 'Atribución automática', 'Historial completo'],
    },
    {
      icon: 'globe',
      title: 'Sitio web profesional',
      items: ['Hosting + SSL', 'Dominio personalizado', 'Templates premium', 'Editor visual', 'SEO técnico', 'Velocidad optimizada'],
    },
    {
      icon: 'sparkle',
      title: 'IA inmobiliaria LATAM',
      items: ['Redacción de propiedades', 'Blog con IA', 'Sugerencias de respuesta', 'Detección de intención', `Vocabulario regional ${vocabRegional}`],
    },
    {
      icon: 'home',
      title: 'Portal Ogarom',
      items: ['10 propiedades activas incluidas', 'Búsqueda con IA para compradores', 'Leads directos al CRM', 'Tráfico calificado'],
    },
    {
      icon: 'link',
      title: 'Publicación multi-portal',
      items: portals,
    },
    {
      icon: 'chat',
      title: 'WhatsApp + comunicación',
      items: ['WhatsApp Business', 'Plantillas', 'Notificaciones automáticas', 'Email integrado'],
    },
    {
      icon: 'users',
      title: 'Equipo',
      items: ['2-4 usuarios incluidos', 'Roles y permisos', 'Round-robin ponderado', `${agentsCapPlural} ilimitados (con costo adicional)`],
    },
    {
      icon: 'check',
      title: 'Soporte humano',
      items: ['24/7 los 365 días', 'WhatsApp, email, chat', 'Migración asistida', 'Equipo que habla español'],
    },
  ];

  return (
    <section>
      <div className="container">
        <div style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 56px' }} className="reveal">
          <div className="eyebrow" style={{ marginBottom: 20 }}><span className="eyebrow-dot" />Qué incluye realmente todo</div>
          <h2 className="h2" style={{ marginBottom: 16, textWrap: 'balance' }}>
            Cuando decimos <span className="serif" style={{ fontStyle: 'italic' }}>todo incluido,</span> es todo.
          </h2>
          <p style={{ fontSize: 16, color: 'var(--fg-soft)', textWrap: 'pretty' }}>
            Sin add-ons obligatorios, sin paquetes premium, sin "esto se cobra aparte". Lo que ves abajo está en tu suscripción desde el día uno.
          </p>
        </div>

        <div ref={gridRef} className="reveal cb-included-grid">
          {groups.map((g) => (
            <div key={g.title} className="cb-included-card">
              <div className="cb-included-icon">
                <Icon name={g.icon} size={20} color="#54B5E3" />
              </div>
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14, color: 'var(--fg)' }}>{g.title}</div>
              <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
                {g.items.map((it, j) => (
                  <li key={j} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 13.5, color: 'var(--fg-soft)', lineHeight: 1.45 }}>
                    <Icon name="check" size={13} color="#16a34a" />
                    <span>{it}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div className="cb-included-track" aria-hidden="true">
          <div className="cb-included-track-fill" style={{ width: `${progress * 100}%` }} />
        </div>

        <style>{`
          .cb-included-track { display: none; }
          .cb-included-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            max-width: 1120px;
            margin: 0 auto;
          }
          .cb-included-card {
            padding: 24px;
            background: #fff;
            border: 1px solid var(--border);
            border-radius: 16px;
            transition: all 0.3s ease;
          }
          .cb-included-card:hover {
            border-color: rgba(198,156,255,0.5);
            box-shadow: 0 12px 32px -16px rgba(84,181,227,0.25);
            transform: translateY(-2px);
          }
          .cb-included-icon {
            width: 40px; height: 40px;
            border-radius: 10px;
            background: var(--grad-soft);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
          }
          @media (max-width: 960px) {
            .cb-included-grid { grid-template-columns: repeat(2, 1fr); }
          }
          @media (max-width: 760px) {
            .cb-included-grid {
              display: flex !important;
              align-items: stretch;
              grid-template-columns: none !important;
              overflow-x: auto;
              overflow-y: hidden;
              scroll-snap-type: x mandatory;
              gap: 14px !important;
              max-width: none !important;
              margin: 0 -16px !important;
              padding: 4px 16px 8px;
              scroll-padding-left: 16px;
              scrollbar-width: none;
              overscroll-behavior-x: contain;
            }
            .cb-included-grid::-webkit-scrollbar { display: none; }
            .cb-included-card {
              flex: 0 0 calc(100% - 48px) !important;
              scroll-snap-align: start;
              scroll-snap-stop: always;
              text-align: center;
              padding: 28px 22px;
            }
            .cb-included-icon { margin-left: auto; margin-right: auto; }
            .cb-included-card ul { align-items: center; }
            .cb-included-card ul li {
              justify-content: center;
              text-align: left;
              max-width: 280px;
              margin: 0 auto;
            }
            .cb-included-track {
              display: block !important;
              position: relative;
              height: 3px;
              background: var(--border);
              border-radius: 999px;
              margin: 18px 24px 0;
              overflow: hidden;
              max-width: 1120px;
              margin-left: auto;
              margin-right: auto;
            }
            .cb-included-track-fill {
              position: absolute;
              top: 0; left: 0; bottom: 0;
              background: linear-gradient(90deg, #54B5E3, #C69CFF);
              border-radius: 999px;
              transition: width 0.12s linear;
              box-shadow: 0 0 8px rgba(198, 156, 255, 0.4);
            }
          }
        `}</style>
      </div>
    </section>
  );
};

window.PreciosHero = PreciosHero;
window.ComparisonTable = ComparisonTable;
window.WhatIsIncluded = WhatIsIncluded;

// ════════════════════════════════════════════════════════════
// PreciosConfigurator — toggles + slider + 2 cards Normal/Pionero
// Cálculo dinámico de precio en tiempo real
// ════════════════════════════════════════════════════════════

const PRICING = {
  monthly: {
    base:    { MXN: 1199, USD: 59, COP: 239000 },
    addUser: { MXN: 180,  USD: 9,  COP: 35000  },
    included: 2,
  },
  annual: {
    base:    { MXN: 1020, USD: 49, COP: 200000 },
    addUser: { MXN: 130,  USD: 7,  COP: 25000  },
    included: 4,
  },
};

const fmt = (n, c) => {
  if (c === 'USD') return `$${n.toLocaleString('en-US')}`;
  if (c === 'COP') return `$${n.toLocaleString('es-CO')}`;
  return `$${n.toLocaleString('es-MX')}`;
};

const PreciosConfigurator = () => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : { country: 'co' };
  const primaryCurrency = ctx.country === 'mx' ? 'MXN' : 'COP';

  const [period, setPeriod] = React.useState('annual');
  const [currency, setCurrency] = React.useState(() => {
    try {
      const url = new URL(window.location.href);
      const cParam = (url.searchParams.get('currency') || '').toUpperCase();
      if (cParam === 'USD') return 'USD';
      if (cParam === 'MXN' || cParam === 'COP') return cParam;
    } catch (e) {}
    return primaryCurrency;
  });

  // Si le pays change (via switcher), re-aligner la devise primaire — sauf si l'utilisateur a explicitement choisi USD
  React.useEffect(() => {
    setCurrency(prev => (prev === 'USD' ? 'USD' : primaryCurrency));
  }, [primaryCurrency]);

  const [users, setUsers] = React.useState(2);

  const cfg = PRICING[period];
  const basePrice = cfg.base[currency];
  const addPrice = cfg.addUser[currency];
  const extra = Math.max(0, users - cfg.included);
  const total = basePrice + extra * addPrice;
  const fillPct = ((users - 1) / (50 - 1)) * 100;

  const PioneroCard = () => (
    <div className="pc-card pc-card-pionero">
      <div className="pc-badge">
        <span style={{ marginRight: 4 }}>⭐</span>PLAN PIONERO
      </div>
      <div className="pc-card-inner">
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <div style={{ fontSize: 26, fontWeight: 600, color: 'var(--fg)', letterSpacing: '-0.01em', marginBottom: 6 }}>
            Plan Pionero
          </div>
          <div style={{ fontSize: 15, color: 'var(--fg-muted)', maxWidth: 460, margin: '0 auto', lineHeight: 1.5 }}>
            Solo 100 agencias acceden a este plan exclusivo de lanzamiento.
          </div>
        </div>

        {/* Precio breakdown */}
        <div className="pc-breakdown-new">
          <div className="pc-bd-line">
            <span style={{ color: 'var(--fg-soft)' }}>
              Precio base
              <span style={{ color: 'var(--fg-faint)', fontSize: 13, marginLeft: 6 }}>
                ({cfg.included} usuario{cfg.included > 1 ? 's' : ''} incluido{cfg.included > 1 ? 's' : ''})
              </span>
            </span>
            <span style={{ color: 'var(--fg)', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }} key={'base' + basePrice + currency}>
              {fmt(basePrice, currency)} {currency}/mes
            </span>
          </div>
          {extra > 0 && (
            <div className="pc-bd-line pc-bd-anim" key={'extra' + extra + currency + period}>
              <span style={{ color: 'var(--fg-soft)' }}>
                + {extra} usuario{extra > 1 ? 's' : ''} adicional{extra > 1 ? 'es' : ''}
                <span style={{ color: 'var(--fg-faint)', fontSize: 13, marginLeft: 6 }}>({fmt(addPrice, currency)} c/u)</span>
              </span>
              <span style={{ color: 'var(--fg)', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
                {fmt(extra * addPrice, currency)} {currency}/mes
              </span>
            </div>
          )}
          <div className="pc-bd-divider" />
          <div className="pc-bd-total">
            <span style={{ fontSize: 18, fontWeight: 500, color: 'var(--fg)' }}>Total</span>
            <span className="pc-total-num" key={'total' + total + currency}>
              <span className="grad-text">{fmt(total, currency)}</span>
              <span style={{ fontSize: 18, color: 'var(--fg-muted)', fontWeight: 500, marginLeft: 8 }}>{currency}/mes</span>
            </span>
          </div>
          {currency !== 'USD' && (
            <div className="mono" style={{ fontSize: 12, color: 'var(--fg-faint)', textAlign: 'right', marginTop: 6 }}>
              IVA incluido
            </div>
          )}
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 18, marginBottom: 36 }}>
          <div className="pc-locked">
            <span>🔒</span>
            <span>Precio bloqueado de por vida</span>
          </div>
        </div>

        <div className="pc-divider" />

        {/* Beneficios Pionero */}
        <ul className="pc-benefits">
          {[
            { t: 'Precio bloqueado de por vida', d: 'Para siempre, sin aumentos. Mismo precio el día 1 y el año 5.' },
            { t: '30 propiedades incluidas en Portal Ogarom', d: 'Triple de capacidad vs el plan estándar (10 propiedades).' },
            { t: 'Voz directa en el roadmap', d: 'Sugiere funciones, vota prioridades, influye en lo que construimos.' },
            { t: 'Soporte prioritario', d: 'Acceso directo al equipo, respuesta en menos de 2 horas.' },
            { t: 'Acceso anticipado a nuevas funciones', d: 'Pruebas las funciones nuevas antes que nadie, sin costo extra.' },
          ].map((b, i) => (
            <li key={i} className="pc-benefit">
              <span className="pc-benefit-check"><Icon name="check" size={14} color="#16a34a" /></span>
              <div>
                <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg)', marginBottom: 2 }}>{b.t}</div>
                <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.5 }}>{b.d}</div>
              </div>
            </li>
          ))}
        </ul>

        {/* Urgencia */}
        <div className="pc-urgency" style={{ marginTop: 36 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--fg-muted)', marginBottom: 10 }}>
            <span>Quedan <strong style={{ color: 'var(--fg)', fontWeight: 600 }}>47 lugares</strong> de 100</span>
            <span className="mono">53%</span>
          </div>
          <div className="pc-progress"><div className="pc-progress-bar" /></div>
        </div>

        {/* CTA */}
        <button
          className="btn btn-grad btn-lg pc-cta"
          style={{ marginTop: 28 }}
          onClick={() => goPaddleCheckout({ plan: period, users, currency })}
        >
          <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            Empezar prueba gratuita de 21 días
            <Icon name="arrow" size={15} />
          </span>
        </button>
        <div style={{ marginTop: 14, fontSize: 13, color: '#6b7280', display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6 }}>
          <Icon name="check" size={13} color="#54B5E3" />
          Sin compromiso · Cancela cuando quieras
        </div>
      </div>
    </div>
  );

  return (
    <section id="precios" style={{ paddingTop: 32 }}>
      <div className="container">
        {/* Configuración */}
        <div className="reveal pc-config">
          <div className="pc-config-toggles">
            {/* Mensual / Anual */}
            <div className="pc-pill">
              <button
                className={period === 'monthly' ? 'on' : ''}
                onClick={() => setPeriod('monthly')}
              >Mensual</button>
              <button
                className={period === 'annual' ? 'on' : ''}
                onClick={() => setPeriod('annual')}
              >
                Anual
                <span className="pc-pill-badge">−15%</span>
              </button>
            </div>

            {/* Moneda */}
            <div className="pc-pill">
              <button
                className={currency === primaryCurrency ? 'on' : ''}
                onClick={() => setCurrency(primaryCurrency)}
              >{primaryCurrency}</button>
              <button
                className={currency === 'USD' ? 'on' : ''}
                onClick={() => setCurrency('USD')}
              >USD</button>
            </div>
          </div>

          {/* Slider */}
          <div className="pc-slider-block">
            <div className="pc-slider-label">
              <span>¿Cuántos usuarios necesitas?</span>
              <span className="pc-slider-value">
                <strong>{users}</strong> usuario{users > 1 ? 's' : ''}
              </span>
            </div>
            <div className="pc-slider-wrap" style={{ '--fill': `${fillPct}%` }}>
              <input
                type="range"
                min={1}
                max={50}
                step={1}
                value={users}
                onChange={e => setUsers(Number(e.target.value))}
                className="pc-slider"
              />
              <div className="pc-slider-track" />
              <div className="pc-slider-fill" />
              <div className="pc-slider-ticks">
                {[10, 20, 30, 40, 50].map(t => (
                  <div key={t} className="pc-tick" style={{ left: `${((t - 1) / 49) * 100}%` }}>
                    <div className="pc-tick-mark" />
                    <div className="pc-tick-label">{t}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Card única — Plan Pionero */}
        <div className="reveal pc-cards-single">
          <PioneroCard />
        </div>
      </div>

      <style>{`
        /* ── Panel de configuración ───────────────────────── */
        .pc-config {
          max-width: 720px;
          margin: 0 auto 56px;
          padding: 32px 40px;
          background: linear-gradient(180deg, #fff 0%, var(--bg-soft) 100%);
          border: 1px solid var(--border);
          border-radius: 24px;
          box-shadow: var(--shadow-sm);
        }
        .pc-config-toggles {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 24px;
          margin-bottom: 36px;
          flex-wrap: wrap;
        }
        .pc-pill {
          display: inline-flex;
          padding: 4px;
          background: var(--bg-soft);
          border: 1px solid var(--border);
          border-radius: 999px;
        }
        .pc-pill button {
          padding: 8px 18px;
          font-size: 14px;
          font-weight: 500;
          color: var(--fg-muted);
          border-radius: 999px;
          display: inline-flex;
          align-items: center;
          gap: 6px;
          transition: all 0.2s;
        }
        .pc-pill button.on {
          background: #fff;
          color: var(--fg);
          box-shadow: var(--shadow-sm);
        }
        .pc-pill-badge {
          font-size: 10px;
          font-weight: 600;
          padding: 2px 6px;
          border-radius: 4px;
          background: var(--grad);
          color: #fff;
          letter-spacing: 0.02em;
        }

        /* ── Slider ───────────────────────────────────────── */
        .pc-slider-block { padding: 0 4px; }
        .pc-slider-label {
          display: flex;
          justify-content: space-between;
          align-items: baseline;
          margin-bottom: 18px;
        }
        .pc-slider-label > span:first-child {
          font-size: 14px;
          color: var(--fg-soft);
          font-weight: 500;
        }
        .pc-slider-value {
          font-size: 14px;
          color: var(--fg-muted);
        }
        .pc-slider-value strong {
          font-size: 18px;
          font-weight: 600;
          color: transparent;
          background: var(--grad);
          -webkit-background-clip: text;
          background-clip: text;
          margin-right: 4px;
        }
        .pc-slider-wrap {
          position: relative;
          height: 44px;
          padding-top: 20px;
        }
        .pc-slider-track {
          position: absolute;
          top: 28px;
          left: 0; right: 0;
          height: 4px;
          background: var(--bg-muted);
          border-radius: 999px;
          pointer-events: none;
        }
        .pc-slider-fill {
          position: absolute;
          top: 28px;
          left: 0;
          height: 4px;
          width: var(--fill);
          background: var(--grad);
          border-radius: 999px;
          pointer-events: none;
          transition: width 0.15s ease;
        }
        .pc-slider {
          position: absolute;
          top: 22px;
          left: 0; right: 0;
          width: 100%;
          height: 16px;
          margin: 0;
          background: transparent;
          -webkit-appearance: none;
          appearance: none;
          cursor: pointer;
          z-index: 2;
        }
        .pc-slider::-webkit-slider-runnable-track {
          height: 16px; background: transparent;
        }
        .pc-slider::-moz-range-track {
          height: 16px; background: transparent;
        }
        .pc-slider::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 22px; height: 22px;
          border-radius: 50%;
          background: #fff;
          border: 2px solid transparent;
          background-image: linear-gradient(#fff, #fff), var(--grad);
          background-origin: border-box;
          background-clip: padding-box, border-box;
          box-shadow: 0 2px 8px rgba(84, 181, 227, 0.4), 0 1px 2px rgba(0,0,0,0.05);
          margin-top: -3px;
          cursor: grab;
          transition: transform 0.15s;
        }
        .pc-slider::-webkit-slider-thumb:active { transform: scale(1.15); cursor: grabbing; }
        .pc-slider::-moz-range-thumb {
          width: 22px; height: 22px;
          border-radius: 50%;
          background: #fff;
          border: 2px solid #54B5E3;
          box-shadow: 0 2px 8px rgba(84, 181, 227, 0.4);
          cursor: grab;
        }
        .pc-slider-ticks {
          position: absolute;
          top: 36px;
          left: 0; right: 0;
          height: 16px;
          pointer-events: none;
        }
        .pc-tick {
          position: absolute;
          transform: translateX(-50%);
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 4px;
        }
        .pc-tick-mark {
          width: 1px; height: 4px;
          background: var(--border);
        }
        .pc-tick-label {
          font-family: 'Geist Mono', monospace;
          font-size: 10px;
          color: var(--fg-faint);
        }

        /* Card unica Pionero */
        .pc-cards-single {
          max-width: 880px;
          margin: 0 auto;
        }
        .pc-card-context {
          text-align: center;
          font-size: 14px;
          color: var(--fg-muted);
          margin-bottom: 28px;
          letter-spacing: 0.005em;
        }
        .pc-card {
          position: relative;
          background: #fff;
          border-radius: 24px;
          padding: 0;
          border: 1px solid var(--border);
          box-shadow: var(--shadow-sm);
          transition: transform 0.25s ease, box-shadow 0.25s ease;
        }
        .pc-card:hover { transform: translateY(-2px); }
        .pc-card-inner { padding: 56px 56px 48px; }
        .pc-card-pionero {
          border: 2px solid transparent;
          background-image: linear-gradient(#fff, #fff), var(--grad);
          background-origin: border-box;
          background-clip: padding-box, border-box;
          box-shadow: 0 24px 60px -20px rgba(84,181,227,0.35);
        }
        .pc-badge {
          position: absolute;
          top: -16px;
          left: 50%;
          transform: translateX(-50%);
          padding: 6px 14px;
          background: var(--grad);
          color: #fff;
          font-size: 11px;
          font-weight: 600;
          letter-spacing: 0.06em;
          border-radius: 999px;
          z-index: 2;
          box-shadow: 0 4px 12px -2px rgba(84,181,227,0.4);
          white-space: nowrap;
        }

        /* Breakdown */
        .pc-breakdown-new {
          background: var(--bg-soft);
          border: 1px solid var(--border-soft);
          border-radius: 16px;
          padding: 22px 26px;
        }
        .pc-bd-line {
          display: flex;
          justify-content: space-between;
          align-items: baseline;
          gap: 16px;
          font-size: 15px;
          padding: 6px 0;
        }
        .pc-bd-anim {
          animation: pc-fade 0.3s ease;
        }
        .pc-bd-divider {
          height: 1px;
          background: var(--border);
          margin: 14px 0 12px;
        }
        .pc-bd-total {
          display: flex;
          justify-content: space-between;
          align-items: baseline;
          gap: 16px;
          padding-top: 4px;
        }
        .pc-total-num {
          display: inline-flex;
          align-items: baseline;
          font-size: 48px;
          font-weight: 700;
          letter-spacing: -0.03em;
          line-height: 1;
          font-variant-numeric: tabular-nums;
          animation: pc-fade 0.3s ease;
        }
        @keyframes pc-fade {
          from { opacity: 0.4; transform: translateY(2px); }
          to { opacity: 1; transform: translateY(0); }
        }

        .pc-locked {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          font-size: 13px;
          color: var(--fg-soft);
          padding: 8px 14px;
          background: var(--bg-soft);
          border: 1px solid var(--border-soft);
          border-radius: 999px;
          font-weight: 500;
        }
        .pc-cta { width: 100%; }
        .pc-urgency { margin-top: 18px; }
        .pc-progress {
          height: 7px;
          background: var(--bg-muted);
          border-radius: 999px;
          overflow: hidden;
        }
        .pc-progress-bar {
          height: 100%;
          width: 53%;
          background: var(--grad);
          border-radius: 999px;
        }
        .pc-divider {
          height: 1px;
          background: var(--border-soft);
          margin: 8px 0 28px;
        }

        /* Beneficios Pionero */
        .pc-benefits {
          list-style: none;
          display: flex;
          flex-direction: column;
          gap: 18px;
        }
        .pc-benefit {
          display: flex;
          align-items: flex-start;
          gap: 12px;
        }
        .pc-benefit-check {
          flex-shrink: 0;
          width: 22px; height: 22px;
          border-radius: 50%;
          background: rgba(22, 163, 74, 0.1);
          display: inline-flex;
          align-items: center;
          justify-content: center;
          margin-top: 2px;
        }

        /* Responsive */
        @media (max-width: 760px) {
          .pc-config { padding: 24px 18px; border-radius: 20px; }
          .pc-config-toggles { gap: 10px; justify-content: center; margin-bottom: 28px; }
          .pc-pill button { padding: 7px 14px; font-size: 13px; }
          .pc-card-inner { padding: 36px 20px 32px; }
          .pc-breakdown-new { padding: 18px 18px; }
          .pc-bd-line { flex-wrap: wrap; font-size: 14px; }
          .pc-bd-line > span:last-child { width: 100%; text-align: right; }
          .pc-total-num { font-size: 36px; }
          .pc-benefits { gap: 14px; }
          .pc-benefit { gap: 10px; }
        }
        @media (max-width: 420px) {
          .pc-total-num { font-size: 32px; }
          .pc-card-inner { padding: 32px 16px 28px; }
        }
      `}</style>
    </section>
  );
};

window.PreciosConfigurator = PreciosConfigurator;

// ════════════════════════════════════════════════════════════
// BuildingTogether — Storytelling fundador / Por qué Plan Pionero
// ════════════════════════════════════════════════════════════

const BuildingTogether = () => (
  <section className="bt-section">
    <div className="container">
      <div className="bt-accent" />
      <div className="reveal" style={{ textAlign: 'center', marginBottom: 24 }}>
        <div className="eyebrow"><span className="eyebrow-dot" />POR QUÉ EL PLAN PIONERO</div>
      </div>
      <h2 className="reveal h2 bt-title">
        Construyendo CloserBroker <span className="serif grad-text" style={{ fontStyle: 'italic' }}>contigo.</span>
      </h2>
      <div className="reveal bt-prose">
        <p>
          CloserBroker no nació en una sala de juntas. Nació de ver, año tras año, agencias inmobiliarias en LATAM trabajando con CRMs estancados en el pasado, mientras el sector inmobiliario evoluciona cada día.
        </p>
        <p>
          Estamos en pleno lanzamiento. Antes de abrir las puertas a todo el mundo, queremos crecer junto a 100 agencias pioneras — las que se atreven a apostar temprano, las que tienen ideas que no hemos pensado, las que nos van a llevar a perfeccionar aún más el CRM inmobiliario que LATAM se merece — hecho a la medida del sector, pensado para cómo se vende aquí.
        </p>
        <p>
          A cambio, te damos algo que ningún cliente futuro va a tener: precio bloqueado de por vida, voz directa en lo que construimos, soporte prioritario, y acceso anticipado a cada función nueva. Una vez que lleguemos a 100, el Plan Pionero deja de existir. Para siempre.
        </p>
      </div>
    </div>
    <style>{`
      .bt-section {
        padding: 112px 0;
        position: relative;
      }
      .bt-accent {
        width: 56px;
        height: 3px;
        background: var(--grad);
        border-radius: 2px;
        margin: 0 auto 28px;
        opacity: 0.7;
      }
      .bt-title {
        text-align: center;
        max-width: 780px;
        margin: 0 auto 48px;
      }
      .bt-prose {
        max-width: 740px;
        margin: 0 auto;
      }
      .bt-prose p {
        font-size: 19px;
        line-height: 1.7;
        color: #374151;
        margin-bottom: 28px;
      }
      .bt-prose p:last-child { margin-bottom: 0; }
      @media (max-width: 760px) {
        .bt-section { padding: 80px 0; }
        .bt-title { margin-bottom: 36px; }
        .bt-prose p { font-size: 17px; line-height: 1.65; margin-bottom: 22px; }
      }
    `}</style>
  </section>
);

window.BuildingTogether = BuildingTogether;

// ════════════════════════════════════════════════════════════
// PreciosFaq — 6 preguntas específicas pricing
// ════════════════════════════════════════════════════════════

const buildPreciosFaqs = (country) => {
  const isCo = country === 'co';
  const primaryCurrency = isCo ? 'COP' : 'MXN';
  const monthlyAdd = fmt(PRICING.monthly.addUser[primaryCurrency], primaryCurrency);
  const annualAdd = fmt(PRICING.annual.addUser[primaryCurrency], primaryCurrency);
  const pesosLabel = isCo ? 'pesos colombianos' : 'pesos mexicanos';
  const agentLabel = isCo ? 'agentes' : 'asesores';
  return [
    {
      q: '¿Puedo cambiar de plan en cualquier momento?',
      a: 'Sí, puedes pasar de Mensual a Anual cuando quieras y aprovechar el 15% de descuento. Si estás en Plan Pionero, mantienes tus beneficios bloqueados de por vida sin importar cómo evolucione tu plan.',
    },
    {
      q: '¿Cómo funciona el costo por usuario adicional?',
      a: `Cada plan incluye un número de usuarios gratuitos (2 en Mensual, 4 en Anual). Si tu equipo crece, agregas usuarios adicionales por ${monthlyAdd} ${primaryCurrency}/mes (Mensual) o ${annualAdd} ${primaryCurrency}/mes (Anual). Los miembros del Plan Pionero mantienen estos precios bloqueados de por vida.`,
    },
    {
      q: '¿Qué pasa con el portal Ogarom?',
      a: 'Tu plan incluye 10 propiedades activas en Ogarom (30 si estás en Plan Pionero). Si necesitas más, puedes ampliar tu cupo de propiedades cuando lo necesites. Los leads que generas en Ogarom llegan automáticamente a tu CRM CloserBroker.',
    },
    {
      q: `¿Puedo pagar en USD o solo en ${pesosLabel}?`,
      a: `Puedes elegir entre las dos monedas. Usa el toggle "${primaryCurrency}/USD" arriba para ver los precios en cada una.`,
    },
    {
      q: '¿Hay descuentos para equipos grandes?',
      a: `Sí, para equipos de más de 50 ${agentLabel}, tenemos planes empresariales personalizados. Contáctanos en hola@closerbroker.com y te armamos un plan a la medida.`,
    },
    {
      q: '¿Qué pasa si cancelo mi suscripción?',
      a: 'Sin penalizaciones. Cancelas cuando quieras desde tu cuenta y mantienes acceso hasta el final del período facturado. Después, exportas todos tus datos (propiedades, prospectos, conversaciones) en formatos estándar y te llevas tu información donde quieras.',
    },
  ];
};

const PreciosFaq = () => {
  const [open, setOpen] = React.useState(0);
  const ctx = (typeof useCountry === 'function') ? useCountry() : { country: 'co' };
  const PRECIOS_FAQS = React.useMemo(() => buildPreciosFaqs(ctx.country), [ctx.country]);
  return (
    <section style={{ background: 'var(--bg-soft)' }}>
      <div className="container-narrow">
        <div style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 48px' }} className="reveal">
          <div className="eyebrow" style={{ marginBottom: 20 }}><span className="eyebrow-dot" />Preguntas frecuentes</div>
          <h2 className="h2" style={{ marginBottom: 16, textWrap: 'balance' }}>
            Preguntas <span className="serif" style={{ fontStyle: 'italic' }}>sobre los planes.</span>
          </h2>
        </div>

        <div className="reveal" style={{ maxWidth: 800, margin: '0 auto' }}>
          {PRECIOS_FAQS.map((it, i) => {
            const isOpen = open === i;
            return (
              <div key={i} style={{ borderBottom: '1px solid var(--border)' }}>
                <button
                  onClick={() => setOpen(isOpen ? -1 : i)}
                  style={{
                    width: '100%', padding: '24px 0',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 24,
                    textAlign: 'left',
                  }}
                >
                  <span style={{ fontSize: 16, fontWeight: 500, color: 'var(--fg)' }}>{it.q}</span>
                  <span style={{
                    flexShrink: 0,
                    width: 28, height: 28, borderRadius: '50%',
                    background: isOpen ? 'var(--grad)' : 'var(--bg-muted)',
                    color: isOpen ? '#fff' : 'var(--fg)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    transform: isOpen ? 'rotate(45deg)' : 'rotate(0)',
                    transition: 'all 0.3s',
                  }}>
                    <Icon name="plus" size={12} />
                  </span>
                </button>
                <div style={{
                  maxHeight: isOpen ? 400 : 0,
                  overflow: 'hidden',
                  transition: 'max-height 0.4s ease',
                }}>
                  <div style={{ paddingBottom: 24, fontSize: 15, color: 'var(--fg-soft)', lineHeight: 1.6, maxWidth: 680 }}>
                    {it.a}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};

window.PreciosFaq = PreciosFaq;
