// plans.jsx — 3 plan variants + comparison table

const PLAN_DATA = [
  {
    id: 'continuidad',
    name: 'Continuidad',
    tagline: 'Monitoreo y mantenimiento esencial para mantener tu web estable.',
    price: '49',
    currency: 'USD',
    period: '/mes',
    cta: 'Empezar con Continuidad',
    features: [
      { strong: true, text: 'Actualización mensual de core, plugins y themes' },
      { strong: false, text: 'Backup mensual completo' },
      { strong: false, text: 'Verificación básica de seguridad' },
      { strong: false, text: 'Reporte mensual al cliente' },
      { strong: false, text: 'Soporte correctivo básico' },
      { strong: false, text: 'Wordfence Community' },
      { strong: false, text: 'AIO WPM Estándar' },
    ],
  },
  {
    id: 'control',
    name: 'Control',
    tagline: 'Mayor frecuencia y control preventivo para reducir riesgos y caídas.',
    price: '129',
    currency: 'USD',
    period: '/mes',
    featured: true,
    cta: 'Recomendado',
    features: [
      { strong: true, text: 'Todo lo del plan Continuidad' },
      { strong: false, text: 'Monitoreo semanal del sitio' },
      { strong: false, text: 'Backups quincenales verificados' },
      { strong: false, text: 'Revisión de vulnerabilidades conocidas (CVE)' },
      { strong: false, text: 'Optimización básica de entorno (PHP, memoria)' },
      { strong: false, text: 'Reporte detallado mensual' },
      { strong: false, text: 'Wordfence Pro' },
      { strong: false, text: 'AIO WPM PRO' },
    ],
  },
  {
    id: 'ultra',
    name: 'Ultra',
    tagline: 'Máxima continuidad y seguridad para operaciones críticas.',
    price: '299',
    currency: 'USD',
    period: '/mes',
    cta: 'Hablemos de Ultra',
    features: [
      { strong: true, text: 'Todo lo del plan Control' },
      { strong: false, text: 'Monitoreo diario del sitio' },
      { strong: false, text: 'Backups semanales' },
      { strong: false, text: 'Copia en AWS S3' },
      { strong: false, text: 'Detección temprana de vulnerabilidades (CVE)' },
      { strong: false, text: 'Alertas proactivas vía email' },
      { strong: false, text: 'Auditoría técnica periódica' },
    ],
  },
];

const BILLING = {
  semiannual: {
    label: 'Semestral',
    badge: null,
    disc: 1.00,
    getNote: (base) => `$${base * 6} facturado c/6 meses`,
    noteColor: 'var(--text-dim)',
  },
  annual: {
    label: 'Anual',
    badge: 'Ahorra 20%',
    disc: 0.80,
    getNote: (base) => {
      const yr = Math.round(base * 0.80) * 12;
      return `$${yr}/año · ahorras $${base * 12 - yr}`;
    },
    noteColor: 'var(--ok)',
  },
};

// VARIANT 1 — Classic three cards, featured in middle
function PlansCards({ billing }) {
  return (
    <div className="grid-3">
      {PLAN_DATA.map((p) => {
        const base = parseInt(p.price);
        const monthlyPrice = Math.round(base * BILLING[billing].disc);
        const bInfo = BILLING[billing];
        return (
        <div className={`plan-card ${p.featured ? 'featured' : ''}`} key={p.id}>
          {p.featured && <div className="plan-tag">Recomendado</div>}
          <div className="plan-name">{p.name}</div>
          <div className="plan-sub">{p.tagline}</div>
          <div className="plan-price">
            <span style={{ color: 'var(--text-muted)', fontSize: 18, marginRight: 2 }}>$</span>
            <span className="amount">{monthlyPrice}</span>
            <span className="per">{p.currency} /mes</span>
          </div>
          <div className="mono" style={{ fontSize: 10, color: bInfo.noteColor, letterSpacing: '0.06em', marginTop: -8, marginBottom: 8 }}>
            {bInfo.getNote(base)}
          </div>
          <ul className="plan-features">
            {p.features.map((f, i) => (
              <li key={i} className={f.strong ? 'strong' : ''}>
                <CheckIcon size={16} color={p.featured ? 'var(--primary)' : 'var(--ok)'} />
                {f.text}
              </li>
            ))}
          </ul>
          <a href="#contacto" className={`btn ${p.featured ? 'btn-primary' : 'btn-ghost'} btn-lg`} style={{ justifyContent: 'center' }}>
            {p.cta}
          </a>
        </div>
        );
      })}
    </div>
  );
}

