// CHECKOUT PAGE — mobile ready
function CheckoutPage({ lang, cart, setCart, session, setPage, showToast }) {
  const settings = Store.getSettings();
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    name: session?.name || '', phone: '', address: '', city: 'Torres Vedras',
    notes: '', payMethod: 'mbway', mbwayPhone: ''
  });
  const [loading, setLoading] = React.useState(false);
  const [orderDone, setOrderDone] = React.useState(false);

  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const deliveryFee = subtotal >= settings.freeDeliveryOver ? 0 : settings.deliveryFee;
  const total = subtotal + deliveryFee;

  const t = lang === 'pt' ? {
    title: 'Finalizar Encomenda', s1: 'Entrega', s2: 'Pagamento',
    name: 'Nome completo', phone: 'Telefone', address: 'Morada', city: 'Cidade',
    notes: 'Notas (opcional)', next: 'Continuar', back: 'Voltar',
    pay: 'Confirmar Pagamento', mbway: 'MB Way', multibanco: 'Multibanco',
    mbwayNum: 'Número MB Way', confirm: 'Encomenda Confirmada!',
    confirmMsg: 'Receberá uma confirmação em breve. Obrigado!',
    backShop: 'Continuar a Comprar', viewOrders: 'Ver Encomendas',
    required: 'Preencha todos os campos obrigatórios',
    delivery: 'Entrega', free: 'Grátis', order: 'A sua encomenda'
  } : {
    title: 'Checkout', s1: 'Delivery', s2: 'Payment',
    name: 'Full name', phone: 'Phone', address: 'Address', city: 'City',
    notes: 'Notes (optional)', next: 'Continue', back: 'Back',
    pay: 'Confirm Payment', mbway: 'MB Way', multibanco: 'Multibanco',
    mbwayNum: 'MB Way number', confirm: 'Order Confirmed!',
    confirmMsg: 'You will receive a confirmation shortly. Thank you!',
    backShop: 'Continue Shopping', viewOrders: 'View Orders',
    required: 'Please fill in all required fields',
    delivery: 'Delivery', free: 'Free', order: 'Your order'
  };

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

  const handleConfirm = () => {
    setLoading(true);
    setTimeout(() => {
      const orders = Store.getOrders();
      Store.saveOrders([...orders, {
        id: Store.nextId(orders), userId: session.id, userName: form.name,
        phone: form.phone, address: `${form.address}, ${form.city}`,
        notes: form.notes, items: cart, subtotal, deliveryFee, total,
        payMethod: form.payMethod, status: 'pending',
        createdAt: new Date().toISOString()
      }]);
      setCart([]); Store.saveCart([]);
      setLoading(false); setOrderDone(true);
    }, 1600);
  };

  const lbl = { display: 'block', fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', marginBottom: 6 };
  const fld = { ...inputStyle, marginBottom: 14 };

  if (orderDone) return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20, padding: '90px 24px 40px', textAlign: 'center' }}>
      <div style={{ fontSize: 72 }}>🎉</div>
      <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 'clamp(24px,5vw,36px)' }}>{t.confirm}</h2>
      <p style={{ fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 16, maxWidth: 400 }}>{t.confirmMsg}</p>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
        <BtnPrimary onClick={() => setPage('shop')}>{t.backShop}</BtnPrimary>
        <BtnGhost onClick={() => setPage('account')}>{t.viewOrders}</BtnGhost>
      </div>
    </div>
  );

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70 }}>
      <div style={{ maxWidth: 900, margin: '0 auto', padding: 'clamp(24px,5vw,50px) clamp(16px,4vw,40px)' }}>
        <SectionTitle center={false}>{t.title}</SectionTitle>

        {/* Steps indicator */}
        <div className="checkout-steps" style={{ display: 'flex', alignItems: 'center', marginBottom: 40 }}>
          {[t.s1, t.s2].map((s, i) => (
            <React.Fragment key={s}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
                <div style={{ width: 34, height: 34, borderRadius: '50%', background: step > i+1 ? 'var(--gold)' : step === i+1 ? 'rgba(212,153,58,0.25)' : 'rgba(212,153,58,0.08)', border: `2px solid ${step >= i+1 ? 'var(--gold)' : 'var(--border)'}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold)', fontFamily: 'Lato, sans-serif', fontSize: 13, fontWeight: 700 }}>{step > i+1 ? '✓' : i+1}</div>
                <span style={{ fontFamily: 'Lato, sans-serif', fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase', color: step >= i+1 ? 'var(--gold)' : 'var(--dim)', whiteSpace: 'nowrap' }}>{s}</span>
              </div>
              {i < 1 && <div style={{ flex: 1, height: 1, background: step > i+1 ? 'var(--gold)' : 'var(--border)', margin: '0 10px', marginBottom: 22 }}></div>}
            </React.Fragment>
          ))}
        </div>

        <div className="checkout-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 28, alignItems: 'start' }}>
          <div>
            {/* Step 1 */}
            {step === 1 && (
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: 'clamp(20px,4vw,28px)' }}>
                <label style={lbl}>{t.name} *</label>
                <input style={fld} value={form.name} onChange={e => set('name', e.target.value)} />
                <label style={lbl}>{t.phone} *</label>
                <input style={fld} value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="+351 9xx xxx xxx" inputMode="tel" />
                <label style={lbl}>{t.address} *</label>
                <input style={fld} value={form.address} onChange={e => set('address', e.target.value)} />
                <label style={lbl}>{t.city}</label>
                <input style={fld} value={form.city} onChange={e => set('city', e.target.value)} />
                <label style={lbl}>{t.notes}</label>
                <textarea style={{ ...inputStyle, height: 80, resize: 'vertical', marginBottom: 20 }} value={form.notes} onChange={e => set('notes', e.target.value)} />
                <BtnPrimary onClick={() => {
                  if (!form.name || !form.phone || !form.address) { showToast(t.required, 'error'); return; }
                  setStep(2);
                }}>{t.next} →</BtnPrimary>
              </div>
            )}

            {/* Step 2 */}
            {step === 2 && (
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: 'clamp(20px,4vw,28px)' }}>
                <div style={{ display: 'flex', gap: 10, marginBottom: 22 }}>
                  {['mbway', 'multibanco'].map(m => (
                    <button key={m} onClick={() => set('payMethod', m)}
                      style={{ flex: 1, padding: '13px 10px', borderRadius: 6, cursor: 'pointer', fontFamily: 'Lato, sans-serif', fontSize: 13, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', border: `2px solid ${form.payMethod === m ? 'var(--gold)' : 'var(--border)'}`, background: form.payMethod === m ? 'rgba(212,153,58,0.15)' : 'transparent', color: form.payMethod === m ? 'var(--gold)' : 'var(--muted)', transition: 'all 0.2s', minHeight: 52 }}>
                      {m === 'mbway' ? '📱 MB Way' : '🏦 Multibanco'}
                    </button>
                  ))}
                </div>

                {form.payMethod === 'mbway' && (
                  <div>
                    <label style={lbl}>{t.mbwayNum}</label>
                    <input style={fld} value={form.mbwayPhone} onChange={e => set('mbwayPhone', e.target.value)} placeholder="+351 9xx xxx xxx" inputMode="tel" />
                    <div style={{ background: 'rgba(212,153,58,0.07)', border: '1px solid var(--border)', borderRadius: 6, padding: '14px', marginBottom: 16, fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 13, lineHeight: 1.6 }}>
                      {lang === 'pt' ? 'Após confirmar, receberá um pedido de pagamento MB Way no seu telemóvel.' : 'After confirming, you will receive an MB Way payment request on your phone.'}
                    </div>
                  </div>
                )}

                {form.payMethod === 'multibanco' && (
                  <div style={{ background: 'rgba(212,153,58,0.07)', border: '1px solid var(--border)', borderRadius: 8, padding: '20px', marginBottom: 20 }}>
                    <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 13, marginBottom: 14 }}>
                      {lang === 'pt' ? 'Dados para pagamento:' : 'Payment details:'}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                      {[['Entidade','12345'],['Referência','000 000 000'],['Montante',`${total.toFixed(2)}€`]].map(([k,v]) => (
                        <div key={k}>
                          <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--dim)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', marginBottom: 2 }}>{k}</div>
                          <div style={{ fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 18 }}>{v}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                  <BtnGhost onClick={() => setStep(1)}>← {t.back}</BtnGhost>
                  <BtnPrimary onClick={handleConfirm} disabled={loading}>
                    {loading ? (lang==='pt'?'A processar...':'Processing...') : t.pay}
                  </BtnPrimary>
                </div>
              </div>
            )}
          </div>

          {/* Order summary */}
          <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: '22px', position: 'sticky', top: 80 }}>
            <h3 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 17, margin: '0 0 16px' }}>{t.order}</h3>
            {cart.map(item => (
              <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontFamily: 'Lato, sans-serif', fontSize: 13 }}>
                <span style={{ color: 'var(--cream)' }}>{item.name} ×{item.qty}</span>
                <span style={{ color: 'var(--gold)', whiteSpace: 'nowrap', marginLeft: 8 }}>{(item.price*item.qty).toFixed(2)}€</span>
              </div>
            ))}
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12, marginTop: 8 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Lato, sans-serif', fontSize: 13, color: 'var(--muted)', marginBottom: 6 }}>
                <span>{t.delivery}</span>
                <span>{deliveryFee===0 ? t.free : `${deliveryFee.toFixed(2)}€`}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: "'Playfair Display', serif", fontSize: 20, color: 'var(--gold)', fontWeight: 700 }}>
                <span>Total</span><span>{total.toFixed(2)}€</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CheckoutPage });
