// ---------- Public order: ice cream, frozen yogurt, crêpes, cart, checkout ----------

const __CART_KEY = 'gh-order-cart';
const __ORDER_TAB_KEY = 'gh-order-tab';

function _newLineId() {
  return 'L' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
}

function _loadCart() {
  try {
    const raw = sessionStorage.getItem(__CART_KEY);
    if (!raw) return [];
    return JSON.parse(raw);
  } catch (e) {
    return [];
  }
}

function _saveCart(cart) {
  try {
    sessionStorage.setItem(__CART_KEY, JSON.stringify(cart));
  } catch (e) { /* no-op */ }
}

function _lineUnitIcecream(line) {
  const t = (window.ORDER_TOPPINGS || []).filter((x) => (line.toppingIds || []).includes(x.id));
  const s = (window.ORDER_SYRUPS || []).filter((x) => (line.syrupIds || []).includes(x.id));
  const sc = line.scoops || 1;
  return sc * line.unitScoop + t.reduce((a, b) => a + b.price, 0) + s.reduce((a, b) => a + b.price, 0);
}
function _lineUnitYogurt(line) {
  const f = (window.ORDER_YOGURT_FLAVORS || []).find((x) => x.id === line.yogurtFlavorId) || { extra: 0 };
  return line.sizePrice + (f.extra || 0);
}
function _lineUnitCrepe(line) {
  const ex = (window.ORDER_CREPE_EXTRAS || []).filter((x) => (line.extraIds || []).includes(x.id));
  return line.crepeBase + ex.reduce((a, b) => a + b.price, 0);
}

function _lineUnit(line) {
  if (line.kind === 'icecream') return _lineUnitIcecream(line);
  if (line.kind === 'yogurt') return _lineUnitYogurt(line);
  if (line.kind === 'crepe') return _lineUnitCrepe(line);
  return 0;
}

function _cartSubtotal(cart) {
  return cart.reduce((sum, l) => sum + _lineUnit(l) * (l.qty || 1), 0);
}

function _whatsappDigits() {
  const d = (typeof window !== 'undefined' && window.GH_WHATSAPP_DIGITS) || '';
  return String(d).replace(/\D/g, '');
}

/** One-line human summary of a cart line (for WhatsApp). */
function _lineDescription(line) {
  const q = line.qty || 1;
  if (line.kind === 'icecream') {
    let s = `${line.flavorName} ×${q}`;
    const scoops = line.scoops || 1;
    s += ` (${scoops}× scoop)`;
    const tops = (window.ORDER_TOPPINGS || []).filter((x) => (line.toppingIds || []).includes(x.id));
    const syrs = (window.ORDER_SYRUPS || []).filter((x) => (line.syrupIds || []).includes(x.id));
    const bits = [...tops.map((x) => x.name), ...syrs.map((x) => x.name)];
    if (bits.length) s += ` + ${bits.join(', ')}`;
    return s;
  }
  if (line.kind === 'yogurt') {
    return `${line.sizeName} · ${line.flavorName} ×${q}`;
  }
  if (line.kind === 'crepe') {
    const exIds = line.extraIds || [];
    const ex = (window.ORDER_CREPE_EXTRAS || []).filter((x) => exIds.includes(x.id));
    const extraBit = ex.length ? ` + ${ex.map((e) => e.name).join(', ')}` : '';
    return `${line.crepeName} ×${q}${extraBit}`;
  }
  return '';
}