// VARIANT 2 — Table-first
function PlansTable({ billing }) {
  const prices = PLAN_DATA.map(p => Math.round(parseInt(p.price) * BILLING[billing].disc));
  return (
    <>
      <div style={{ overflowX: 'auto', borderRadius: 'var(--r-md)', border: '1px solid var(--border)' }}>
        <table className="plan-table">
          <thead>
            <tr>
              <th></th>
              <th>Continuidad</th>
              <th className="featured">Control · Recomendado</th>
              <th>Ultra</th>
            </tr>
            <tr>
              <td></td>
              <td><span className="display" style={{ fontSize: 28 }}>${prices[0]}</span><span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 4 }}>/mes</span></td>
              <td className="featured"><span className="display" style={{ fontSize: 28, color: 'var(--primary)' }}>${prices[1]}</span><span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 4 }}>/mes</span></td>
              <td><span className="display" style={{ fontSize: 28 }}>${prices[2]}</span><span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 4 }}>/mes</span></td>
            </tr>
          </thead>
          <tbody>
            <tr className="section-row"><td colSpan="4">Mantenimiento</td></tr>
            <CompareRow label="Actualizaciones de core, plugins, themes" v={['Mensual', 'Semanal', 'Diaria']} />
            <CompareRow label="Verificación post-update manual" v={[true, true, true]} />
            <CompareRow label="Eliminación de plugins/themes obsoletos" v={[false, true, true]} />
            <CompareRow label="Optimización de entorno (PHP, memoria, caché)" v={[false, true, true]} />

            <tr className="section-row"><td colSpan="4">Seguridad</td></tr>
            <CompareRow label="Verificación básica de seguridad" v={[true, true, true]} />
            <CompareRow label="Revisión de vulnerabilidades conocidas (CVE)" v={[false, true, true]} />
            <CompareRow label="Detección temprana de CVEs" v={[false, false, true]} />
            <CompareRow label="Firewall + anti-malware activo" v={[true, true, true]} />
            <CompareRow label="Alertas proactivas (email + WhatsApp)" v={[false, false, true]} />

            <tr className="section-row"><td colSpan="4">Backups</td></tr>
            <CompareRow label="Frecuencia de backup" v={['Mensual', 'Quincenal', 'Diaria']} />
            <CompareRow label="Backup pre-update verificado" v={[true, true, true]} />
            <CompareRow label="Backup post-update verificado" v={[false, true, true]} />

            <tr className="section-row"><td colSpan="4">Soporte y reportes</td></tr>
            <CompareRow label="Reporte al cliente" v={['Mensual básico', 'Detallado', 'Detallado + auditoría']} />
            <CompareRow label="Soporte correctivo" v={['Básico', 'Estándar', 'Prioritario · SLA']} />
            <CompareRow label="Auditoría técnica periódica" v={[false, false, true]} />
          </tbody>
        </table>
      </div>
      <div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 36, flexWrap: 'wrap' }}>
        <a href="#contacto" className="btn btn-ghost">Empezar con Continuidad</a>
        <a href="#contacto" className="btn btn-primary">Recomendado · Control <ArrowIcon /></a>
        <a href="#contacto" className="btn btn-ghost">Hablemos de Ultra</a>
      </div>
    </>
  );
}

function CompareRow({ label, v }) {
  const render = (val, isFeat) => {
    if (val === true) return <span className="check">✓</span>;
    if (val === false) return <span className="dash">—</span>;
    return val;
  };
  return (
    <tr>
      <td>{label}</td>
      <td>{render(v[0])}</td>
      <td className="featured">{render(v[1], true)}</td>
      <td>{render(v[2])}</td>
    </tr>
  );
}

