/* Checkout (personal + corporate), Confirmation, Survey */
/* globals React, Icon, ProductImage */

const Checkout = ({ items, mode, region, onNav, setOrder }) => {
  const [step, setStep] = React.useState(1);
  const [formData, setFormData] = React.useState({
    name: 'Jordan Chen', email: 'jordan.chen@uber.com',
    address1: '1725 3rd Street', address2: 'Floor 4',
    city: 'San Francisco', zip: '94158', state: 'CA',
    card: '•••• •••• •••• 4242', exp: '09/28', cvc: '•••',
    costCenter: '4401 — Global Marketing',
    approver: 'amelia.ramirez@uber.com',
    fto: 'FTO-2026-0471',
  });
  const sub = items.reduce((s, i) => s + i.price * i.qty, 0);
  const tax = sub * 0.085;
  const ship = sub > 75 ? 0 : 9.5;
  const total = sub + tax + ship;

  const placeOrder = () => {
    const order = {
      number: 'UB-' + Math.floor(100000 + Math.random()*900000),
      po: 'PO-' + Math.floor(10000 + Math.random()*90000),
      fto: formData.fto,
      date: 'Apr 23, 2026',
      email: formData.email,
      total, items, mode,
      address: `${formData.address1}, ${formData.city}, ${formData.state} ${formData.zip}`,
    };
    setOrder(order);
    onNav('confirmation');
  };

  const accent = mode === 'corporate' ? '#000' : 'var(--u-eats)';

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '32px 32px 64px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <Icon name={mode === 'corporate' ? 'building' : 'user'} size={18}/>
        <span className="chip" style={{ background: mode === 'corporate' ? '#000' : 'var(--u-eats)', color: mode === 'corporate' ? '#fff' : '#000' }}>
          {mode === 'corporate' ? 'Corporate order · Coupa / Zip' : 'Personal order · Personal credit card'}
        </span>
      </div>
      <h1 className="u-h2" style={{ margin: 0, marginBottom: 32 }}>Checkout</h1>

      {/* Stepper */}
      <div style={{ display: 'flex', gap: 0, marginBottom: 40, borderBottom: '1px solid var(--u-line)' }}>
        {(mode === 'corporate'
          ? ['Shipping','Cost center & approval','Review & submit PR']
          : ['Shipping','Payment','Review']
        ).map((s, i) => (
          <div key={s} onClick={() => setStep(i+1)} style={{ padding: '14px 24px', cursor:'pointer', borderBottom: step === i+1 ? `2px solid ${mode==='corporate'?'#000':'var(--u-eats-dark)'}` : '2px solid transparent', marginBottom: -1, fontSize: 14, fontWeight: step === i+1 ? 600 : 500, color: step === i+1 ? '#000' : 'var(--u-text-2)' }}>
            <span style={{ marginRight: 10, display: 'inline-flex', alignItems:'center', justifyContent:'center', width: 22, height: 22, borderRadius: 11, background: step >= i+1 ? accent : '#EEE', color: step >= i+1 ? (mode==='corporate'?'#fff':'#000') : 'var(--u-text-3)', fontSize: 12, fontWeight: 700 }}>{i+1}</span>
            {s}
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48 }}>
        <div>
          {step === 1 && (
            <div>
              <h3 className="u-h4" style={{ marginTop: 0, marginBottom: 20 }}>Shipping address</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
                <div><label className="label">Full name</label><input className="input" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})}/></div>
                <div><label className="label">Email</label><input className="input" value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})}/></div>
              </div>
              <div style={{ marginBottom: 14 }}><label className="label">Address line 1</label><input className="input" value={formData.address1} onChange={e => setFormData({...formData, address1: e.target.value})}/></div>
              <div style={{ marginBottom: 14 }}><label className="label">Address line 2</label><input className="input" value={formData.address2} onChange={e => setFormData({...formData, address2: e.target.value})}/></div>
              <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 14, marginBottom: 14 }}>
                <div><label className="label">City</label><input className="input" value={formData.city} onChange={e => setFormData({...formData, city: e.target.value})}/></div>
                <div><label className="label">State</label><input className="input" value={formData.state} onChange={e => setFormData({...formData, state: e.target.value})}/></div>
                <div><label className="label">ZIP</label><input className="input" value={formData.zip} onChange={e => setFormData({...formData, zip: e.target.value})}/></div>
              </div>
              <div style={{ fontSize: 12, color: 'var(--u-text-2)', display:'flex', gap: 6, alignItems:'center', marginBottom: 20 }}>
                <Icon name="globe" size={14}/> Shipping from {region === 'US' ? 'Nashville, TN' : region === 'EMEA' ? 'Rotterdam, NL' : 'Singapore'} · {region}
              </div>
              <button onClick={() => setStep(2)} className="btn btn-primary btn-lg">Continue <Icon name="arrow-right" size={16}/></button>
            </div>
          )}

          {step === 2 && mode === 'personal' && (
            <div>
              <h3 className="u-h4" style={{ marginTop: 0, marginBottom: 20 }}>Payment</h3>
              <div style={{ padding: 14, background: 'var(--u-eats-tint)', borderRadius: 8, fontSize: 13, marginBottom: 20, display:'flex', gap: 10, alignItems:'center' }}>
                <Icon name="check" size={16} style={{ color: 'var(--u-eats-dark)' }}/>
                Employee discount (25%) applied automatically.
              </div>
              <div style={{ marginBottom: 14 }}><label className="label">Card number</label><input className="input" value={formData.card}/></div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 20 }}>
                <div><label className="label">Expiration</label><input className="input" value={formData.exp}/></div>
                <div><label className="label">CVC</label><input className="input" value={formData.cvc}/></div>
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => setStep(1)} className="btn btn-secondary btn-lg"><Icon name="chevron-left" size={16}/>Back</button>
                <button onClick={() => setStep(3)} className="btn btn-primary btn-lg">Review order</button>
              </div>
            </div>
          )}

          {step === 2 && mode === 'corporate' && (
            <div>
              <h3 className="u-h4" style={{ marginTop: 0, marginBottom: 8 }}>Cost center & approval</h3>
              <p style={{ margin: '0 0 20px', fontSize: 14, color: 'var(--u-text-2)' }}>This order routes through Coupa/Zip. A purchase requisition (PR) will be generated and sent to your approver.</p>
              <div style={{ marginBottom: 14 }}><label className="label">Cost center</label><input className="input" value={formData.costCenter}/></div>
              <div style={{ marginBottom: 14 }}><label className="label">Approver email</label><input className="input" value={formData.approver}/></div>
              <div style={{ marginBottom: 14 }}><label className="label">Finance-to-order reference (FTO)</label><input className="input" value={formData.fto}/></div>
              <div style={{ marginBottom: 14 }}><label className="label">PO notes (optional)</label><textarea className="input" rows={3} placeholder="Event, campaign, or team context for finance…"/></div>
              <div style={{ padding: 14, background: '#F6F6F6', borderRadius: 8, fontSize: 13, marginBottom: 20, display: 'grid', gridTemplateColumns: '20px 1fr', gap: 10, alignItems:'start' }}>
                <Icon name="doc" size={16} style={{ marginTop: 2 }}/>
                <div>
                  <div style={{ fontWeight: 600, marginBottom: 2 }}>Coupa/Zip routing</div>
                  <div style={{ color: 'var(--u-text-2)' }}>PR sent to {formData.approver.split('@')[0]} → auto-PO on approval → invoiced to {formData.costCenter.split(' — ')[0]}.</div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => setStep(1)} className="btn btn-secondary btn-lg"><Icon name="chevron-left" size={16}/>Back</button>
                <button onClick={() => setStep(3)} className="btn btn-primary btn-lg">Review & submit PR</button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <h3 className="u-h4" style={{ marginTop: 0, marginBottom: 20 }}>Review</h3>
              <div className="card" style={{ padding: 20, marginBottom: 14 }}>
                <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--u-text-3)', marginBottom: 8 }}>Ship to</div>
                <div style={{ fontSize: 14 }}>{formData.name} · {formData.email}</div>
                <div style={{ fontSize: 14, color: 'var(--u-text-2)' }}>{formData.address1}, {formData.address2}, {formData.city} {formData.state} {formData.zip}</div>
              </div>
              {mode === 'corporate' ? (
                <div className="card" style={{ padding: 20, marginBottom: 14 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--u-text-3)', marginBottom: 8 }}>Cost center & approval</div>
                  <div style={{ fontSize: 14 }}>{formData.costCenter}</div>
                  <div style={{ fontSize: 14, color: 'var(--u-text-2)' }}>Approver: {formData.approver} · FTO {formData.fto}</div>
                </div>
              ) : (
                <div className="card" style={{ padding: 20, marginBottom: 14 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--u-text-3)', marginBottom: 8 }}>Payment</div>
                  <div style={{ fontSize: 14, display:'flex', gap: 10, alignItems:'center' }}><Icon name="card" size={16}/>Visa {formData.card} · exp {formData.exp}</div>
                </div>
              )}
              <button onClick={placeOrder} className="btn btn-primary btn-lg btn-block" style={{ marginTop: 8 }}>
                {mode === 'corporate' ? 'Submit PR for approval' : `Place order · $${total.toFixed(2)}`}
              </button>
            </div>
          )}
        </div>

        <aside>
          <div style={{ background: '#F6F6F6', padding: 24, borderRadius: 12, position: 'sticky', top: 120 }}>
            <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 16 }}>Your order ({items.length})</div>
            {items.map((it, idx) => (
              <div key={idx} style={{ display: 'grid', gridTemplateColumns: '48px 1fr auto', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--u-line)', alignItems: 'center' }}>
                <div style={{ width: 48 }}><ProductImage product={it} showLabel={false}/></div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{it.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--u-text-2)' }}>{it.size && `${it.size} · `}Qty {it.qty}</div>
                </div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>${(it.price * it.qty).toFixed(2)}</div>
              </div>
            ))}
            <div style={{ paddingTop: 14 }}>
              {[
                { l: 'Subtotal', v: `$${sub.toFixed(2)}` },
                { l: 'Shipping', v: ship === 0 ? 'Free' : `$${ship.toFixed(2)}` },
                { l: 'Tax', v: `$${tax.toFixed(2)}` },
              ].map(r => (
                <div key={r.l} style={{ display:'flex', justifyContent:'space-between', fontSize: 13, padding: '4px 0' }}>
                  <span style={{ color:'var(--u-text-2)' }}>{r.l}</span><span>{r.v}</span>
                </div>
              ))}
              <div style={{ display:'flex', justifyContent:'space-between', fontSize: 16, fontWeight: 700, paddingTop: 10, borderTop: '1px solid var(--u-line)', marginTop: 10 }}>
                <span>Total</span><span>${total.toFixed(2)}</span>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
};
window.Checkout = Checkout;