function _buildOrderWhatsAppText({ cart, total, name, phone, fulfillment, address, notes, pay, orderRef, t }) {
  const payRow = (window.ORDER_PAYMENT_METHODS || []).find((x) => x.id === pay);
  const payLabel = payRow ? payRow.label : pay;
  const lines = [];
  lines.push(`*${t('order.msg_intro')}*`);
  lines.push(`*${t('order.thank_ref')}:* ${orderRef}`);
  lines.push('');
  lines.push(`${t('order.name')}: ${name}`);
  lines.push(`${t('order.phone')}: ${phone.trim() ? phone.trim() : t('order.msg_none')}`);
  lines.push(`${t('order.fulfillment')}: ${fulfillment === 'delivery' ? t('order.delivery') : t('order.pickup')}`);
  if (fulfillment === 'delivery' && address.trim()) lines.push(`${t('order.address')}: ${address.trim()}`);
  lines.push('');
  cart.forEach((line, i) => {
    lines.push(`${i + 1}. ${_lineDescription(line)} — ${fmtNumber(_lineUnit(line) * (line.qty || 1))} FCFA`);
  });
  lines.push('');
  lines.push(`*${t('order.msg_total')}:* ${fmtNumber(total)} FCFA`);
  lines.push(`*${t('order.msg_pay')}:* ${payLabel}`);
  if (notes.trim()) lines.push(`*${t('order.msg_notes')}:* ${notes.trim()}`);
  return lines.join('\n');
}

const PayIcon = { CreditCard: Icon.CreditCard, Truck: Icon.Truck, Smartphone: Icon.Smartphone };

