// Pricing — 3 annual plans (annual only, never monthly) + Klarna/PayPal financing disclaimer
function Pricing() {
  const [yys, setYys] = React.useState(false);
  const [lb, setLb] = React.useState(false);
  const [stock, setStock] = React.useState({ total: 15, sold: 0, left: 15 });
  const [couponInput, setCouponInput] = React.useState('');
  const [appliedCoupon, setAppliedCoupon] = React.useState('');
  const [couponErr, setCouponErr] = React.useState('');

  // Live lifetime stock counter
  React.useEffect(() => {
    const load = () => fetch('/api/lifetime/stock', { cache: 'no-store' })
      .then(r => r.json())
      .then(d => { if (d && typeof d.left === 'number') setStock(d); })
      .catch(() => {});
    load();
    const id = setInterval(load, 30000); // refresh every 30s
    return () => clearInterval(id);
  }, []);

  const base = { esencial: 343, premium: 571 };
  const yysDiscount = yys ? 0.30 : 0;
  const esencial = Math.round(base.esencial * (1 - yysDiscount));
  const premium = Math.round(base.premium * (1 - yysDiscount));
  const lifetime = 699; // no discount on lifetime promo
  const tokensBonus = lb ? ' +20% tokens' : '';

  const plans = [
    {
      id: 'esencial',
      tier: 'Esencial',
      tag: 'Tú al mando',
      desc: 'Bolsa anual de tokens. Tú decides cuándo prospectar y a quién.',
      price: esencial,
      original: yys ? base.esencial : null,
      period: '/año',
      cta: 'Empezar Esencial',
      ctaStyle: 'ghost',
      stripeUrl: '/api/stripe/checkout-dynamic?plan=sin_rotador&period=yearly',
      features: [
        'Bolsa anual de tokens · gástalos a tu ritmo',
        'Prospección ilimitada en Google Maps + análisis SEO',
        'Generación de webs con IA (hero, logo, copy)',
        'Emails + WhatsApp + scripts de llamada',
        'Editor visual de cada web',
        'Soporte por email',
      ],
    },
    {
      id: 'premium',
      tier: 'Premium',
      tag: 'Con Rotador automático',
      desc: 'Tu cartera de citas se llena sola. Tú solo apareces a vender.',
      price: premium,
      original: yys ? base.premium : null,
      period: '/año',
      cta: 'Empezar Premium',
      ctaStyle: 'accent',
      popular: true,
      stripeUrl: '/api/stripe/checkout-dynamic?plan=con_rotador&period=yearly',
      features: [
        'Todo lo del plan Esencial',
        '🤖 Rotador automático: 10 emails al día sin que toques nada',
        'Tú eliges la categoría (ej: pintores) y la ciudad',
        'El bot scrapea, detecta los que más necesitan + email activo',
        'Geogrid (próximamente)',
        'Acceso prioritario + onboarding 1:1',
      ],
    },
    {
      id: 'lifetime',
      tier: 'Lifetime',
      tag: 'Pago único · para siempre',
      desc: 'Compras una vez. Lo tienes para toda la vida. Solo durante el lanzamiento.',
      price: lifetime,
      original: 1197,
      period: 'una vez',
      cta: 'Pillar Lifetime',
      ctaStyle: 'gold',
      dark: true,
      best: true,
      stripeUrl: '/api/stripe/checkout-dynamic?plan=lifetime',
      features: [
        'TODO lo del plan Premium · para siempre',
        '♾️ Sin renovaciones, sin sustos',
        '🤖 Rotador incluido de por vida',
        'Bolsa anual recurrente con bonus Yinyang Academy/local brain',
        'Todas las features futuras incluidas',
        `Quedan ${stock.left} de ${stock.total} plazas a este precio`,
      ],
    },
  ];

  // Promo coupon: from ?coupon= in the URL OR typed in the "¿Tienes un cupón?" field.
  // Only PUBLIC coupons (in COUPON_PROMOS) apply here; the checkout re-validates server-side.
  const COUPON_PROMOS = { ACADEMY15: { pct: 15, source: 'YinYang Academy' } };
  const urlCoupon = (() => { try { return (new URLSearchParams(window.location.search).get('coupon') || '').trim().toUpperCase(); } catch (e) { return ''; } })();
  const activeCoupon = (urlCoupon && COUPON_PROMOS[urlCoupon]) ? urlCoupon : (COUPON_PROMOS[appliedCoupon] ? appliedCoupon : '');
  const promo = COUPON_PROMOS[activeCoupon] || null;
  const couponPct = promo ? promo.pct : 0;
  const applyCoupon = () => {
    const code = (couponInput || '').trim().toUpperCase();
    if (COUPON_PROMOS[code]) { setAppliedCoupon(code); setCouponErr(''); }
    else { setAppliedCoupon(''); setCouponErr('Ese cupón no es válido.'); }
  };
  // Append the active coupon to subscription checkout links only (NOT lifetime — promo is Esencial/Premium).
  if (activeCoupon) plans.forEach(pl => { if (pl.stripeUrl && pl.stripeUrl.indexOf('checkout-dynamic') !== -1 && pl.stripeUrl.indexOf('plan=lifetime') === -1) pl.stripeUrl += '&coupon=' + encodeURIComponent(activeCoupon); });

  return (
    <section id="planes" style={{ padding: 'var(--pl-section-py) 0' }}>
      <div className="pl-container">
        <div className="pl-section-head">
          <span className="pl-eyebrow">Planes</span>
          <h2 className="pl-display">Elige cómo quieres <span className="pl-accent-grad">trabajar</span></h2>
          <p>Dos planes anuales + una oferta lifetime de lanzamiento. Cancela cuando quieras.</p>
          {promo && (
            <div style={{
              margin: '20px auto 0', maxWidth: 700,
              background: 'linear-gradient(120deg,#7c3aed 0%,#9333ea 45%,#ec4899 100%)',
              color: '#fff', borderRadius: 20, padding: '20px 26px',
              boxShadow: '0 18px 44px -14px rgba(124,58,237,.6)', textAlign: 'center',
            }}>
              <div style={{ fontSize: 12.5, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase', opacity: .92, marginBottom: 6 }}>
                🎉 Vienes de {promo.source}
              </div>
              <div style={{ fontSize: 21, fontWeight: 900, lineHeight: 1.25, marginBottom: 7 }}>
                ¡Gracias por llegar desde el vídeo o el podcast! 🙌
              </div>
              <div style={{ fontSize: 15.5, fontWeight: 600, opacity: .97 }}>
                Tienes un <span style={{ background: 'rgba(255,255,255,.22)', padding: '2px 10px', borderRadius: 8, fontWeight: 900 }}>{promo.pct}% de descuento</span> exclusivo — ya aplicado en los precios de abajo 👇
              </div>
            </div>
          )}
          {!promo && (
            <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--pl-ink-3)' }}>¿Tienes un cupón?</span>
              <input
                value={couponInput}
                onChange={(e) => { setCouponInput(e.target.value); if (couponErr) setCouponErr(''); }}
                onKeyDown={(e) => { if (e.key === 'Enter') applyCoupon(); }}
                placeholder="Escríbelo aquí"
                style={{ padding: '8px 12px', borderRadius: 10, border: '1px solid var(--pl-border-strong)', fontSize: 14, fontWeight: 700, textTransform: 'uppercase', width: 160, outline: 'none', background: 'var(--pl-surface)', color: 'var(--pl-ink)' }}
              />
              <button onClick={applyCoupon} className="pl-btn" style={{ background: 'var(--pl-ink)', color: '#fff', padding: '8px 18px', fontSize: 14 }}>Aplicar</button>
              {couponErr && <span style={{ fontSize: 13, fontWeight: 700, color: '#dc2626', width: '100%', marginTop: 4 }}>{couponErr}</span>}
            </div>
          )}
        </div>

        {/* Discount toggles */}
        <div style={{
          maxWidth: 760, margin: '0 auto 28px',
          background: 'linear-gradient(135deg, #fff8d6 0%, #fff 80%)',
          border: '1px solid rgba(234,179,8,.3)',
          borderRadius: 18,
          padding: '20px 22px',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
            flexWrap: 'wrap',
          }}>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14.5 }}>
                ¿Eres alumno Yinyang Academy o tienes local brain?
              </div>
              <div style={{ fontSize: 13, color: 'var(--pl-ink-3)' }}>
                Yinyang Academy te da <b>−30%</b> en el precio · local brain te da <b>+20% tokens</b> anuales. Acumulables.
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <DiscountToggle checked={yys} onChange={setYys}>Alumno Yinyang Academy <span style={{ opacity: .65 }}>−30%</span></DiscountToggle>
              <DiscountToggle checked={lb} onChange={setLb}>Tengo local brain <span style={{ opacity: .65 }}>+20% tok</span></DiscountToggle>
            </div>
          </div>
        </div>

        {/* Plan cards */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20,
          alignItems: 'stretch',
          padding: '32px 0 28px',
        }}>
          {plans.map(p => <PlanCard key={p.id} p={p} tokensBonus={tokensBonus} stockLeft={stock.left} stockTotal={stock.total} couponPct={p.period !== 'una vez' ? couponPct : 0} />)}
        </div>

        {/* Footnotes */}
        <div style={{
          textAlign: 'center', marginTop: 22,
          fontSize: 13.5, color: 'var(--pl-ink-3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, flexWrap: 'wrap',
        }}>
          <span>🔒 Pago seguro con Stripe</span>
          <span>·</span>
          <span>📄 IVA incluido</span>
          <span>·</span>
          <span>⚡ Acceso inmediato</span>
          <span>·</span>
          <span>✋ Cancela cuando quieras</span>
        </div>

        {/* Annual-only + Klarna/PayPal financing disclaimer (their financing, we charge the full year) */}
        <div style={{
          marginTop: 24, maxWidth: 640, margin: '24px auto 0',
          textAlign: 'center', fontSize: 13, lineHeight: 1.6, color: 'var(--pl-ink-3)',
        }}>
          💳 Todos los precios son <b style={{ color: 'var(--pl-ink-2)' }}>anuales</b>. Si lo prefieres, al pagar con <b>Klarna</b> o <b>PayPal</b> puedes dividir ese pago hasta en 12 meses — ellos te financian a ti; nosotros recibimos el año completo.
        </div>
      </div>
    </section>
  );
}

