/* Blackstock — Checkout / Onboarding flow */

const CheckoutPage = ({ onNavigate }) => {
  const [step, setStep] = React.useState(1);
  const [plan, setPlan] = React.useState('PRO');
  const [billing, setBilling] = React.useState('monthly');
  const [accounts, setAccounts] = React.useState(2);
  const [email, setEmail] = React.useState('');
  const [coupon, setCoupon] = React.useState('');
  const [couponApplied, setCouponApplied] = React.useState(false);

  // CheckoutPage está deprecado: el flujo comercial ahora se hace por
  // llamada (BookingModal). Si alguien aterriza aquí, redirigimos al
  // home y abrimos la reserva de llamada automáticamente.
  React.useEffect(() => {
    if (typeof window.bsOpenBooking === 'function') {
      window.bsOpenBooking();
    }
    onNavigate && onNavigate('home');
  }, []);

  const planMap = {
    BASIC: { monthly: 22.90, max: 1 },
    PRO: { monthly: 149.90, max: 4 },
  };
  const price = (planMap[plan] || planMap.BASIC).monthly;
  const discount = couponApplied ? Math.round(price * 0.2 * 100) / 100 : 0;
  const total = Math.round((price - discount) * 100) / 100;

  return (
    <div className="bs-shell" style={{ minHeight: '100vh' }}>
      {/* Compact nav */}
      <div style={{ borderBottom: '1px solid var(--line)', background: 'var(--bg)' }}>
        <div className="bs-container" style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: 64
        }}>
          <button onClick={() => onNavigate('home')} style={{ background: 'none', border: 'none', cursor: 'pointer' }}>
            <Logo />
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', letterSpacing: '0.06em' }}>
              ● PAGO SEGURO · STRIPE
            </span>
            <button onClick={() => onNavigate('home')} className="bs-btn bs-btn-ghost bs-btn-sm" style={{ height: 36 }}>
              ← Volver
            </button>
          </div>
        </div>
      </div>

      <div className="bs-container" style={{ paddingTop: 60, paddingBottom: 100 }}>
        {/* Step indicator */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 48, justifyContent: 'center' }}>
          {[
          { n: 1, l: 'Plan' },
          { n: 2, l: 'Cuenta' },
          { n: 3, l: 'Pago' }].
          map((s, i) =>
          <React.Fragment key={i}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                width: 28, height: 28, borderRadius: '50%',
                background: step >= s.n ? 'var(--acid)' : 'var(--bg-2)',
                color: step >= s.n ? '#000' : 'var(--fg-3)',
                border: '1px solid', borderColor: step >= s.n ? 'var(--acid)' : 'var(--line-2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700
              }}>{step > s.n ? '✓' : s.n}</div>
                <span style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em',
                color: step >= s.n ? 'var(--fg)' : 'var(--fg-3)', textTransform: 'uppercase'
              }}>{s.l}</span>
              </div>
              {i < 2 && <div style={{ width: 40, height: 1, background: step > s.n ? 'var(--acid)' : 'var(--line)' }} />}
            </React.Fragment>
          )}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48, alignItems: 'start' }}>
          {/* Left form */}
          <div>
            {step === 1 &&
            <Step1Plan
              plan={plan} setPlan={setPlan}
              billing={billing} setBilling={setBilling}
              accounts={accounts} setAccounts={setAccounts}
              planMap={planMap} />

            }
            {step === 2 &&
            <Step2Account email={email} setEmail={setEmail} />
            }
            {step === 3 &&
            <Step3Payment
              coupon={coupon} setCoupon={setCoupon}
              couponApplied={couponApplied} setCouponApplied={setCouponApplied} />

            }

            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32 }}>
              <button
                onClick={() => step > 1 ? setStep(step - 1) : onNavigate('home')}
                className="bs-btn bs-btn-ghost">
                ← Atrás</button>
              <button
                onClick={() => step < 3 ? setStep(step + 1) : alert('🚀 Demo: aquí iría Stripe checkout')}
                className="bs-btn bs-btn-acid">
                
                {step < 3 ? 'Continuar →' : 'Suscribirse →'}
              </button>
            </div>
          </div>

          {/* Right summary */}
          <OrderSummary
            plan={plan} planMap={planMap} billing={billing}
            accounts={accounts} price={price} discount={discount} total={total}
            couponApplied={couponApplied} />
          
        </div>
      </div>
    </div>);

};