// ——————— Confirmation ———————
const Confirmation = ({ order, mode, onNav }) => {
  if (!order) { onNav('landing'); return null; }
  return (
    <div style={{ maxWidth: 820, margin: '0 auto', padding: '64px 32px' }}>
      <div style={{ width: 56, height: 56, borderRadius: 28, background: 'var(--u-eats)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom: 24 }}>
        <Icon name="check" size={28} style={{ color: '#000' }}/>
      </div>
      <h1 className="u-h1" style={{ margin: 0, marginBottom: 12, fontSize: 'clamp(36px,4vw,56px)' }}>
        {mode === 'corporate' ? 'PR submitted.' : 'Thanks — your order is in.'}
      </h1>
      <p style={{ fontSize: 18, color: 'var(--u-text-2)', margin: 0, marginBottom: 32 }}>
        {mode === 'corporate'
          ? `Your purchase requisition has been routed to your approver. You'll receive a PO confirmation once approved (typically within 1 business day).`
          : `We've emailed a receipt to ${order.email}. Your kit is being prepared.`}
      </p>
      <div className="card" style={{ padding: 28, marginBottom: 24 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          {[
            { l: 'Order number', v: order.number },
            { l: 'PO number', v: order.po },
            { l: 'Finance-to-order ref', v: order.fto },
            { l: 'Date', v: order.date },
            { l: 'Requester', v: order.email },
            { l: 'Ship to', v: order.address },
          ].map(r => (
            <div key={r.l}>
              <div style={{ fontSize: 12, color: 'var(--u-text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>{r.l}</div>
              <div style={{ fontSize: 15, fontWeight: 500, fontFamily: r.l.includes('number') || r.l.includes('ref') ? 'ui-monospace, Menlo, monospace' : undefined }}>{r.v}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="card" style={{ padding: 28, marginBottom: 24 }}>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>What happens next</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {[
            { t: 'Brand Desk review', d: 'Your order items have already been approved. No action needed.', done: true },
            { t: mode === 'corporate' ? 'Coupa / Zip approval' : 'Card charged', d: mode === 'corporate' ? `Routed to approver.` : 'Your card will be charged when the order ships.', done: mode === 'personal' },
            { t: 'Shipping confirmation email', d: 'You\'ll get an email with tracking once your order ships (usually 2–3 days).', done: false },
            { t: 'Satisfaction survey', d: 'We\'ll send a 2-minute survey ~48 hours after delivery.', done: false },
          ].map((s, i) => (
            <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'start' }}>
              <div style={{ width: 22, height: 22, borderRadius: 11, background: s.done ? 'var(--u-eats)' : '#EEE', display:'flex', alignItems:'center', justifyContent:'center', marginTop: 1, flexShrink: 0 }}>
                {s.done ? <Icon name="check" size={12} style={{ color: '#000' }}/> : <span style={{ width: 6, height: 6, borderRadius: 3, background: '#999' }}/>}
              </div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{s.t}</div>
                <div style={{ fontSize: 13, color: 'var(--u-text-2)' }}>{s.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <button className="btn btn-primary" onClick={() => onNav('landing')}>Continue shopping</button>
        <button className="btn btn-secondary" onClick={() => onNav('survey')}>Preview post-delivery survey</button>
      </div>
    </div>
  );
};
window.Confirmation = Confirmation;

// ——————— Survey ———————
const Survey = ({ onNav }) => {
  const [nps, setNps] = React.useState(9);
  const [ratings, setRatings] = React.useState({ quality: 0, ship: 0, pkg: 0 });
  const [text, setText] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const Star = ({ value, onChange }) => (
    <div style={{ display: 'flex', gap: 4 }}>
      {[1,2,3,4,5].map(n => (
        <button key={n} onClick={() => onChange(n)} style={{ background: 'transparent', border: 0, padding: 4, cursor: 'pointer', color: n <= value ? '#000' : '#DADADA' }}>
          <Icon name="star" size={24} style={{ fill: n <= value ? '#000' : 'transparent' }}/>
        </button>
      ))}
    </div>
  );
  if (submitted) {
    return (
      <div style={{ maxWidth: 620, margin: '0 auto', padding: '120px 32px', textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: 28, background: 'var(--u-eats)', display:'flex', alignItems:'center', justifyContent:'center', margin: '0 auto 24px' }}>
          <Icon name="check" size={28} style={{ color: '#000' }}/>
        </div>
        <h1 className="u-h2" style={{ margin: 0, marginBottom: 12 }}>Thanks for the feedback.</h1>
        <p style={{ fontSize: 16, color: 'var(--u-text-2)' }}>We'll use it to keep improving the employee store.</p>
        <button className="btn btn-primary" onClick={() => onNav('landing')} style={{ marginTop: 20 }}>Back to store</button>
      </div>
    );
  }
  return (
    <div style={{ maxWidth: 620, margin: '0 auto', padding: '48px 32px 64px' }}>
      <div className="uppercase" style={{ color: 'var(--u-text-3)', marginBottom: 8 }}>Post-delivery · 48 hours</div>
      <h1 className="u-h2" style={{ margin: 0, marginBottom: 10 }}>How was your order?</h1>
      <p style={{ fontSize: 15, color: 'var(--u-text-2)', marginBottom: 32 }}>Order UB-482139 · 2 items · Delivered Apr 21</p>
      <div style={{ marginBottom: 32 }}>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>How likely are you to recommend the Uber employee store to a colleague?</div>
        <div style={{ display: 'flex', gap: 4 }}>
          {Array.from({ length: 11 }, (_, i) => (
            <button key={i} onClick={() => setNps(i)} style={{ flex: 1, padding: '10px 0', background: i === nps ? '#000' : '#F6F6F6', color: i === nps ? '#fff' : '#000', border: 0, borderRadius: 4, cursor: 'pointer', fontWeight: 600 }}>{i}</button>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--u-text-3)', marginTop: 6 }}>
          <span>Not at all likely</span><span>Extremely likely</span>
        </div>
      </div>
      {[
        { k: 'quality', l: 'Product quality' },
        { k: 'ship', l: 'Shipping speed' },
        { k: 'pkg', l: 'Packaging & unboxing' },
      ].map(r => (
        <div key={r.k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 0', borderBottom: '1px solid var(--u-line)' }}>
          <span style={{ fontSize: 15, fontWeight: 500 }}>{r.l}</span>
          <Star value={ratings[r.k]} onChange={v => setRatings({ ...ratings, [r.k]: v })}/>
        </div>
      ))}
      <div style={{ marginTop: 24 }}>
        <label className="label">Anything else? (optional)</label>
        <textarea className="input" rows={4} value={text} onChange={e => setText(e.target.value)} placeholder="Tell us what worked or didn't…"/>
      </div>
      <button onClick={() => setSubmitted(true)} className="btn btn-primary btn-lg" style={{ marginTop: 20 }}>Submit feedback</button>
    </div>
  );
};
window.Survey = Survey;
