// Checkout.jsx — multi-step terminal checkout
// SECURITY: client-side validation is convenience only. Server MUST re-validate everything.
// Payment is mock — in production this hands off to Stripe Elements / Shopify Payments,
// which means card data NEVER touches our servers (PCI scope = 0).

const Checkout = ({ open, items, user, onClose, onComplete }) => {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    email: user?.email || '',
    name:  user?.name || '',
    line1: user?.shipping?.line1 || '',
    line2: user?.shipping?.line2 || '',
    city:  user?.shipping?.city || '',
    state: user?.shipping?.state || '',
    zip:   user?.shipping?.zip || '',
    country: user?.shipping?.country || 'US',
    shipping: 'STANDARD', // STANDARD | EXPRESS | PICKUP
    card: '',
    exp: '',
    cvc: '',
    saveCard: false,
  });
  const [errs, setErrs] = React.useState({});
  const [processing, setProcessing] = React.useState(false);
  const [processLog, setProcessLog] = React.useState([]);
  const [orderId, setOrderId] = React.useState(null);

  React.useEffect(() => { if (open) { setStep(0); setOrderId(null); setProcessLog([]); } }, [open]);
  // Lock body scroll while open
  React.useEffect(() => {
    if (open) document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  if (!open) return null;

  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setErrs((e) => ({ ...e, [k]: null })); };

  const subtotal = items.reduce((s, i) => s + i.p.price * i.qty, 0);
  const shippingCost = form.shipping === 'EXPRESS' ? 12 : form.shipping === 'PICKUP' ? 0 : 5;
  const tax = Math.round(subtotal * 0.08875 * 100) / 100;
  const total = subtotal + shippingCost + tax;
  const steps = ['IDENTIFY', 'TARGET', 'EXECUTE', 'CONFIRM'];

  // Per-step validation
  const validate = (n) => {
    const next = {};
    if (n === 0) {
      if (!form.email.includes('@')) next.email = 'invalid email';
      if (!form.name.trim()) next.name = 'required';
    }
    if (n === 1) {
      if (!form.line1.trim()) next.line1 = 'required';
      if (!form.city.trim()) next.city = 'required';
      if (!form.state.trim()) next.state = 'required';
      if (!form.zip.match(/^[A-Za-z0-9 \-]{3,12}$/)) next.zip = 'invalid postal code';
    }
    if (n === 2) {
      if (!form.card.replace(/\s/g,'').match(/^\d{12,19}$/)) next.card = 'invalid card number';
      if (!form.exp.match(/^\d{2}\s?\/\s?\d{2}$/)) next.exp = 'MM/YY';
      if (!form.cvc.match(/^\d{3,4}$/)) next.cvc = 'invalid CVC';
    }
    setErrs(next);
    return Object.keys(next).length === 0;
  };

  const advance = () => {
    if (!validate(step)) return;
    if (step < 2) setStep(step + 1);
    else execute();
  };

  // The "execute transaction" path — animated log of Shopify call.
  // In production: POST to /api/checkout → Shopify Cart.checkoutCreate mutation → Stripe confirmCardPayment.
  const execute = () => {
    setProcessing(true);
    setStep(3);
    const lines = [
      { t: 200,  text: 'validating cart line items ............ [ OK ]' },
      { t: 500,  text: 'computing tax (jurisdiction: NY) ...... [ OK ]' },
      { t: 800,  text: 'reserving inventory ................... [ OK ]' },
      { t: 1200, text: 'tokenizing card (stripe.js) ........... [ OK ]' },
      { t: 1700, text: 'creating shopify checkout ............. [ OK ]' },
      { t: 2100, text: 'authorizing payment ................... [ OK ]' },
      { t: 2500, text: 'capturing funds ....................... [ OK ]' },
      { t: 2900, text: 'creating order #........................[ OK ]' },
      { t: 3300, text: 'queueing fulfillment .................. [ OK ]' },
      { t: 3700, text: 'sending receipt to ' + (form.email || 'inbox') + ' [ OK ]' },
    ];
    setProcessLog([]);
    lines.forEach((l) => setTimeout(() => setProcessLog((p) => [...p, l]), l.t));

    // Finalize: generate order ID, fire onComplete after log finishes
    setTimeout(() => {
      const id = Math.floor(Math.random() * 9999).toString().padStart(4, '0');
      const orderNumber = '#' + Math.random().toString(16).slice(2, 6).toUpperCase() + '-' + id;
      setOrderId(orderNumber);
      setProcessing(false);
    }, 4100);
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.92)', zIndex: 110, padding: 32, overflow: 'auto' }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 920, margin: '0 auto', background: '#0A0A0A', border: '1px solid #00FF41', padding: 0 }}>
        {/* terminal chrome */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 18px', borderBottom: '1px solid rgba(255,255,255,0.22)', background: '#000' }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#FF3344' }}></span>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#FFD23F' }}></span>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#00FF41' }}></span>
          <span style={{ marginLeft: 14, fontSize: 12, color: '#BFBFBF', letterSpacing: '0.12em' }}>operator@brew-co — ./checkout — secure</span>
          <span style={{ marginLeft: 'auto', fontSize: 11, color: '#9A9A9A', letterSpacing: '0.18em' }}>TLS 1.3 · PCI-DSS</span>
          <button onClick={onClose} style={{ marginLeft: 12, background: 'transparent', border: '1px solid rgba(255,255,255,0.28)', color: '#B8B8B8', cursor: 'pointer', fontSize: 11, padding: '3px 8px', letterSpacing: '0.15em', fontFamily: 'inherit' }}>[ ESC ]</button>
        </div>

        <div style={{ padding: 28 }}>
          {/* Step indicator */}
          <div style={{ display: 'flex', gap: 4, marginBottom: 24 }}>
            {steps.map((s, i) => (
              <div key={s} style={{
                flex: 1, padding: '8px 0', textAlign: 'center', fontSize: 10, letterSpacing: '0.18em',
                color: i === step ? '#000' : i < step ? '#00FF41' : '#9A9A9A',
                background: i === step ? '#00FF41' : 'transparent',
                border: `1px solid ${i <= step ? '#00FF41' : 'rgba(255,255,255,0.28)'}`,
                fontWeight: i === step ? 800 : 600,
              }}>
                [{i+1}] {s}
              </div>
            ))}
          </div>

          {/* Order summary always visible on right (collapsed on smaller; here single col) */}
          <div style={{ display: 'grid', gridTemplateColumns: step === 3 ? '1fr' : '1fr 280px', gap: 28 }}>
            {/* LEFT: step body */}
            <div>
              {step === 0 && (
                <div>
                  <div style={{ fontSize: 12, color: '#00FF41', letterSpacing: '0.18em', marginBottom: 14 }}>{'>'} who_am_i ?</div>
                  <CkField label="EMAIL" value={form.email} onChange={(v) => set('email', v)} type="email" placeholder="operator@target.coffee" error={errs.email} autoFocus />
                  <CkField label="NAME" value={form.name} onChange={(v) => set('name', v)} placeholder="full name for shipping label" error={errs.name} />
                  {!user && (
                    <div style={{ marginTop: 18, padding: '10px 14px', border: '1px dashed rgba(255,255,255,0.32)', fontSize: 11, color: '#BFBFBF', lineHeight: 1.7 }}>
                      // already have an account? <span style={{ color: '#00FF41', cursor: 'pointer' }}>./login</span> first to use saved address + payment.<br/>
                      // checking out as guest will auto-create an account.
                    </div>
                  )}
                </div>
              )}

              {step === 1 && (
                <div>
                  <div style={{ fontSize: 12, color: '#00FF41', letterSpacing: '0.18em', marginBottom: 14 }}>{'>'} target_address ?</div>
                  <CkField label="STREET" value={form.line1} onChange={(v) => set('line1', v)} placeholder="127 Localhost Lane" error={errs.line1} />
                  <CkField label="UNIT / APT (optional)" value={form.line2} onChange={(v) => set('line2', v)} placeholder="Unit 0x2A" />
                  <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 10 }}>
                    <CkField label="CITY" value={form.city} onChange={(v) => set('city', v)} placeholder="Brooklyn" error={errs.city} />
                    <CkField label="STATE" value={form.state} onChange={(v) => set('state', v)} placeholder="NY" error={errs.state} />
                    <CkField label="ZIP" value={form.zip} onChange={(v) => set('zip', v)} placeholder="11201" error={errs.zip} />
                  </div>

                  <div style={{ marginTop: 22, fontSize: 11, letterSpacing: '0.2em', color: '#E0E0E0', fontWeight: 700, marginBottom: 8 }}>{'>'} SHIPPING METHOD</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {[
                      { id: 'STANDARD', label: 'STANDARD', sub: '5-7 BUSINESS DAYS', price: 5 },
                      { id: 'EXPRESS',  label: 'EXPRESS',  sub: '2-3 BUSINESS DAYS', price: 12 },
                      { id: 'PICKUP',   label: 'LOCAL PICKUP', sub: 'BROOKLYN ROASTERY', price: 0 },
                    ].map((opt) => (
                      <label key={opt.id} style={{
                        display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
                        border: `1px solid ${form.shipping === opt.id ? '#00FF41' : 'rgba(255,255,255,0.22)'}`,
                        background: form.shipping === opt.id ? 'rgba(0,255,65,0.06)' : 'transparent',
                        cursor: 'pointer', borderRadius: 2,
                      }}>
                        <input type="radio" name="ship" checked={form.shipping === opt.id} onChange={() => set('shipping', opt.id)} style={{ accentColor: '#00FF41' }} />
                        <span style={{ fontSize: 12, color: '#FFF', letterSpacing: '0.15em', fontWeight: 700 }}>{opt.label}</span>
                        <span style={{ fontSize: 10, color: '#BFBFBF', letterSpacing: '0.18em' }}>// {opt.sub}</span>
                        <span style={{ marginLeft: 'auto', fontSize: 13, color: form.shipping === opt.id ? '#00FF41' : '#FFF', fontWeight: 700 }}>
                          {opt.price === 0 ? 'FREE' : `$${opt.price}`}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>
              )}

              {step === 2 && (
                <div>
                  <div style={{ fontSize: 12, color: '#00FF41', letterSpacing: '0.18em', marginBottom: 14 }}>{'>'} payload_secured. authorize.</div>
                  <CkField label="CARD NUMBER" value={form.card} onChange={(v) => set('card', formatCard(v))} placeholder="4242 4242 4242 4242" error={errs.card} />
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                    <CkField label="EXP (MM/YY)" value={form.exp} onChange={(v) => set('exp', formatExp(v))} placeholder="12 / 28" error={errs.exp} />
                    <CkField label="CVC" value={form.cvc} onChange={(v) => set('cvc', v.replace(/\D/g,'').slice(0,4))} placeholder="000" error={errs.cvc} type="password" />
                  </div>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4, cursor: 'pointer' }}>
                    <input type="checkbox" checked={form.saveCard} onChange={(e) => set('saveCard', e.target.checked)} style={{ accentColor: '#00FF41' }} />
                    <span style={{ fontSize: 11, color: '#BFBFBF', letterSpacing: '0.06em' }}>save card for next time (tokenized · never plaintext)</span>
                  </label>

                  <div style={{ marginTop: 18, padding: '10px 14px', border: '1px dashed rgba(255,255,255,0.32)', fontSize: 11, color: '#BFBFBF', lineHeight: 1.7 }}>
                    // payments processed by stripe.js — card data never touches operator brewing servers.<br/>
                    // pci-dss scope: zero. tls 1.3 + cert pinning.
                  </div>
                </div>
              )}

              {step === 3 && (
                <div>
                  {processing || !orderId ? (
                    <div style={{ color: '#00FF41', fontSize: 14, lineHeight: 1.9, letterSpacing: '0.04em' }}>
                      <div>$ ./execute-transaction --commit</div>
                      {processLog.map((l, i) => (
                        <div key={i}>&nbsp;&nbsp;{l.text}</div>
                      ))}
                      {processLog.length < 10 && (
                        <div style={{ marginTop: 10, color: '#BFBFBF' }}>// processing<span className="ck-cursor"></span></div>
                      )}
                    </div>
                  ) : (
                    <div style={{ textAlign: 'center', padding: '20px 0' }}>
                      <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#BFBFBF', marginBottom: 8 }}>// ORDER CONFIRMED</div>
                      <span className="ck-granted">[ ACCESS GRANTED ]</span>
                      <div style={{ marginTop: 22, fontSize: 14, color: '#E0E0E0', lineHeight: 1.8 }}>
                        order <span style={{ color: '#00FF41', fontWeight: 800 }}>{orderId}</span> queued for fulfillment.<br/>
                        receipt sent to <span style={{ color: '#00E5FF' }}>{form.email}</span>.<br/>
                        roasted-to-order. ships in 2-3 days.
                      </div>
                      <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center' }}>
                        <button onClick={() => onComplete(orderId)} style={{
                          background: '#00FF41', color: '#000', border: '1px solid #00FF41',
                          padding: '12px 22px', fontFamily: 'inherit', fontWeight: 800, fontSize: 12,
                          letterSpacing: '0.2em', cursor: 'pointer', borderRadius: 2,
                        }}>{'>'} ./view-order</button>
                        <button onClick={onClose} style={{
                          background: 'transparent', color: '#BFBFBF', border: '1px solid rgba(255,255,255,0.28)',
                          padding: '12px 22px', fontFamily: 'inherit', fontWeight: 700, fontSize: 12,
                          letterSpacing: '0.2em', cursor: 'pointer', borderRadius: 2,
                        }}>./keep-shopping</button>
                      </div>
                      <div style={{ marginTop: 28, fontSize: 10, color: '#7A7A7A', letterSpacing: '0.18em' }}>
                        // drink responsibly. pwn responsibly.
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* nav buttons */}
              {step < 3 && (
                <div style={{ display: 'flex', gap: 10, marginTop: 28, alignItems: 'center' }}>
                  {step > 0 ? (
                    <button onClick={() => setStep(step - 1)} style={{
                      background: 'transparent', color: '#BFBFBF', border: '1px solid rgba(255,255,255,0.28)',
                      padding: '12px 18px', fontFamily: 'inherit', fontSize: 12, letterSpacing: '0.18em',
                      fontWeight: 700, cursor: 'pointer', borderRadius: 2,
                    }}>← BACK</button>
                  ) : (
                    <button onClick={onClose} style={{
                      background: 'transparent', color: '#BFBFBF', border: '1px solid rgba(255,255,255,0.28)',
                      padding: '12px 18px', fontFamily: 'inherit', fontSize: 12, letterSpacing: '0.18em',
                      fontWeight: 700, cursor: 'pointer', borderRadius: 2,
                    }}>./abort</button>
                  )}
                  <button onClick={advance} style={{
                    marginLeft: 'auto', background: '#00FF41', color: '#000', border: '1px solid #00FF41',
                    padding: '12px 22px', fontFamily: 'inherit', fontWeight: 800, fontSize: 12,
                    letterSpacing: '0.2em', cursor: 'pointer', borderRadius: 2,
                  }}>
                    {step < 2 ? '> NEXT' : '> EXECUTE TRANSACTION'}
                  </button>
                </div>
              )}
            </div>

            {/* RIGHT: order summary */}
            {step < 3 && (
              <aside style={{ background: '#000', border: '1px solid rgba(255,255,255,0.22)', padding: 18, alignSelf: 'start' }}>
                <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#BFBFBF', fontWeight: 700, marginBottom: 12 }}>// ORDER</div>
                {items.map((it, i) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px dashed rgba(255,255,255,0.18)', fontSize: 12 }}>
                    <span style={{ color: '#FFFFFF', flex: 1, lineHeight: 1.4 }}>
                      <span style={{ color: it.p.accent }}>{'>'}</span> {it.p.name}<br/>
                      <span style={{ color: '#BFBFBF', fontSize: 10, letterSpacing: '0.1em' }}>× {it.qty} · {it.grind}</span>
                    </span>
                    <span style={{ color: '#FFFFFF', fontWeight: 700, marginLeft: 8 }}>${it.p.price * it.qty}</span>
                  </div>
                ))}
                <SumRow label="SUBTOTAL" value={`$${subtotal}`} />
                <SumRow label="SHIPPING" value={shippingCost === 0 ? 'FREE' : `$${shippingCost}`} />
                <SumRow label="TAX" value={`$${tax.toFixed(2)}`} />
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '12px 0 4px', borderTop: '1px solid rgba(255,255,255,0.28)', marginTop: 8, fontSize: 14 }}>
                  <span style={{ color: '#00FF41', letterSpacing: '0.18em', fontWeight: 800 }}>TOTAL</span>
                  <span style={{ color: '#FFFFFF', fontWeight: 800 }}>${total.toFixed(2)}</span>
                </div>
              </aside>
            )}
          </div>
        </div>
      </div>

      <style>{`
        .ck-cursor::after { content: '█'; animation: ckBlink 1s steps(2) infinite; margin-left: 4px; color: #00FF41; }
        @keyframes ckBlink { to { opacity: 0; } }
        .ck-granted {
          display: inline-block; background: #00FF41; color: #000;
          padding: 10px 22px; font-size: 22px; font-weight: 800; letter-spacing: 0.28em;
          box-shadow: 0 0 28px rgba(0,255,65,0.7);
          animation: ckGrantedFlash 160ms steps(2) 5;
        }
        @keyframes ckGrantedFlash { 0%, 100% { opacity: 1; } 50% { opacity: 0.2; } }
      `}</style>
    </div>
  );
};