const Step1Plan = ({ plan, setPlan, billing, setBilling, accounts, setAccounts, planMap }) => {
  const plans = [
  { id: 'BASIC', tag: 'Estándar', desc: 'Todo Blackstock. Opera desde tu equipo.' },
  { id: 'PRO', tag: 'Incluye Bazooka', desc: 'Todo Blackstock + worker remoto 24/7.', highlight: true }];


  return (
    <div>
      <h2 className="bs-display" style={{ fontSize: 32, fontWeight: 700, margin: 0, marginBottom: 8, letterSpacing: '-0.025em' }}>
        Elige tu plan
      </h2>
      <p style={{ color: 'var(--fg-2)', margin: 0, marginBottom: 28 }}>
        Cambias o cancelas cuando quieras. Sin permanencia. Facturación mensual.
      </p>

      {/* Toggle anual eliminado: solo facturación mensual */}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {plans.map((p) =>
        <button key={p.id} onClick={() => setPlan(p.id)} style={{
          width: '100%', textAlign: 'left', cursor: 'pointer',
          background: plan === p.id ? 'rgba(214,255,77,0.06)' : 'var(--bg-1)',
          border: '1px solid', borderColor: plan === p.id ? 'var(--line-acid)' : 'var(--line)',
          borderRadius: 14, padding: 20,
          display: 'flex', alignItems: 'center', gap: 16,
          transition: 'all .15s ease'
        }}>
            <div style={{
            width: 22, height: 22, borderRadius: '50%',
            border: '2px solid', borderColor: plan === p.id ? 'var(--acid)' : 'var(--line-2)',
            background: plan === p.id ? 'var(--acid)' : 'transparent',
            flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
              {plan === p.id && <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#000' }}></span>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                <span className="bs-display" style={{ fontSize: 18, fontWeight: 700, color: "rgb(214, 255, 77)" }}>{p.id}</span>
                {p.highlight && <span className="bs-pill acid" style={{ height: 20, fontSize: 9 }}>POPULAR</span>}
              </div>
              <div style={{ color: 'var(--fg-3)', fontSize: 13 }}>{p.desc}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="bs-num" style={{
              fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em',
              color: plan === p.id ? 'var(--acid)' : 'var(--fg)'
            }}>{planMap[p.id][billing]}€</div>
              <div style={{ color: 'var(--fg-3)', fontSize: 11, fontFamily: 'var(--font-mono)' }}>/mes</div>
            </div>
          </button>
        )}
      </div>
    </div>);

};

const Step2Account = ({ email, setEmail }) =>
<div>
    <h2 className="bs-display" style={{ fontSize: 32, fontWeight: 700, margin: 0, marginBottom: 8, letterSpacing: '-0.025em' }}>
      Crea tu cuenta
    </h2>
    <p style={{ color: 'var(--fg-2)', margin: 0, marginBottom: 28 }}>
      Acceso inmediato al panel y a la academia. Recibes el welcome kit en tu email.
    </p>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {[
    { label: 'EMAIL', placeholder: 'tu@email.com', value: email, onChange: setEmail, type: 'email' },
    { label: 'NOMBRE', placeholder: 'Tu nombre', type: 'text' },
    { label: 'TELÉFONO (opcional)', placeholder: '+34 ...', type: 'tel' }].
    map((f, i) =>
    <div key={i}>
          <label className="bs-eyebrow" style={{ display: 'block', marginBottom: 8 }}>{f.label}</label>
          <input
        type={f.type} placeholder={f.placeholder}
        value={f.value} onChange={(e) => f.onChange && f.onChange(e.target.value)}
        style={{
          width: '100%', height: 52, padding: '0 18px',
          background: 'var(--bg-1)', border: '1px solid var(--line-2)', borderRadius: 12,
          color: 'var(--fg)', fontSize: 15, fontFamily: 'var(--font-body)',
          outline: 'none'
        }}
        onFocus={(e) => e.target.style.borderColor = 'var(--acid)'}
        onBlur={(e) => e.target.style.borderColor = 'var(--line-2)'} />
      
        </div>
    )}

      <label style={{
      display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 8,
      fontSize: 13, color: 'var(--fg-2)', cursor: 'pointer'
    }}>
        <input type="checkbox" defaultChecked style={{ marginTop: 3, accentColor: 'var(--acid)' }} />
        <span>Acepto los términos y condiciones y la política de privacidad. Puedo cancelar cuando quiera desde el panel.</span>
      </label>
    </div>
  </div>;


const Step3Payment = ({ coupon, setCoupon, couponApplied, setCouponApplied }) =>
<div>
    <h2 className="bs-display" style={{ fontSize: 32, fontWeight: 700, margin: 0, marginBottom: 8, letterSpacing: '-0.025em' }}>
      Método de pago
    </h2>
    <p style={{ color: 'var(--fg-2)', margin: 0, marginBottom: 28 }}>
      Pago seguro. Te cobramos hoy y se renueva mensualmente. Cancelas cuando quieras.
    </p>

    <div style={{
    padding: '14px 16px', background: 'rgba(214,255,77,0.05)',
    border: '1px solid var(--line-acid)', borderRadius: 10, marginBottom: 24,
    display: 'flex', alignItems: 'center', gap: 10, fontSize: 13
  }}>
      <span className="bs-dot" style={{ width: 8, height: 8 }}></span>
      <span><strong style={{ color: 'var(--acid)' }}>Acceso inmediato.</strong> Activamos el panel en cuanto se confirma el pago.</span>
    </div>

    <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
      {['Tarjeta', 'PayPal', 'Bizum'].map((m, i) =>
    <button key={i} style={{
      flex: 1, height: 56,
      background: i === 0 ? 'rgba(214,255,77,0.06)' : 'var(--bg-1)',
      border: '1px solid', borderColor: i === 0 ? 'var(--line-acid)' : 'var(--line-2)',
      borderRadius: 12, color: 'var(--fg)', cursor: 'pointer',
      fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 14
    }}>{m}</button>
    )}
    </div>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div>
        <label className="bs-eyebrow" style={{ display: 'block', marginBottom: 8 }}>NÚMERO DE TARJETA</label>
        <input
        placeholder="4242 4242 4242 4242"
        style={{
          width: '100%', height: 52, padding: '0 18px',
          background: 'var(--bg-1)', border: '1px solid var(--line-2)', borderRadius: 12,
          color: 'var(--fg)', fontSize: 15, fontFamily: 'var(--font-mono)', outline: 'none'
        }} />
      
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div>
          <label className="bs-eyebrow" style={{ display: 'block', marginBottom: 8 }}>EXPIRACIÓN</label>
          <input
          placeholder="MM / AA"
          style={{
            width: '100%', height: 52, padding: '0 18px',
            background: 'var(--bg-1)', border: '1px solid var(--line-2)', borderRadius: 12,
            color: 'var(--fg)', fontSize: 15, fontFamily: 'var(--font-mono)', outline: 'none'
          }} />
        
        </div>
        <div>
          <label className="bs-eyebrow" style={{ display: 'block', marginBottom: 8 }}>CVC</label>
          <input
          placeholder="123"
          style={{
            width: '100%', height: 52, padding: '0 18px',
            background: 'var(--bg-1)', border: '1px solid var(--line-2)', borderRadius: 12,
            color: 'var(--fg)', fontSize: 15, fontFamily: 'var(--font-mono)', outline: 'none'
          }} />
        
        </div>
      </div>

      <div style={{ marginTop: 12 }}>
        <label className="bs-eyebrow" style={{ display: 'block', marginBottom: 8 }}>CÓDIGO DE DESCUENTO</label>
        <div style={{ display: 'flex', gap: 8 }}>
          <input
          value={coupon} onChange={(e) => setCoupon(e.target.value)}
          placeholder="EJ. RESELLER20"
          style={{
            flex: 1, height: 52, padding: '0 18px',
            background: 'var(--bg-1)', border: '1px solid var(--line-2)', borderRadius: 12,
            color: 'var(--fg)', fontSize: 15, fontFamily: 'var(--font-mono)', outline: 'none'
          }} />
        
          <button
          onClick={() => coupon.length > 2 && setCouponApplied(true)}
          className="bs-btn bs-btn-ghost"
          style={{ height: 52 }}>
          
            {couponApplied ? '✓ Aplicado' : 'Aplicar'}
          </button>
        </div>
      </div>
    </div>
  </div>;


const OrderSummary = ({ plan, planMap, billing, price, discount, total, couponApplied }) =>
<div style={{
  background: 'linear-gradient(180deg, var(--bg-2), var(--bg-1))',
  border: '1px solid var(--line-2)', borderRadius: 16,
  padding: 28, position: 'sticky', top: 100
}}>
    <div className="bs-eyebrow acid" style={{ marginBottom: 16 }}>RESUMEN</div>

    <div style={{
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    paddingBottom: 18, borderBottom: '1px solid var(--line)', marginBottom: 18
  }}>
      <div>
        <div className="bs-display" style={{ fontSize: 22, fontWeight: 700 }}>BLACKSTOCK {plan}</div>
        <div style={{ color: 'var(--fg-3)', fontSize: 13, marginTop: 2 }}>
          Facturación mensual · hasta {planMap[plan].max} cuenta{planMap[plan].max > 1 ? 's' : ''}
        </div>
      </div>
      <div className="bs-num" style={{ fontSize: 24, fontWeight: 700 }}>{price}€</div>
    </div>

    {/* Whats included */}
    <div style={{ marginBottom: 18 }}>
      <div className="bs-eyebrow" style={{ marginBottom: 10 }}>INCLUIDO</div>
      {[
    'Bot de mercado ilimitado',
    'IA negociadora',
    'Multicuenta unificada',
    'Restocks automáticos',
    'Academia + comunidad',
    'Soporte prioritario'].
    map((f, i) =>
    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '5px 0', fontSize: 13, color: 'var(--fg-2)' }}>
          <svg width="12" height="12" viewBox="0 0 24 24"><path d="M5 12l5 5L20 7" stroke="var(--acid)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" fill="none" /></svg>
          {f}
        </div>
    )}
    </div>

    <div style={{ borderTop: '1px solid var(--line)', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--fg-2)' }}>
        <span>Subtotal</span><span className="bs-num">{price}€</span>
      </div>
      {couponApplied &&
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--acid)' }}>
          <span>Descuento (20%)</span><span className="bs-num">−{discount}€</span>
        </div>
    }
      <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      marginTop: 10, paddingTop: 16, borderTop: '1px solid var(--line)'
    }}>
        <span className="bs-display" style={{ fontSize: 18, fontWeight: 700 }}>TOTAL HOY</span>
        <span className="bs-num" style={{ fontSize: 36, fontWeight: 800, color: 'var(--acid)', letterSpacing: '-0.03em' }}>{total}€</span>
      </div>
      <div style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)', textAlign: 'right', letterSpacing: '0.04em' }}>
        Renovación mensual · cancelas cuando quieras
      </div>
    </div>

    <div style={{
    marginTop: 20, padding: 14,
    background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 10,
    display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--fg-3)'
  }}>
      <span>🛡</span>
      <span>Pago seguro con Stripe. Sin permanencia.</span>
    </div>
  </div>;


Object.assign(window, { CheckoutPage, Step1Plan, Step2Account, Step3Payment, OrderSummary });