function DiscountToggle({ checked, onChange, children }) {
  return (
    <label style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 14px',
      background: checked ? 'var(--pl-ink)' : '#fff',
      color: checked ? '#fff' : 'var(--pl-ink)',
      border: '1px solid ' + (checked ? 'var(--pl-ink)' : 'var(--pl-border)'),
      borderRadius: 999,
      cursor: 'pointer',
      fontWeight: 600, fontSize: 13,
      userSelect: 'none',
    }}>
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)}
             style={{ accentColor: 'var(--pl-accent)', cursor: 'pointer' }} />
      {children}
    </label>
  );
}

function PlanCard({ p, tokensBonus, stockLeft = 15, stockTotal = 15, couponPct = 0 }) {
  const isDark = !!p.dark;
  const hasCoupon = couponPct > 0 && p.period !== 'una vez';
  const discounted = hasCoupon ? Math.round(p.price * (1 - couponPct / 100)) : p.price;
  const monthly = p.period === 'una vez' ? null : Math.round(p.price / 12);
  const cardStyle = isDark ? {
    background: 'linear-gradient(160deg, var(--pl-accent-ink) 0%, #3b1d8b 60%, var(--pl-accent-deep) 100%)',
    color: '#fff',
    border: '1px solid rgba(255,255,255,.1)',
    boxShadow: '0 20px 60px -20px rgba(60,24,140,.6)',
  } : {
    background: 'var(--pl-surface)',
    color: 'var(--pl-ink)',
    border: '1px solid ' + (p.popular ? 'var(--pl-accent)' : 'var(--pl-border)'),
    boxShadow: p.popular ? '0 20px 50px -20px rgba(124,58,237,.4)' : 'var(--pl-shadow)',
  };
  const ink2 = isDark ? 'rgba(255,255,255,.85)' : 'var(--pl-ink-2)';
  const muted = isDark ? 'rgba(255,255,255,.55)' : 'var(--pl-ink-3)';

  return (
    <div style={{
      ...cardStyle,
      borderRadius: 26,
      padding: 30,
      display: 'flex', flexDirection: 'column',
      position: 'relative',
      transform: p.popular ? 'scale(1.02)' : 'none',
    }}>
      {(p.popular || p.best) && (
        <span style={{
          position: 'absolute', top: -12, left: '50%', transform: 'translateX(-50%)',
          padding: '5px 14px', borderRadius: 999,
          background: p.best ? '#fbbf24' : 'var(--pl-accent)',
          color: p.best ? '#1a0d3a' : '#fff',
          fontSize: 11.5, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase',
          whiteSpace: 'nowrap',
          boxShadow: '0 6px 16px -4px rgba(0,0,0,.25)',
        }}>
          {p.best ? `🔥 Mejor valor · quedan ${stockLeft} de ${stockTotal}` : '✦ Más popular'}
        </span>
      )}

      <div style={{ marginBottom: 6 }}>
        <span style={{
          fontSize: 11, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase',
          color: isDark ? '#fbbf24' : 'var(--pl-accent)',
        }}>{p.tier}</span>
      </div>
      <h3 className="pl-display" style={{ fontSize: 28, margin: '0 0 6px', letterSpacing: '-.01em' }}>{p.tag}</h3>
      <p style={{ margin: '0 0 22px', fontSize: 14, color: muted, lineHeight: 1.5 }}>{p.desc}</p>

      <div style={{ marginBottom: 18 }}>
        {hasCoupon ? (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 3 }}>
              <span style={{ fontSize: 17, color: muted, textDecoration: 'line-through', fontWeight: 700 }}>{p.price}€</span>
              <span style={{ fontSize: 11.5, fontWeight: 900, color: '#fff', background: '#16a34a', padding: '2px 9px', borderRadius: 999, letterSpacing: '.02em' }}>−{couponPct}% YinYang</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{
                fontFamily: 'var(--pl-font-display)', fontWeight: 700,
                fontSize: 56, letterSpacing: '-.03em',
                color: isDark ? '#fff' : 'var(--pl-ink)', lineHeight: 1,
              }}>{discounted}€</span>
              <span style={{ fontSize: 14, color: muted, fontWeight: 600 }}>{p.period}</span>
            </div>
            <div style={{ fontSize: 13, color: ink2, marginTop: 6, fontWeight: 800 }}>
              🎉 Te ahorras {p.price - discounted}€ · facturación anual
            </div>
          </>
        ) : (
          <>
            {p.original && (
              <div style={{ fontSize: 14, color: muted, textDecoration: 'line-through', fontWeight: 600 }}>
                {p.original}€
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{
                fontFamily: 'var(--pl-font-display)', fontWeight: 700,
                fontSize: 56, letterSpacing: '-.03em',
                color: isDark ? '#fff' : 'var(--pl-ink)', lineHeight: 1,
              }}>{p.price}€</span>
              <span style={{ fontSize: 14, color: muted, fontWeight: 600 }}>{p.period}</span>
            </div>
            {p.period !== 'una vez' ? (
              <div style={{ fontSize: 13, color: muted, marginTop: 6 }}>
                <b style={{ color: ink2 }}>Facturación anual</b> · un solo pago al año
              </div>
            ) : (
              <div style={{ fontSize: 13, color: '#fde68a', marginTop: 6, fontWeight: 600 }}>
                ♾️ Pago único · sin renovaciones
              </div>
            )}
          </>
        )}
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 22 }}>
        {p.features.map((f, i) => (
          <div key={i} style={{ display: 'flex', gap: 9, fontSize: 13.5, lineHeight: 1.45 }}>
            <span style={{
              flexShrink: 0, width: 18, height: 18, borderRadius: '50%',
              background: isDark ? 'rgba(251,191,36,.18)' : 'rgba(124,58,237,.12)',
              color: isDark ? '#fbbf24' : 'var(--pl-accent)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginTop: 1,
            }}>
              <IconCheck size={11} stroke={3} />
            </span>
            <span style={{ color: ink2 }}>{f}</span>
          </div>
        ))}
        {tokensBonus && (
          <div style={{
            display: 'flex', gap: 9, fontSize: 13.5,
            padding: '8px 10px', borderRadius: 8,
            background: isDark ? 'rgba(251,191,36,.12)' : 'rgba(124,58,237,.08)',
            fontWeight: 700,
          }}>
            <span>🎁</span><span>{tokensBonus} aplicado (local brain)</span>
          </div>
        )}
      </div>

      <a
        href={p.stripeUrl || '/api/auth/signin/google?callbackUrl=%2Fprecios'}
        target={p.stripeUrl && p.stripeUrl.startsWith('http') ? '_blank' : '_self'}
        rel={p.stripeUrl && p.stripeUrl.startsWith('http') ? 'noopener noreferrer' : undefined}
        className="pl-btn"
        style={{
          background: p.ctaStyle === 'gold' ? '#fbbf24' : (p.ctaStyle === 'accent' ? 'var(--pl-accent)' : (isDark ? '#fff' : 'var(--pl-ink)')),
          color: p.ctaStyle === 'gold' ? '#1a0d3a' : (p.ctaStyle === 'accent' ? '#fff' : (isDark ? 'var(--pl-ink)' : '#fff')),
          width: '100%',
          fontSize: 15.5,
          boxShadow: p.ctaStyle === 'gold' ? '0 6px 20px -6px rgba(251,191,36,.6)' : undefined,
        }}
      >
        {p.cta} <IconArrowRight size={15} stroke={2.5} />
      </a>

      <div style={{ marginTop: 12, textAlign: 'center', fontSize: 11.5, color: muted }}>
        {p.id === 'lifetime' ? '🔒 Acceso de por vida · Pago único Stripe' : '🔒 Cancela cuando quieras · Stripe'}
      </div>
    </div>
  );
}

window.Pricing = Pricing;