function OrderSection() {
  const { t } = useT();
  const [tab, setTab] = React.useState(() => { try { return sessionStorage.getItem(__ORDER_TAB_KEY) || 'ice'; } catch (e) { return 'ice'; } });
  const [cart, setCart] = React.useState(_loadCart);
  const [checkout, setCheckout] = React.useState(false);
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [address, setAddress] = React.useState('');
  const [fulfillment, setFulfillment] = React.useState('pickup');
  const [notes, setNotes] = React.useState('');
  const [pay, setPay] = React.useState('delivery');
  const [doneDetails, setDoneDetails] = React.useState(null);
  const [copiedOk, setCopiedOk] = React.useState(false);
  const [mobileCart, setMobileCart] = React.useState(false);
  const [yogSize, setYogSize] = React.useState('ys');
  const [yogFlavor, setYogFlavor] = React.useState('yf1');
  const [expandLine, setExpandLine] = React.useState(null);

  React.useEffect(() => { _saveCart(cart); }, [cart]);
  React.useEffect(() => { try { sessionStorage.setItem(__ORDER_TAB_KEY, tab); } catch (e) { /* */ } }, [tab]);

  const addIce = (f) => {
    setCart((c) => [
      ...c,
      { id: _newLineId(), kind: 'icecream', flavorId: f.id, flavorName: f.name, unitScoop: f.price, scoops: 1, toppingIds: [], syrupIds: [], qty: 1 },
    ]);
  };
  const addYogurt = () => {
    const YS = window.YOGURT_SIZES || [];
    const YF = window.ORDER_YOGURT_FLAVORS || [];
    const sz = YS.find((x) => x.id === yogSize) || YS[0];
    const fl = YF.find((x) => x.id === yogFlavor) || YF[0];
    if (!sz || !fl) return;
    setCart((c) => [
      ...c,
      {
        id: _newLineId(),
        kind: 'yogurt',
        yogurtSizeId: sz.id,
        sizeName: sz.name,
        sizePrice: sz.price,
        yogurtFlavorId: fl.id,
        flavorName: fl.name,
        qty: 1,
      },
    ]);
  };
  const addCrepe = (c) => {
    setCart((l) => [
      ...l,
      { id: _newLineId(), kind: 'crepe', crepeId: c.id, crepeName: c.name, crepeBase: c.price, extraIds: [], qty: 1 },
    ]);
  };

  const updateLine = (id, fn) => {
    setCart((rows) => rows.map((r) => (r.id === id ? fn(r) : r)));
  };
  const removeLine = (id) => {
    setExpandLine((ex) => (ex === id ? null : ex));
    setCart((rows) => rows.filter((r) => r.id !== id));
  };
  const setScoops = (id, n) => {
    const v = Math.max(1, Math.min(20, n));
    updateLine(id, (r) => (r.kind === 'icecream' ? { ...r, scoops: v } : r));
  };
  const setLineQty = (id, n) => {
    const v = Math.max(1, Math.min(99, n));
    updateLine(id, (r) => ({ ...r, qty: v }));
  };
  const toggleTop = (lineId, tid) => {
    updateLine(lineId, (r) => {
      if (r.kind !== 'icecream') return r;
      const set = new Set(r.toppingIds || []);
      if (set.has(tid)) set.delete(tid); else set.add(tid);
      return { ...r, toppingIds: [...set] };
    });
  };
  const toggleSyr = (lineId, sid) => {
    updateLine(lineId, (r) => {
      if (r.kind !== 'icecream') return r;
      const set = new Set(r.syrupIds || []);
      if (set.has(sid)) set.delete(sid); else set.add(sid);
      return { ...r, syrupIds: [...set] };
    });
  };
  const toggleExtra = (lineId, eid) => {
    updateLine(lineId, (r) => {
      if (r.kind !== 'crepe') return r;
      const set = new Set(r.extraIds || []);
      if (set.has(eid)) set.delete(eid); else set.add(eid);
      return { ...r, extraIds: [...set] };
    });
  };

  const total = _cartSubtotal(cart);

  const placeOrder = (e) => {
    e.preventDefault();
    if (!cart.length) return;
    if (fulfillment === 'delivery' && !address.trim()) return;
    const orderRef = 'GH-' + Date.now().toString(36).toUpperCase().slice(-10);
    const msg = _buildOrderWhatsAppText({
      cart, total, name, phone, fulfillment, address, notes, pay, orderRef, t,
    });
    const digits = _whatsappDigits();
    let waUrl = null;
    if (digits.length >= 10) {
      waUrl = `https://wa.me/${digits}?text=${encodeURIComponent(msg)}`;
      window.open(waUrl, '_blank', 'noopener,noreferrer');
    }
    setDoneDetails({ ref: orderRef, msg, waUrl });
    setCopiedOk(false);
    setCart([]);
    setCheckout(false);
    setMobileCart(false);
    setName('');
    setPhone('');
    setAddress('');
    setNotes('');
    setFulfillment('pickup');
    setPay('delivery');
  };

  const tabBtn = (id, label) => (
    <button
      type="button"
      onClick={() => setTab(id)}
      style={{
        padding: '10px 18px',
        borderRadius: 999,
        border: '1px solid ' + (tab === id ? 'var(--accent)' : 'var(--border)'),
        background: tab === id ? 'var(--accent-dim)' : 'var(--card2)',
        color: tab === id ? 'var(--accent)' : 'var(--text-dim)',
        fontSize: 12,
        fontWeight: 600,
        fontFamily: 'JetBrains Mono',
        letterSpacing: '0.06em',
        textTransform: 'uppercase',
        cursor: 'pointer',
        transition: 'all .2s',
      }}
    >
      {label}
    </button>
  );

  if (doneDetails) {
    return (
      <section id="order" style={{ padding: '100px 40px 80px', background: 'var(--surface)', borderTop: '1px solid var(--border)' }}>
        <div style={{ maxWidth: 560, margin: '0 auto', textAlign: 'center' }}>
          <div style={{ fontFamily: 'Cormorant Garamond', fontSize: 48, fontWeight: 300, color: 'var(--accent)', marginBottom: 16 }}>Thank you</div>
          <p style={{ fontFamily: 'JetBrains Mono', fontSize: 14, color: 'var(--accent)', marginBottom: 8 }}>{t('order.thank_ref')}: <strong>{doneDetails.ref}</strong></p>
          <p style={{ color: 'var(--text-dim)', lineHeight: 1.6, marginBottom: 24 }}>{t('order.thank_body')}</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 320, margin: '0 auto 24px' }}>
            {doneDetails.waUrl && (
              <a href={doneDetails.waUrl} target="_blank" rel="noopener noreferrer" className="btn btn-primary" style={{ justifyContent: 'center', textDecoration: 'none' }}>
                {t('order.open_whatsapp')}
              </a>
            )}
            <button
              type="button"
              className="btn btn-ghost"
              style={{ justifyContent: 'center', border: '1px solid var(--border2)' }}
              onClick={() => {
                navigator.clipboard.writeText(doneDetails.msg).then(() => {
                  setCopiedOk(true);
                  setTimeout(() => setCopiedOk(false), 2500);
                });
              }}
            >
              {copiedOk ? t('order.copy_done') : t('order.copy_message')}
            </button>
          </div>
          <button type="button" className="btn btn-primary" onClick={() => setDoneDetails(null)}>{t('order.thank_back')}</button>
        </div>
      </section>
    );
  }

  return (
    <section id="order" style={{ padding: '100px 40px 100px', background: 'var(--bg)' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 14, fontFamily: 'JetBrains Mono' }}>✦ {t('order.eyebrow')}</div>
          <h2 style={{ fontFamily: 'Cormorant Garamond', fontSize: 'clamp(36px,5vw,56px)', fontWeight: 300, letterSpacing: '-0.02em' }}>{t('order.title')}</h2>
          <p style={{ color: 'var(--text-dim)', maxWidth: 640, margin: '16px auto 0', lineHeight: 1.6 }}>{t('order.sub')}</p>
        </div>

        <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 10, marginBottom: 36 }}>{tabBtn('ice', t('order.tab_ice'))}{tabBtn('yog', t('order.tab_yog'))}{tabBtn('crepe', t('order.tab_crepe'))}</div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 28, alignItems: 'start' }} className="order-grid">
          <div>
            {tab === 'ice' && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px,1fr))', gap: 16 }} className="order-product-grid">
                {(window.ORDER_ICE_CREAM || []).map((f) => (
                  <div
                    key={f.id}
                    className="card"
                    style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 10, border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', background: 'var(--card)' }}
                  >
                    <div style={{ height: 100, borderRadius: 12, background: `radial-gradient(circle at 30% 20%, ${f.color2},${f.color} 90%)`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 40 }}>
                      {f.emoji}
                    </div>
                    <div style={{ fontWeight: 500, fontSize: 16 }}>{f.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.4, flex: 1 }}>{f.desc}</div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                      <span style={{ fontFamily: 'JetBrains Mono', color: 'var(--accent)' }}>{fmtNumber(f.price)} FCFA <span style={{ color: 'var(--text-dim)', fontSize: 10 }}>/{t('order.per_scoop')}</span></span>
                      <button type="button" className="btn btn-primary btn-sm" onClick={() => addIce(f)}>+ {t('order.add')}</button>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {tab === 'yog' && (
              <div className="card" style={{ padding: 24, maxWidth: 640, background: 'var(--card)', border: '1px solid var(--border2)', borderRadius: 'var(--radius-lg)' }}>
                <h3 style={{ fontFamily: 'Cormorant Garamond', fontSize: 28, fontWeight: 400, marginBottom: 8 }}>{t('order.yogurt_build')}</h3>
                <p style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 20 }}>{t('order.yogurt_hint')}</p>
                <div style={{ marginBottom: 16 }}>
                  <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-dim)', marginBottom: 8 }}>{t('order.size')}</div>
                  <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                    {(window.YOGURT_SIZES || []).map((s) => (
                      <button
                        key={s.id}
                        type="button"
                        onClick={() => setYogSize(s.id)}
                        style={{
                          padding: '12px 18px',
                          borderRadius: 12,
                          border: '1px solid ' + (yogSize === s.id ? 'var(--accent)' : 'var(--border)'),
                          background: yogSize === s.id ? 'var(--accent-dim)' : 'var(--card2)',
                          color: 'var(--text)',
                          textAlign: 'left',
                        }}
                      >
                        <div style={{ fontWeight: 600 }}>{s.name} · {fmtNumber(s.price)} F</div>
                        <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>~{s.ml} ml</div>
                      </button>
                    ))}
                  </div>
                </div>
                <div style={{ marginBottom: 20 }}>
                  <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-dim)', marginBottom: 8 }}>{t('order.flavor')}</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px,1fr))', gap: 8 }}>
                    {(window.ORDER_YOGURT_FLAVORS || []).map((f) => (
                      <button
                        key={f.id}
                        type="button"
                        onClick={() => setYogFlavor(f.id)}
                        style={{
                          padding: 10,
                          borderRadius: 10,
                          border: '1px solid ' + (yogFlavor === f.id ? 'var(--accent)' : 'var(--border)'),
                          background: yogFlavor === f.id ? 'var(--accent-dim)' : 'var(--card2)',
                          display: 'flex',
                          alignItems: 'center',
                          gap: 8,
                        }}
                      >
                        <span style={{ fontSize: 20 }}>{f.emoji}</span>
                        <span style={{ fontSize: 12 }}>{f.name}{f.extra ? ` +${f.extra} F` : ''}</span>
                      </button>
                    ))}
                  </div>
                </div>
                <button type="button" className="btn btn-primary" onClick={addYogurt}>{t('order.add_yogurt')}</button>
              </div>
            )}

            {tab === 'crepe' && (
              <div>
                <p style={{ color: 'var(--text-dim)', marginBottom: 16, maxWidth: 700, lineHeight: 1.6 }}>{t('order.crepe_intro')}</p>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px,1fr))', gap: 16 }}>
                  {(window.ORDER_CREPES || []).map((c) => (
                    <div key={c.id} className="card" style={{ padding: 20, background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)' }}>
                      <div style={{ fontSize: 32, marginBottom: 8 }}>{c.emoji}</div>
                      <div style={{ fontWeight: 500, marginBottom: 6 }}>{c.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 12 }}>{c.desc}</div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontFamily: 'JetBrains Mono', color: 'var(--accent)' }}>{fmtNumber(c.price)} F</span>
                        <button type="button" className="btn btn-primary btn-sm" onClick={() => addCrepe(c)}>+ {t('order.add')}</button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <p style={{ fontSize: 12, color: 'var(--text-dimmer)', marginTop: 24, fontStyle: 'italic' }}>{t('order.legal')}</p>
          </div>

          {/* Cart column */}
          <div className="hide-md" style={{ position: 'sticky', top: 88 }}>
            <OrderCart
              t={t}
              cart={cart}
              setExpandLine={setExpandLine}
              expandLine={expandLine}
              removeLine={removeLine}
              setScoops={setScoops}
              setLineQty={setLineQty}
              toggleTop={toggleTop}
              toggleSyr={toggleSyr}
              toggleExtra={toggleExtra}
              total={total}
              onProceed={() => { setCheckout(true); setMobileCart(false); }}
            />
          </div>
        </div>
      </div>

      {checkout && (
        <div
          style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(0,0,0,0.65)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, overflow: 'auto' }}
          onClick={() => setCheckout(false)}
        >
          <div
            className="card"
            onClick={(e) => e.stopPropagation()}
            style={{ width: '100%', maxWidth: 440, padding: 28, background: 'var(--card)', borderRadius: 'var(--radius-xl)', border: '1px solid var(--border2)' }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
              <h3 style={{ fontFamily: 'Cormorant Garamond', fontSize: 26 }}>{t('order.checkout')}</h3>
              <button type="button" onClick={() => setCheckout(false)} style={{ color: 'var(--text-dim)' }}><Icon.X size={22} /></button>
            </div>
            <form onSubmit={placeOrder} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)' }}>{t('order.name')}</label>
                <input required value={name} onChange={(e) => setName(e.target.value)} style={{ width: '100%', marginTop: 6, padding: 10, borderRadius: 8, border: '1px solid var(--border)', background: 'var(--card2)', color: 'var(--text)' }} />
              </div>
              <div>
                <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)' }}>{t('order.phone')}</label>
                <input required value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+235 …" style={{ width: '100%', marginTop: 6, padding: 10, borderRadius: 8, border: '1px solid var(--border)', background: 'var(--card2)', color: 'var(--text)' }} />
              </div>
              <div>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)', marginBottom: 8 }}>{t('order.fulfillment')}</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button
                    type="button"
                    onClick={() => setFulfillment('pickup')}
                    style={{
                      flex: 1,
                      padding: '12px 14px',
                      borderRadius: 10,
                      border: '1px solid ' + (fulfillment === 'pickup' ? 'var(--accent)' : 'var(--border)'),
                      background: fulfillment === 'pickup' ? 'var(--accent-dim)' : 'var(--card2)',
                      color: 'var(--text)',
                      cursor: 'pointer',
                      fontWeight: 600,
                      fontSize: 13,
                    }}
                  >
                    {t('order.pickup')}
                  </button>
                  <button
                    type="button"
                    onClick={() => setFulfillment('delivery')}
                    style={{
                      flex: 1,
                      padding: '12px 14px',
                      borderRadius: 10,
                      border: '1px solid ' + (fulfillment === 'delivery' ? 'var(--accent)' : 'var(--border)'),
                      background: fulfillment === 'delivery' ? 'var(--accent-dim)' : 'var(--card2)',
                      color: 'var(--text)',
                      cursor: 'pointer',
                      fontWeight: 600,
                      fontSize: 13,
                    }}
                  >
                    {t('order.delivery')}
                  </button>
                </div>
                {fulfillment === 'pickup' && (
                  <p style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 10, marginBottom: 0 }}>{t('order.addr_pickup')}</p>
                )}
              </div>
              {fulfillment === 'delivery' && (
                <div>
                  <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)' }}>{t('order.address')}</label>
                  <textarea required value={address} onChange={(e) => setAddress(e.target.value)} rows={2} style={{ width: '100%', marginTop: 6, padding: 10, borderRadius: 8, border: '1px solid var(--border)', background: 'var(--card2)', color: 'var(--text)', resize: 'vertical' }} />
                </div>
              )}
              <div>
                <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)' }}>{t('order.notes')}</label>
                <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} placeholder={t('order.notes_placeholder')} style={{ width: '100%', marginTop: 6, padding: 10, borderRadius: 8, border: '1px solid var(--border)', background: 'var(--card2)', color: 'var(--text)', resize: 'vertical' }} />
              </div>
              <div>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)', marginBottom: 8 }}>{t('order.payment')}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {(window.ORDER_PAYMENT_METHODS || []).map((m) => {
                    const Ico = PayIcon[m.icon] || Icon.Smartphone;
                    return (
                      <label
                        key={m.id}
                        style={{
                          display: 'flex', alignItems: 'flex-start', gap: 10, padding: 12, borderRadius: 10, border: '1px solid ' + (pay === m.id ? 'var(--accent)' : 'var(--border)'),
                          background: pay === m.id ? 'var(--accent-dim)' : 'var(--card2)', cursor: 'pointer',
                        }}
                      >
                        <input type="radio" name="pay" value={m.id} checked={pay === m.id} onChange={() => setPay(m.id)} style={{ marginTop: 3 }} />
                        <div style={{ flex: 1 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <Ico size={16} />
                            <span style={{ fontWeight: 500 }}>{m.label}</span>
                          </div>
                          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{m.hint}</div>
                        </div>
                      </label>
                    );
                  })}
                </div>
              </div>
              <div style={{ padding: 14, background: 'var(--card2)', borderRadius: 10, border: '1px solid var(--border)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}><span style={{ color: 'var(--text-dim)' }}>{t('order.subtotal')}</span><span className="mono" style={{ fontWeight: 600 }}>{fmtNumber(total)} FCFA</span></div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 6 }}>{t('order.no_tax')}</div>
              </div>
              <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }}>{t('order.submit')}</button>
            </form>
          </div>
        </div>
      )}

      {/* mobile cart bar */}
      <div className="show-md" style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 90, background: 'var(--surface)', borderTop: '1px solid var(--border)', padding: '10px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <button type="button" onClick={() => setMobileCart(true)} style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text)' }}>
          <Icon.ShoppingBag size={22} />
          <span className="mono" style={{ fontWeight: 600 }}>{fmtNumber(total)} F</span>
          <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>({cart.length})</span>
        </button>
        <button type="button" className="btn btn-primary btn-sm" disabled={!cart.length} onClick={() => setMobileCart(true)}>{t('order.view_cart')}</button>
      </div>

      {mobileCart && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'var(--bg)' }} className="show-md">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: 16, borderBottom: '1px solid var(--border)' }}>
            <h3 style={{ fontFamily: 'Cormorant Garamond' }}>{t('order.cart')}</h3>
            <button type="button" onClick={() => setMobileCart(false)}><Icon.X size={24} /></button>
          </div>
          <div style={{ padding: 16, maxHeight: '70vh', overflow: 'auto' }}>
            <OrderCart
              t={t}
              cart={cart}
              setExpandLine={setExpandLine}
              expandLine={expandLine}
              removeLine={removeLine}
              setScoops={setScoops}
              setLineQty={setLineQty}
              toggleTop={toggleTop}
              toggleSyr={toggleSyr}
              toggleExtra={toggleExtra}
              total={total}
              onProceed={() => { setCheckout(true); setMobileCart(false); }}
              mobile
            />
          </div>
          <div style={{ padding: 16, borderTop: '1px solid var(--border)' }}>
            <button type="button" className="btn btn-primary" style={{ width: '100%' }} disabled={!cart.length} onClick={() => { if (cart.length) { setCheckout(true); setMobileCart(false); } }}>{t('order.proceed')}</button>
          </div>
        </div>
      )}

      <style>{`
        @media (max-width: 900px) {
          .order-grid { grid-template-columns: 1fr !important; }
          #order { padding-bottom: 120px !important; }
        }
      `}</style>
    </section>
  );
}