// VARIANT 3 — Stacked/tiered horizontal
function PlansStacked({ billing }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {PLAN_DATA.map((p, idx) => {
        const base = parseInt(p.price);
        const monthlyPrice = Math.round(base * BILLING[billing].disc);
        const bInfo = BILLING[billing];
        return (
        <div
          key={p.id}
          className={p.featured ? 'plan-card plan-stacked-card featured' : 'plan-card plan-stacked-card'}
          style={{
            padding: '36px 40px',
          }}
        >
          {p.featured && <div className="plan-tag">Recomendado</div>}
          <div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.12em', marginBottom: 8 }}>NIVEL · 0{idx + 1}</div>
            <div className="plan-name" style={{ fontSize: 40 }}>{p.name}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 14 }}>
              <span style={{ color: 'var(--text-muted)', fontSize: 18 }}>$</span>
              <span className="display" style={{ fontSize: 56, lineHeight: 1, color: p.featured ? 'var(--primary)' : 'var(--text)' }}>{monthlyPrice}</span>
              <span style={{ color: 'var(--text-muted)', fontSize: 13 }}>/mes</span>
            </div>
            <div className="mono" style={{ fontSize: 10, color: bInfo.noteColor, letterSpacing: '0.06em', marginTop: 6 }}>
              {bInfo.getNote(base)}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.55, marginBottom: 18 }}>
              {p.tagline}
            </div>
            <ul style={{ listStyle: 'none', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 24px' }}>
              {p.features.map((f, i) => (
                <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, color: f.strong ? 'var(--text)' : 'var(--text-muted)' }}>
                  <CheckIcon size={14} color={p.featured ? 'var(--primary)' : 'var(--ok)'} />
                  {f.text}
                </li>
              ))}
            </ul>
          </div>
          <div>
            <a href="#contacto" className={`btn ${p.featured ? 'btn-primary' : 'btn-ghost'} btn-lg`}>
              {p.cta} <ArrowIcon />
            </a>
          </div>
        </div>
        );
      })}
    </div>
  );
}

function Plans({ variant }) {
  const [billing, setBilling] = React.useState('semiannual');

  let body;
  if (variant === 'table') body = <PlansTable billing={billing} />;
  else if (variant === 'stacked') body = <PlansStacked billing={billing} />;
  else body = <PlansCards billing={billing} />;

  return (
    <section className="section" id="planes">
      <div className="sec-head">
        <span className="eyebrow">Planes</span>
        <h2 className="display h2">
          Tres niveles.<br/>
          <span style={{ color: 'var(--primary)' }}>Misma promesa</span>: que no tengas que ocuparte.
        </h2>
        {/* <p className="lead">
          Todos los planes incluyen plataforma, soporte por chat y reporte mensual. Sin permanencia mínima — si no te aporta, te vas.
        </p> */}
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 40 }}>
        <div style={{ display: 'inline-flex', background: 'rgba(15,29,51,0.6)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 4, gap: 2 }}>
          {Object.entries(BILLING).map(([key, b]) => (
            <button
              key={key}
              onClick={() => setBilling(key)}
              style={{
                appearance: 'none', border: 'none', cursor: 'pointer',
                padding: '8px 22px', borderRadius: 'calc(var(--r-md) - 2px)',
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.06em',
                textTransform: 'uppercase', whiteSpace: 'nowrap',
                background: billing === key ? 'var(--primary)' : 'transparent',
                color: billing === key ? '#fff' : 'var(--text-muted)',
                transition: 'background 0.15s, color 0.15s',
                display: 'flex', alignItems: 'center', gap: 6,
              }}
            >
              {b.label}
              {b.badge && (
                <span style={{
                  fontSize: 9, fontWeight: 700, letterSpacing: '0.08em',
                  background: billing === key ? 'rgba(255,255,255,0.25)' : 'rgba(30,156,255,0.15)',
                  color: billing === key ? '#fff' : 'var(--primary)',
                  padding: '2px 5px', borderRadius: 4,
                }}>
                  {b.badge}
                </span>
              )}
            </button>
          ))}
        </div>
      </div>

      {body}

      {/* <div style={{ marginTop: 36, display: 'flex', justifyContent: 'center' }}>
        <div className="pill" style={{ height: 32, fontSize: 11 }}>
          <span className="dot pulse" style={{ background: 'var(--ok)' }} />
          14 días de garantía · Sin permanencia · Diagnóstico inicial gratis
        </div>
      </div> */}
    </section>
  );
}

Object.assign(window, { Plans });
