// MobileCheckout.jsx — full-screen mobile checkout, single-column stacked layout
const MobileCheckout = ({ 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',
    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);
  const [showSummary, setShowSummary] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setStep(0); setOrderId(null); setProcessLog([]); setShowSummary(false);
      setForm((f) => ({
        ...f,
        email: user?.email || f.email,
        name:  user?.name || f.name,
        line1: user?.shipping?.line1 || f.line1,
        line2: user?.shipping?.line2 || f.line2,
        city:  user?.shipping?.city || f.city,
        state: user?.shipping?.state || f.state,
        zip:   user?.shipping?.zip || f.zip,
        country: user?.shipping?.country || f.country,
      }));
      setErrs({});
    }
  }, [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 = ['ID', 'ADDR', 'PAY', 'EXEC'];

  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();
  };

  const execute = () => {
    setProcessing(true);
    setStep(3);
    const lines = [
      { t: 200,  text: 'validating cart ............. [ OK ]' },
      { t: 500,  text: 'computing tax ............... [ OK ]' },
      { t: 800,  text: 'reserving inventory ......... [ OK ]' },
      { t: 1200, text: 'tokenizing card ............. [ OK ]' },
      { t: 1700, text: 'creating 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 ............. [ OK ]' },
    ];
    setProcessLog([]);
    lines.forEach((l) => setTimeout(() => setProcessLog((p) => [...p, l]), l.t));
    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);
  };

  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;
  };

  const MckField = ({ label, value, onChange, type, placeholder, error, autoFocus, inputMode }) => (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        fontSize: 10, letterSpacing: '0.2em', fontWeight: 700, marginBottom: 6,
        color: error ? '#FF3344' : '#E0E0E0',
      }}>
        {'>'} {label}{error && <span style={{ color: '#FF3344', marginLeft: 8, fontSize: 9 }}>· {error}</span>}
      </div>
      <input
        type={type === 'password' ? 'password' : 'text'}
        inputMode={inputMode}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        autoFocus={autoFocus}
        autoComplete="off"
        maxLength={500}
        style={{
          width: '100%', background: '#000',
          border: '1px solid ' + (error ? '#FF3344' : 'rgba(255,255,255,0.28)'),
          color: '#FFF', fontFamily: 'inherit', fontSize: 16, padding: '14px 13px',
          borderRadius: 2, minHeight: 48,
        }}
        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>
  );

  return (
    <div style={{
      position: 'fixed', inset: 0, background: '#0A0A0A', zIndex: 120,
      fontFamily: "'JetBrains Mono', monospace",
      display: 'flex', flexDirection: 'column',
    }}>
      {/* HEADER */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, padding: '12px 16px',
        borderBottom: '1px solid rgba(255,255,255,0.15)', background: '#000',
        minHeight: 48, flexShrink: 0,
      }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#FF3344' }} />
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#FFD23F' }} />
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#00FF41' }} />
        <span style={{ marginLeft: 8, fontSize: 11, color: '#BFBFBF', letterSpacing: '0.1em', flex: 1 }}>
          ./checkout
        </span>
        <span style={{ fontSize: 9, color: '#6E6E6E', letterSpacing: '0.15em' }}>TLS 1.3</span>
        <button onClick={onClose} style={{
          background: 'transparent', border: '1px solid rgba(255,255,255,0.2)',
          color: '#B8B8B8', padding: '8px 14px', fontFamily: 'inherit',
          fontSize: 11, letterSpacing: '0.12em', cursor: 'pointer', minHeight: 40, minWidth: 40,
        }}>[x]</button>
      </div>

      {/* STEP INDICATOR */}
      <div style={{
        display: 'flex', gap: 3, padding: '10px 16px', flexShrink: 0,
        borderBottom: '1px solid rgba(255,255,255,0.08)',
      }}>
        {steps.map((s, i) => (
          <div key={s} style={{
            flex: 1, padding: '7px 0', textAlign: 'center', fontSize: 10, letterSpacing: '0.15em',
            color: i === step ? '#000' : i < step ? '#00FF41' : '#6E6E6E',
            background: i === step ? '#00FF41' : 'transparent',
            border: '1px solid ' + (i <= step ? '#00FF41' : 'rgba(255,255,255,0.15)'),
            fontWeight: i === step ? 800 : 600,
          }}>
            {s}
          </div>
        ))}
      </div>

      {/* SCROLLABLE BODY */}
      <div style={{ flex: 1, overflow: 'auto', padding: 16 }}>

        {/* COLLAPSIBLE ORDER SUMMARY */}
        {step < 3 && (
          <div style={{
            marginBottom: 20, border: '1px solid rgba(255,255,255,0.15)',
            background: '#000',
          }}>
            <button
              onClick={() => setShowSummary(!showSummary)}
              style={{
                width: '100%', display: 'flex', justifyContent: 'space-between',
                alignItems: 'center', padding: '12px 14px', background: 'transparent',
                border: 'none', color: '#FFF', fontFamily: 'inherit', cursor: 'pointer',
                minHeight: 44,
              }}
            >
              <span style={{ fontSize: 10, letterSpacing: '0.2em', color: '#BFBFBF', fontWeight: 700 }}>
                // ORDER · {items.length} item{items.length !== 1 ? 's' : ''}
              </span>
              <span style={{ fontSize: 14, fontWeight: 800, color: '#00FF41' }}>
                ${total.toFixed(2)} {showSummary ? '▲' : '▼'}
              </span>
            </button>
            {showSummary && (
              <div style={{ padding: '0 14px 14px', borderTop: '1px solid rgba(255,255,255,0.08)' }}>
                {items.map((it, i) => (
                  <div key={i} style={{
                    display: 'flex', justifyContent: 'space-between', padding: '8px 0',
                    borderBottom: '1px dashed rgba(255,255,255,0.1)', fontSize: 12,
                  }}>
                    <span style={{ color: '#FFF', flex: 1 }}>
                      <span style={{ color: it.p.accent }}>{'>'}</span> {it.p.name}
                      <span style={{ color: '#6E6E6E', fontSize: 10, marginLeft: 6 }}>x{it.qty}</span>
                    </span>
                    <span style={{ color: '#FFF', fontWeight: 700, flexShrink: 0 }}>${it.p.price * it.qty}</span>
                  </div>
                ))}
                <div style={{ paddingTop: 8, fontSize: 11, letterSpacing: '0.15em' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', color: '#9A9A9A' }}>
                    <span>SUBTOTAL</span><span style={{ color: '#FFF' }}>${subtotal}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', color: '#9A9A9A' }}>
                    <span>SHIPPING</span><span style={{ color: '#FFF' }}>{shippingCost === 0 ? 'FREE' : '$' + shippingCost}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', color: '#9A9A9A' }}>
                    <span>TAX</span><span style={{ color: '#FFF' }}>${tax.toFixed(2)}</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* STEP 0: IDENTIFY */}
        {step === 0 && (
          <div>
            <div style={{ fontSize: 12, color: '#00FF41', letterSpacing: '0.15em', marginBottom: 16 }}>{'>'} who_am_i ?</div>
            <MckField label="EMAIL" value={form.email} onChange={(v) => set('email', v)}
              placeholder="operator@target.coffee" error={errs.email} autoFocus inputMode="email" />
            <MckField label="NAME" value={form.name} onChange={(v) => set('name', v)}
              placeholder="full name for shipping" error={errs.name} />
            {!user && (
              <div style={{
                marginTop: 12, padding: '12px 14px',
                border: '1px dashed rgba(255,255,255,0.25)',
                fontSize: 11, color: '#9A9A9A', lineHeight: 1.8,
              }}>
                // already have an account?<br/>
                // <span style={{ color: '#00FF41' }}>./login</span> first to use saved info.
              </div>
            )}
          </div>
        )}

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

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

        {/* STEP 2: PAYMENT */}
        {step === 2 && (
          <div>
            <div style={{ fontSize: 12, color: '#00FF41', letterSpacing: '0.15em', marginBottom: 16 }}>{'>'} authorize_payment</div>
            <MckField label="CARD NUMBER" value={form.card}
              onChange={(v) => set('card', formatCard(v))}
              placeholder="4242 4242 4242 4242" error={errs.card} inputMode="numeric" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <MckField label="EXP (MM/YY)" value={form.exp}
                onChange={(v) => set('exp', formatExp(v))}
                placeholder="12 / 28" error={errs.exp} inputMode="numeric" />
              <MckField label="CVC" value={form.cvc}
                onChange={(v) => set('cvc', v.replace(/\D/g,'').slice(0,4))}
                placeholder="000" error={errs.cvc} type="password" inputMode="numeric" />
            </div>
            <label style={{
              display: 'flex', alignItems: 'center', gap: 10, marginTop: 4,
              cursor: 'pointer', minHeight: 44,
            }}>
              <input type="checkbox" checked={form.saveCard}
                onChange={(e) => set('saveCard', e.target.checked)}
                style={{ accentColor: '#00FF41', width: 18, height: 18 }} />
              <span style={{ fontSize: 11, color: '#9A9A9A' }}>save card (tokenized · never plaintext)</span>
            </label>
            <div style={{
              marginTop: 18, padding: '12px 14px',
              border: '1px dashed rgba(255,255,255,0.25)',
              fontSize: 10, color: '#6E6E6E', lineHeight: 1.8,
            }}>
              // payments via stripe.js<br/>
              // card data never touches our servers<br/>
              // pci-dss scope: zero
            </div>
          </div>
        )}

        {/* STEP 3: EXECUTE / CONFIRM */}
        {step === 3 && (
          <div>
            {processing || !orderId ? (
              <div style={{ color: '#00FF41', fontSize: 12, lineHeight: 2, letterSpacing: '0.03em' }}>
                <div style={{ marginBottom: 4 }}>$ ./execute --commit</div>
                {processLog.map((l, i) => (
                  <div key={i} style={{ fontSize: 11 }}>&nbsp;&nbsp;{l.text}</div>
                ))}
                {processLog.length < 10 && (
                  <div style={{ marginTop: 10, color: '#9A9A9A', fontSize: 11 }}>
                    // processing<span style={{ animation: 'mckBlink 1s steps(2) infinite', marginLeft: 4 }}>█</span>
                  </div>
                )}
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: '24px 0' }}>
                <div style={{ fontSize: 10, letterSpacing: '0.2em', color: '#9A9A9A', marginBottom: 10 }}>// ORDER CONFIRMED</div>
                <div style={{
                  display: 'inline-block', background: '#00FF41', color: '#000',
                  padding: '10px 20px', fontSize: 18, fontWeight: 800, letterSpacing: '0.25em',
                  boxShadow: '0 0 24px rgba(0,255,65,0.6)',
                  animation: 'mckFlash 160ms steps(2) 5',
                }}>[ ACCESS GRANTED ]</div>
                <div style={{ marginTop: 24, fontSize: 13, color: '#E0E0E0', lineHeight: 2 }}>
                  order <span style={{ color: '#00FF41', fontWeight: 800 }}>{orderId}</span><br/>
                  queued for fulfillment.<br/>
                  receipt → <span style={{ color: '#00E5FF' }}>{form.email}</span><br/>
                  <span style={{ fontSize: 11, color: '#6E6E6E' }}>roasted-to-order · ships 2-3 days</span>
                </div>
                <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 10, padding: '0 16px' }}>
                  <button onClick={() => onComplete(orderId)} style={{
                    width: '100%', background: '#00FF41', color: '#000', border: '1px solid #00FF41',
                    padding: '14px', fontFamily: 'inherit', fontWeight: 800, fontSize: 13,
                    letterSpacing: '0.18em', cursor: 'pointer', borderRadius: 2, minHeight: 48,
                  }}>{'>'} ./view-order</button>
                  <button onClick={onClose} style={{
                    width: '100%', background: 'transparent', color: '#9A9A9A',
                    border: '1px solid rgba(255,255,255,0.2)',
                    padding: '14px', fontFamily: 'inherit', fontWeight: 700, fontSize: 13,
                    letterSpacing: '0.18em', cursor: 'pointer', borderRadius: 2, minHeight: 48,
                  }}>./keep-shopping</button>
                </div>
                <div style={{ marginTop: 24, fontSize: 9, color: '#4A4A4A', letterSpacing: '0.15em' }}>
                  // drink responsibly. pwn responsibly.
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* BOTTOM NAV BUTTONS — pinned above keyboard */}
      {step < 3 && (
        <div style={{
          padding: '12px 16px', borderTop: '1px solid rgba(255,255,255,0.15)',
          background: '#0A0A0A', flexShrink: 0,
          display: 'flex', gap: 10,
        }}>
          {step > 0 ? (
            <button onClick={() => setStep(step - 1)} style={{
              background: 'transparent', color: '#9A9A9A',
              border: '1px solid rgba(255,255,255,0.2)',
              padding: '14px 16px', fontFamily: 'inherit', fontSize: 12,
              letterSpacing: '0.15em', fontWeight: 700, cursor: 'pointer',
              borderRadius: 2, minHeight: 48,
            }}>← BACK</button>
          ) : (
            <button onClick={onClose} style={{
              background: 'transparent', color: '#9A9A9A',
              border: '1px solid rgba(255,255,255,0.2)',
              padding: '14px 16px', fontFamily: 'inherit', fontSize: 12,
              letterSpacing: '0.15em', fontWeight: 700, cursor: 'pointer',
              borderRadius: 2, minHeight: 48,
            }}>./abort</button>
          )}
          <button onClick={advance} style={{
            flex: 1, background: '#00FF41', color: '#000', border: '1px solid #00FF41',
            padding: '14px', fontFamily: 'inherit', fontWeight: 800, fontSize: 13,
            letterSpacing: '0.18em', cursor: 'pointer', borderRadius: 2, minHeight: 48,
          }}>
            {step < 2 ? '> NEXT' : '> EXECUTE'}
          </button>
        </div>
      )}

      <style>{`
        @keyframes mckBlink { to { opacity: 0; } }
        @keyframes mckFlash { 0%, 100% { opacity: 1; } 50% { opacity: 0.2; } }
      `}</style>
    </div>
  );
};

window.MobileCheckout = MobileCheckout;