function OrderCart({ t, cart, setExpandLine, expandLine, removeLine, setScoops, setLineQty, toggleTop, toggleSyr, toggleExtra, total, onProceed, mobile }) {
  return (
    <div className="card" style={{ padding: 20, background: 'var(--card)', border: '1px solid var(--border2)', borderRadius: 'var(--radius-lg)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon.ShoppingBag size={20} />
          <span style={{ fontWeight: 600, fontSize: 16 }}>{t('order.cart')}</span>
        </div>
        <span style={{ fontSize: 11, fontFamily: 'JetBrains Mono', color: 'var(--text-dim)' }}>{cart.length} {t('order.lines')}</span>
      </div>
      {!cart.length && <div style={{ color: 'var(--text-dim)', fontSize: 13, padding: '20px 0' }}>{t('order.empty')}</div>}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxHeight: mobile ? 'none' : '55vh', overflow: 'auto' }}>
        {cart.map((line) => (
          <div key={line.id} style={{ padding: 12, background: 'var(--card2)', borderRadius: 10, border: '1px solid var(--border)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'flex-start' }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 500, fontSize: 14 }}>
                  {line.kind === 'icecream' && <>{line.flavorName}</>}
                  {line.kind === 'yogurt' && <>{line.sizeName} · {line.flavorName}</>}
                  {line.kind === 'crepe' && <>{line.crepeName}</>}
                </div>
                {line.kind === 'icecream' && (
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>{t('order.scoops')}: {line.scoops || 1}</div>
                )}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                <button
                  type="button"
                  onClick={() => setLineQty(line.id, (line.qty || 1) - 1)}
                  style={{ width: 30, height: 30, borderRadius: 8, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)' }}
                >
                  <Icon.Minus size={14} />
                </button>
                <span className="mono" style={{ minWidth: 24, textAlign: 'center', fontWeight: 600 }}>{line.qty || 1}</span>
                <button
                  type="button"
                  onClick={() => setLineQty(line.id, (line.qty || 1) + 1)}
                  style={{ width: 30, height: 30, borderRadius: 8, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)' }}
                >
                  <Icon.Plus size={14} />
                </button>
              </div>
            </div>
            {line.kind === 'icecream' && (
              <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>{t('order.scoops')}</span>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <button type="button" onClick={() => setScoops(line.id, (line.scoops || 1) - 1)} style={{ width: 28, height: 28, borderRadius: 6, border: '1px solid var(--border)' }}>−</button>
                  <span className="mono" style={{ minWidth: 20, textAlign: 'center' }}>{line.scoops || 1}</span>
                  <button type="button" onClick={() => setScoops(line.id, (line.scoops || 1) + 1)} style={{ width: 28, height: 28, borderRadius: 6, border: '1px solid var(--border)' }}>+</button>
                </div>
                <button type="button" onClick={() => setExpandLine(expandLine === line.id ? null : line.id)} style={{ fontSize: 11, color: 'var(--accent)' }}>
                  {expandLine === line.id ? t('order.less') : t('order.customize')}
                </button>
              </div>
            )}
            {line.kind === 'icecream' && expandLine === line.id && (
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)', marginBottom: 6 }}>{t('order.toppings')}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {(window.ORDER_TOPPINGS || []).map((o) => (
                    <label key={o.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, padding: '4px 8px', borderRadius: 6, border: '1px solid ' + (line.toppingIds.includes(o.id) ? 'var(--accent)' : 'var(--border)'), cursor: 'pointer' }}>
                      <input type="checkbox" checked={line.toppingIds.includes(o.id)} onChange={() => toggleTop(line.id, o.id)} />
                      {o.name} +{fmtNumber(o.price)}
                    </label>
                  ))}
                </div>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)', margin: '10px 0 6px' }}>{t('order.syrups')}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {(window.ORDER_SYRUPS || []).map((o) => (
                    <label key={o.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, padding: '4px 8px', borderRadius: 6, border: '1px solid ' + (line.syrupIds.includes(o.id) ? 'var(--accent)' : 'var(--border)'), cursor: 'pointer' }}>
                      <input type="checkbox" checked={line.syrupIds.includes(o.id)} onChange={() => toggleSyr(line.id, o.id)} />
                      {o.name} +{fmtNumber(o.price)}
                    </label>
                  ))}
                </div>
              </div>
            )}
            {line.kind === 'crepe' && (
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-dim)', marginBottom: 6 }}>{t('order.crepe_extras')}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {(window.ORDER_CREPE_EXTRAS || []).map((e) => (
                    <label key={e.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, fontSize: 12, cursor: 'pointer' }}>
                      <span><input type="checkbox" checked={line.extraIds.includes(e.id)} onChange={() => toggleExtra(line.id, e.id)} /> {e.name}</span>
                      <span className="mono" style={{ color: 'var(--text-dim)' }}>+{fmtNumber(e.price)}</span>
                    </label>
                  ))}
                </div>
              </div>
            )}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
              <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>{t('order.line')}</span>
              <span className="mono" style={{ fontWeight: 600, color: 'var(--accent)' }}>{fmtNumber(_lineUnit(line) * (line.qty || 1))} FCFA</span>
            </div>
            <button type="button" onClick={() => removeLine(line.id)} style={{ fontSize: 11, color: 'var(--red)', marginTop: 8, background: 'none', border: 'none', cursor: 'pointer' }}>{t('order.remove')}</button>
          </div>
        ))}
      </div>
      {!!cart.length && (
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border2)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}><span style={{ color: 'var(--text-dim)' }}>{t('order.subtotal')}</span><span className="mono" style={{ fontSize: 18, fontWeight: 600 }}>{fmtNumber(total)} FCFA</span></div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 12 }}>{t('order.no_tax')}</div>
          <button type="button" className="btn btn-primary" style={{ width: '100%' }} onClick={onProceed}>{t('order.proceed')}</button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { OrderSection, OrderCart, _lineUnit, _cartSubtotal });
