// RIFTR storefront — checkout: details + fulfillment, then TNG payment + receipt upload.
(() => {
const { Button, Input, Label, Card } = window.RIFTRDesignSystem_b64b32;

const FULFILLMENT = [
  { type: 'pickup',   location: 'Boards & Brew, Sunway', fee: 0,  sub: 'Self-collect' },
  { type: 'meetup',   location: 'Subang Jaya',           fee: 0,  sub: 'Meetup point' },
  { type: 'meetup',   location: 'Kota Kemuning',         fee: 0,  sub: 'Meetup point' },
  { type: 'delivery', location: 'Peninsular Malaysia',   fee: 10, sub: 'Courier · +RM10', needsAddress: true },
];

const TYPE_LABEL = { pickup: 'Pickup', meetup: 'COD meetup', delivery: 'Delivery' };

function Field({ children }) {
  return <div style={{ marginBottom: 14 }}>{children}</div>;
}

function Checkout({ cart, onBack, onClearCart }) {
  const RM = window.RIFTR_RM;
  const Ic = window.Ic;

  const [name, setName]   = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [sel, setSel]     = React.useState(null);
  const [address, setAddress] = React.useState('');

  const [stage, setStage] = React.useState('form'); // form → pay → done
  const [order, setOrder] = React.useState(null);
  const [busy, setBusy]   = React.useState(false);
  const [err, setErr]     = React.useState('');

  const [file, setFile]   = React.useState(null);
  const [upBusy, setUpBusy] = React.useState(false);
  const [upErr, setUpErr]   = React.useState('');

  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const subtotal = cart.reduce((a, b) => a + b.price * b.qty, 0);
  const fee = sel != null ? FULFILLMENT[sel].fee : 0;
  const total = subtotal + fee;

  async function placeOrder() {
    setErr('');
    if (!name.trim())  return setErr('Please enter your name.');
    if (!/^\S+@\S+\.\S+$/.test(email)) return setErr('Please enter a valid email.');
    if (!phone.trim()) return setErr('Please enter your phone number.');
    if (sel == null)   return setErr('Please choose a fulfillment option.');
    const opt = FULFILLMENT[sel];
    if (opt.needsAddress && !address.trim()) return setErr('Please enter your delivery address.');

    setBusy(true);
    try {
      const res = await fetch('/api/create_order.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name, email, phone,
          fulfillment_type: opt.type,
          fulfillment_location: opt.location,
          delivery_address: opt.needsAddress ? address : '',
          items: cart.map((c) => ({ id: c.id, qty: c.qty })),
        }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error || 'Could not place order.');
      setOrder(data);
      onClearCart();
      setStage('pay');
      window.scrollTo({ top: 0 });
    } catch (e) {
      setErr(e.message || 'Network error. Please try again.');
    } finally {
      setBusy(false);
    }
  }

  async function uploadReceipt() {
    setUpErr('');
    if (!file) return setUpErr('Please choose your receipt image first.');
    setUpBusy(true);
    try {
      const fd = new FormData();
      fd.append('order_id', order.order_id);
      fd.append('receipt', file);
      const res = await fetch('/api/upload_receipt.php', { method: 'POST', body: fd });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error || 'Upload failed.');
      setStage('done');
      window.scrollTo({ top: 0 });
    } catch (e) {
      setUpErr(e.message || 'Network error. Please try again.');
    } finally {
      setUpBusy(false);
    }
  }

  // ---------- DONE ----------
  if (stage === 'done') {
    return (
      <section className="product-page-pad" style={{ maxWidth: 720, margin: '0 auto', padding: '48px 28px 80px', textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}><Ic n="check" s={26} /></div>
        <h1 style={{ fontFamily: 'var(--font-display)', margin: 0, fontSize: 34, fontWeight: 700, textTransform: 'uppercase' }}>Receipt received</h1>
        <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginTop: 14 }}>
          We're verifying your payment now. You'll get an email once it's confirmed — usually within a few hours.
        </p>
        <div style={{ display: 'inline-block', marginTop: 22, padding: '14px 22px', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-sm)' }}>
          <Label style={{ marginBottom: 6 }}>Your order ID</Label>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 700, letterSpacing: '.04em' }}>{order.order_id}</div>
        </div>
        <p style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)', marginTop: 16 }}>
          Save this ID to track your order anytime.
        </p>
        <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <Button variant="primary" onClick={() => { window.location.href = '/track/?id=' + encodeURIComponent(order.order_id); }}>Track my order</Button>
          <Button variant="secondary" onClick={onBack}>Back to shop</Button>
        </div>
      </section>
    );
  }

  // ---------- PAY ----------
  if (stage === 'pay') {
    return (
      <section className="product-page-pad" style={{ maxWidth: 560, margin: '0 auto', padding: '24px 28px 80px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', margin: '0 0 6px', fontSize: 30, fontWeight: 700, textTransform: 'uppercase' }}>Pay with TNG</h1>
        <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 8 }}>
          Scan the QR with Touch ’n Go eWallet and pay the exact total. Then upload your receipt below.
        </p>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '12px 0', borderTop: '1px solid var(--border-strong)', borderBottom: '1px solid var(--border-strong)', margin: '8px 0 20px' }}>
          <Label>Amount to pay</Label>
          <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 22, color: 'var(--accent)' }}>{RM(order.total)}</span>
        </div>

        <div className="ticks" style={{ position: 'relative', maxWidth: 320, margin: '0 auto 8px', border: '1px solid var(--border-hairline)', borderRadius: 'var(--radius-md)', overflow: 'hidden', background: 'var(--surface-card)' }}>
          <img src="/TNG/TNG.png" alt="TNG QR" style={{ width: '100%', display: 'block' }} />
        </div>
        <p style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', letterSpacing: '.08em', marginBottom: 28 }}>
          ORDER {order.order_id}
        </p>

        <Label style={{ marginBottom: 10 }}>Upload payment receipt</Label>
        <label style={{ display: 'block', border: '1px dashed var(--border-strong)', borderRadius: 'var(--radius-sm)', padding: '22px 16px', textAlign: 'center', cursor: 'pointer', background: 'var(--bg-raised)' }}>
          <input type="file" accept="image/png,image/jpeg,image/webp" style={{ display: 'none' }}
            onChange={(e) => { setFile(e.target.files[0] || null); setUpErr(''); }} />
          <span style={{ display: 'inline-flex', color: 'var(--accent)', marginBottom: 6 }}><Ic n="upload" s={20} /></span>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: file ? 'var(--text-primary)' : 'var(--text-muted)' }}>
            {file ? file.name : 'Tap to choose a JPG / PNG screenshot'}
          </div>
        </label>

        {upErr && <p style={{ color: 'var(--signal-danger)', fontSize: 13, marginTop: 12 }}>{upErr}</p>}

        <Button variant="primary" notch style={{ width: '100%', marginTop: 18 }} disabled={upBusy} onClick={uploadReceipt}>
          {upBusy ? 'Uploading…' : 'Submit receipt'}
        </Button>
        <p style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', textAlign: 'center', marginTop: 14 }}>
          Save your order ID — {order.order_id}
        </p>
      </section>
    );
  }

  // ---------- FORM ----------
  return (
    <section className="product-page-pad" style={{ maxWidth: 1100, margin: '0 auto', padding: '24px 28px 80px' }}>
      <Button variant="ghost" onClick={onBack} iconLeft={<Ic n="arrow-left" />} style={{ padding: '8px 0', marginBottom: 14 }}>Back</Button>
      <h1 style={{ fontFamily: 'var(--font-display)', margin: '0 0 24px', fontSize: 34, fontWeight: 700, textTransform: 'uppercase' }}>Checkout</h1>

      {cart.length === 0 ? (
        <p style={{ fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>Your cart is empty.</p>
      ) : (
      <div className="product-page-grid" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 44, alignItems: 'start' }}>
        {/* LEFT — details */}
        <div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 14 }}>Your details</h2>
          <Field><Input label="Full name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" /></Field>
          <Field><Input label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" /></Field>
          <Field><Input label="Phone" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="01X-XXXXXXX" /></Field>

          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em', margin: '28px 0 14px' }}>Fulfillment</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {FULFILLMENT.map((o, i) => {
              const on = sel === i;
              return (
                <button key={i} type="button" onClick={() => setSel(i)}
                  style={{
                    textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
                    padding: '14px 16px', background: on ? 'var(--accent-soft)' : 'var(--bg-raised)',
                    border: '1px solid', borderColor: on ? 'var(--accent)' : 'var(--border-strong)',
                    borderRadius: 'var(--radius-sm)', transition: 'border-color .12s, background .12s',
                  }}>
                  <span style={{ width: 16, height: 16, borderRadius: '50%', flex: 'none', border: '2px solid', borderColor: on ? 'var(--accent)' : 'var(--border-strong)', background: on ? 'var(--accent)' : 'transparent', boxShadow: on ? 'inset 0 0 0 2px var(--bg-raised)' : 'none' }} />
                  <span style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, textTransform: 'uppercase' }}>{TYPE_LABEL[o.type]} — {o.location}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{o.sub}</div>
                  </span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13, color: o.fee ? 'var(--text-primary)' : 'var(--text-muted)' }}>{o.fee ? RM(o.fee) : 'FREE'}</span>
                </button>
              );
            })}
          </div>
          {sel != null && FULFILLMENT[sel].needsAddress && (
            <Field><div style={{ marginTop: 14 }}><Input label="Delivery address" value={address} onChange={(e) => setAddress(e.target.value)} placeholder="Full address, postcode, state" /></div></Field>
          )}
        </div>

        {/* RIGHT — summary */}
        <Card>
          <div style={{ padding: '18px 20px' }}>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em', margin: '0 0 14px' }}>Order summary</h2>
            {cart.map((it) => (
              <div key={it.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '8px 0', fontSize: 13 }}>
                <span style={{ color: 'var(--text-secondary)' }}>{it.qty}× {it.name}</span>
                <span style={{ fontFamily: 'var(--font-mono)' }}>{RM(it.price * it.qty)}</span>
              </div>
            ))}
            <div style={{ borderTop: '1px solid var(--border-hairline)', margin: '10px 0', paddingTop: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0' }}>
                <Label>Subtotal</Label><span style={{ fontFamily: 'var(--font-mono)' }}>{RM(subtotal)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0' }}>
                <Label>Delivery</Label><span style={{ fontFamily: 'var(--font-mono)' }}>{sel == null ? '—' : (fee ? RM(fee) : 'FREE')}</span>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderTop: '1px solid var(--border-strong)', paddingTop: 12 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, textTransform: 'uppercase' }}>Total</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 20 }}>{RM(total)}</span>
            </div>

            {err && <p style={{ color: 'var(--signal-danger)', fontSize: 13, marginTop: 12 }}>{err}</p>}

            <Button variant="primary" notch style={{ width: '100%', marginTop: 16 }} disabled={busy} onClick={placeOrder}>
              {busy ? 'Placing…' : 'Place order'}
            </Button>
            <p style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', textAlign: 'center', marginTop: 12 }}>
              Pay via TNG QR on the next step
            </p>
          </div>
        </Card>
      </div>
      )}
    </section>
  );
}

Object.assign(window, { Checkout });
})();