const CkField = ({ label, value, onChange, type='text', placeholder, error, autoFocus }) => (
  <div style={{ marginBottom: 14 }}>
    <div style={{ fontSize: 10, letterSpacing: '0.22em', color: error ? '#FF3344' : '#E0E0E0', fontWeight: 700, marginBottom: 5 }}>
      {'>'} {label}{error && <span style={{ color: '#FF3344', marginLeft: 8, fontSize: 9 }}>· {error}</span>}
    </div>
    <input
      type={type === 'password' ? 'password' : 'text'}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      autoFocus={autoFocus}
      maxLength={500}
      style={{
        width: '100%', background: '#000', border: `1px solid ${error ? '#FF3344' : 'rgba(255,255,255,0.28)'}`,
        color: '#FFF', fontFamily: 'inherit', fontSize: 14, padding: '11px 13px', borderRadius: 2,
      }}
      onFocus={(e) => { if (!error) { e.target.style.borderColor = '#00FF41'; e.target.style.boxShadow = '0 0 0 1px #00FF41'; } }}
      onBlur={(e) => { if (!error) { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; e.target.style.boxShadow = 'none'; } }}
    />
  </div>
);

const SumRow = ({ label, value }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 11, letterSpacing: '0.18em' }}>
    <span style={{ color: '#BFBFBF' }}>{label}</span>
    <span style={{ color: '#FFFFFF' }}>{value}</span>
  </div>
);

// Format helpers — purely cosmetic
const formatCard = (v) => v.replace(/\D/g, '').slice(0, 19).replace(/(.{4})/g, '$1 ').trim();
const formatExp  = (v) => {
  const d = v.replace(/\D/g, '').slice(0, 4);
  return d.length > 2 ? `${d.slice(0,2)} / ${d.slice(2)}` : d;
};

window.Checkout = Checkout;
