// กับข้าวคุณแม่ — Remaining screens (detail / cart / checkout / status / receipt / history)
// Loaded after screens.jsx — uses the atoms it exposes.

const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2 } = React;
const _t = (l, k) => window.tt(l, k);

// ─────────────────────────────────────────────────────────────
// ITEM DETAIL (bottom sheet)
// ─────────────────────────────────────────────────────────────
function ItemDetail({ item, lang, onClose, onAdd }) {
  const proteinOptions = item.proteinGroup === 'full' ? window.PROTEIN_FULL
                       : item.proteinGroup === 'minced_seafood' ? window.PROTEIN_MINCED_SEAFOOD
                       : null;

  const [format, setFormat] = useState2(item.hasFormat ? 'rice' : null);
  const [protein, setProtein] = useState2(proteinOptions ? proteinOptions[0].id : null);
  const [addons, setAddons] = useState2([]);
  const [spice, setSpice] = useState2(item.spicy > 0 ? 'med' : 'none');
  const [note, setNote] = useState2('');
  const [qty, setQty] = useState2(1);

  const proteinDelta = proteinOptions
    ? (proteinOptions.find(p => p.id === protein)?.delta || 0)
    : 0;
  const formatDelta = format === 'dish' ? -5 : 0; // กับข้าวจาน ไม่มีข้าว → ลด ฿5
  const addonDelta = addons.reduce((sum, id) => sum + (window.ADDONS.find(a => a.id === id)?.price || 0), 0);
  const unit = item.basePrice + proteinDelta + formatDelta + addonDelta;
  const total = unit * qty;

  const toggleAddon = (id) => {
    setAddons(addons.includes(id) ? addons.filter(a => a !== id) : [...addons, id]);
  };

  const handleAdd = () => {
    onAdd({
      menuId: item.id,
      name: { th: item.th, en: item.en },
      basePrice: item.basePrice,
      format,
      protein,
      proteinLabel: proteinOptions ? _t(lang, proteinOptions.find(p => p.id === protein).key) : null,
      addons,
      spice,
      note: note.trim(),
      qty,
      unitPrice: unit,
      total,
      c1: item.c1, c2: item.c2,
    });
  };

  const phLabel = lang === 'th' ? `[ ${item.th} ]` : `[ ${item.en} ]`;
  const name = lang === 'th' ? item.th : item.en;
  const desc = lang === 'th' ? item.descTh : item.descEn;

  return (
    <div className="fade-in" style={{
      position: 'absolute', inset: 0, background: 'rgba(42,26,14,0.55)',
      zIndex: 100, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
    }} onClick={onClose}>
      <div className="slide-up" onClick={e => e.stopPropagation()} style={{
        background: 'var(--cream-50)',
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        maxHeight: '92%', display: 'flex', flexDirection: 'column',
        position: 'relative',
        boxShadow: '0 -10px 40px rgba(42,26,14,0.25)',
      }}>
        {/* grabber */}
        <div style={{
          position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)',
          width: 40, height: 4, borderRadius: 99, background: 'var(--cream-300)',
        }}/>
        {/* close */}
        <button onClick={onClose} className="press" style={{
          position: 'absolute', top: 18, right: 16, zIndex: 5,
          width: 34, height: 34, borderRadius: 999,
          background: 'rgba(255,252,245,0.92)', backdropFilter: 'blur(6px)',
          border: '1px solid var(--cream-200)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--brown-700)', fontSize: 18,
        }}>×</button>

        {/* scroll */}
        <div style={{ overflow: 'auto', flex: 1 }} className="scroll-hide">
          {/* hero image */}
          <div style={{ height: 200, position: 'relative' }}>
            <FoodPlaceholder c1={item.c1} c2={item.c2} label={phLabel} size="lg"/>
          </div>

          <div style={{ padding: '18px 20px 4px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
              <div style={{ flex: 1 }}>
                <h2 style={{
                  margin: 0, fontFamily: 'var(--font-display)',
                  fontSize: 30, fontWeight: 700, lineHeight: 1.1, color: 'var(--brown-900)',
                }}>{name}</h2>
                <div style={{ display: 'flex', gap: 8, marginTop: 6, alignItems: 'center', flexWrap: 'wrap' }}>
                  {item.popular && (
                    <span style={{
                      fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4,
                      background: 'var(--mustard-100)', color: 'var(--mustard)',
                      letterSpacing: '0.04em', whiteSpace: 'nowrap',
                    }}>★ {lang === 'th' ? 'ฮิต' : 'HOT'}</span>
                  )}
                  {item.spicy > 0 && (
                    <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center', fontSize: 11, color: 'var(--chili)', fontWeight: 500 }}>
                      <ChiliIcons n={item.spicy} size={11}/> {_t(lang, 'spicy')}
                    </span>
                  )}
                </div>
                <div style={{ fontSize: 13, color: 'var(--brown-500)', lineHeight: 1.45, marginTop: 10 }}>{desc}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 10, color: 'var(--brown-500)', fontWeight: 500 }}>{_t(lang, 'base_price')}</div>
                <div style={{
                  fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700,
                  color: 'var(--terra-700)', lineHeight: 1,
                }}>{fmtBaht(item.basePrice)}</div>
              </div>
            </div>
          </div>

          {/* Format toggle: ราดข้าว / กับข้าว */}
          {item.hasFormat && (
            <Section title={_t(lang, 'format')} required lang={lang}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {[
                  { id: 'rice', titleKey: 'format_rice', subKey: 'format_rice_sub', delta: 0,
                    icon: <RiceIcon /> },
                  { id: 'dish', titleKey: 'format_dish', subKey: 'format_dish_sub', delta: -5,
                    icon: <DishIcon /> },
                ].map(opt => {
                  const active = format === opt.id;
                  return (
                    <button key={opt.id} onClick={() => setFormat(opt.id)} className="press" style={{
                      textAlign: 'left', padding: 12,
                      background: active ? 'var(--terra-100)' : 'var(--paper)',
                      border: '2px solid ' + (active ? 'var(--terra)' : 'var(--cream-200)'),
                      borderRadius: 14,
                      display: 'flex', flexDirection: 'column', gap: 8,
                    }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                        <div style={{ color: active ? 'var(--terra-700)' : 'var(--brown-700)' }}>{opt.icon}</div>
                        {opt.delta !== 0 && (
                          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--leaf)' }}>
                            {opt.delta > 0 ? '+' : ''}{opt.delta}฿
                          </span>
                        )}
                      </div>
                      <div>
                        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--brown-900)' }}>{_t(lang, opt.titleKey)}</div>
                        <div style={{ fontSize: 11, color: 'var(--brown-500)', marginTop: 2, lineHeight: 1.3 }}>{_t(lang, opt.subKey)}</div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </Section>
          )}

          {/* Protein */}
          {proteinOptions && (
            <Section title={_t(lang, 'protein')} required lang={lang}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {proteinOptions.map(p => {
                  const active = protein === p.id;
                  return (
                    <button key={p.id} onClick={() => setProtein(p.id)} className="press" style={{
                      padding: '10px 16px', borderRadius: 12,
                      background: active ? 'var(--brown-900)' : 'var(--paper)',
                      border: '2px solid ' + (active ? 'var(--brown-900)' : 'var(--cream-200)'),
                      color: active ? 'var(--cream-50)' : 'var(--brown-900)',
                      display: 'flex', alignItems: 'center', gap: 8,
                      fontWeight: 500, fontSize: 14,
                    }}>
                      <span>{_t(lang, p.key)}</span>
                      {p.delta > 0 && (
                        <span style={{
                          fontSize: 11, padding: '2px 6px', borderRadius: 4,
                          background: active ? 'rgba(255,252,245,0.2)' : 'var(--mustard-100)',
                          color: active ? 'var(--cream-50)' : 'var(--mustard)',
                          fontWeight: 600,
                        }}>+{p.delta}฿</span>
                      )}
                    </button>
                  );
                })}
              </div>
            </Section>
          )}

          {/* Add-ons */}
          <Section title={_t(lang, 'addons')} optional lang={lang}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {window.ADDONS.map(a => {
                const active = addons.includes(a.id);
                return (
                  <button key={a.id} onClick={() => toggleAddon(a.id)} className="press" style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '10px 12px', borderRadius: 12,
                    background: active ? 'var(--terra-100)' : 'var(--paper)',
                    border: '1.5px solid ' + (active ? 'var(--terra)' : 'var(--cream-200)'),
                    textAlign: 'left',
                  }}>
                    <div style={{
                      width: 22, height: 22, borderRadius: 6,
                      background: active ? 'var(--terra)' : 'var(--paper)',
                      border: '2px solid ' + (active ? 'var(--terra)' : 'var(--brown-300)'),
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {active && <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8l3.5 3.5L13 4"/></svg>}
                    </div>
                    <div style={{ flex: 1, fontSize: 14, fontWeight: 500, color: 'var(--brown-900)' }}>{_t(lang, a.key)}</div>
                    <div style={{
                      fontSize: 13, fontWeight: 600,
                      color: a.price > 0 ? 'var(--terra-700)' : 'var(--leaf)',
                    }}>{a.price > 0 ? `+${a.price}฿` : _t(lang, 'free')}</div>
                  </button>
                );
              })}
            </div>
          </Section>

          {/* Spice */}
          {item.spicy > 0 && (
            <Section title={_t(lang, 'spice')} lang={lang}>
              <div style={{ display: 'flex', gap: 8 }}>
                {window.SPICE_LEVELS.map(s => {
                  const active = spice === s.id;
                  return (
                    <button key={s.id} onClick={() => setSpice(s.id)} className="press" style={{
                      flex: 1, padding: '10px 6px', borderRadius: 12,
                      background: active ? 'var(--terra-100)' : 'var(--paper)',
                      border: '1.5px solid ' + (active ? 'var(--terra)' : 'var(--cream-200)'),
                      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                    }}>
                      <div style={{ height: 16, display: 'flex', alignItems: 'center' }}>
                        {s.icons > 0 ? <ChiliIcons n={s.icons} size={12} /> : (
                          <span style={{ fontSize: 11, color: 'var(--brown-300)' }}>○</span>
                        )}
                      </div>
                      <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--brown-900)' }}>{_t(lang, s.key)}</div>
                    </button>
                  );
                })}
              </div>
            </Section>
          )}

          {/* Notes */}
          <Section title={_t(lang, 'extras')} optional lang={lang}>
            <textarea
              value={note}
              onChange={e => setNote(e.target.value)}
              placeholder={_t(lang, 'note_ph')}
              rows={2}
              style={{
                width: '100%', padding: 12, borderRadius: 12,
                background: 'var(--paper)', border: '1.5px solid var(--cream-200)',
                fontSize: 13, resize: 'none', outline: 'none',
                color: 'var(--brown-900)',
              }}
            />
          </Section>

          {/* Qty */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 20px 24px',
          }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--brown-700)' }}>{_t(lang, 'qty')}</div>
            <QtyStepper qty={qty} setQty={setQty} />
          </div>
        </div>

        {/* CTA */}
        <div style={{
          padding: '14px 20px 24px',
          background: 'var(--paper)',
          borderTop: '1px solid var(--cream-200)',
        }}>
          <button onClick={handleAdd} className="press" style={{
            width: '100%', padding: '14px 18px',
            background: 'var(--terra)', color: 'white',
            borderRadius: 16,
            fontSize: 15, fontWeight: 600,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            boxShadow: '0 10px 24px -10px rgba(194,65,12,0.5)',
            whiteSpace: 'nowrap', gap: 8,
          }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap' }}>
              <span style={{
                background: 'rgba(255,252,245,0.22)', padding: '2px 8px', borderRadius: 6,
                fontSize: 13, fontWeight: 700,
              }}>{qty}×</span>
              <span style={{ whiteSpace: 'nowrap' }}>{_t(lang, 'add_to_cart')}</span>
            </span>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, whiteSpace: 'nowrap' }}>{fmtBaht(total)}</span>
          </button>
        </div>
      </div>
    </div>
  );
}

// Form section helper
function Section({ title, children, required, optional, lang }) {
  return (
    <div style={{ padding: '12px 20px 6px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
        <div style={{
          fontSize: 13, fontWeight: 600, color: 'var(--brown-700)',
          letterSpacing: '0.02em', whiteSpace: 'nowrap',
        }}>
          {title}
        </div>
        {required && <span style={{
          fontSize: 10, fontWeight: 700, color: 'var(--terra)',
          background: 'var(--terra-100)', padding: '2px 8px', borderRadius: 99,
          letterSpacing: '0.04em',
        }}>*</span>}
        {optional && <span style={{ fontSize: 11, color: 'var(--brown-500)', whiteSpace: 'nowrap' }}>
          ({lang === 'th' ? 'ไม่บังคับ' : 'optional'})
        </span>}
      </div>
      {children}
    </div>
  );
}

// Decorative icons for format options
function RiceIcon() {
  return (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none">
      <ellipse cx="16" cy="22" rx="13" ry="3.5" fill="currentColor" opacity="0.15"/>
      <path d="M3 22 C3 16, 9 11, 16 11 S29 16, 29 22" fill="currentColor" opacity="0.18"/>
      <path d="M8 14 q2 -4 4 0 M14 12 q2 -4 4 0 M20 14 q2 -4 4 0" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
      <circle cx="10" cy="16" r="1.2" fill="currentColor"/>
      <circle cx="16" cy="15" r="1.2" fill="currentColor"/>
      <circle cx="22" cy="16" r="1.2" fill="currentColor"/>
      <circle cx="13" cy="18" r="1.2" fill="currentColor"/>
      <circle cx="19" cy="18" r="1.2" fill="currentColor"/>
    </svg>
  );
}
function DishIcon() {
  return (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none">
      <ellipse cx="16" cy="22" rx="14" ry="3.5" fill="currentColor" opacity="0.15"/>
      <ellipse cx="16" cy="20" rx="12" ry="3" fill="currentColor" opacity="0.25"/>
      <ellipse cx="16" cy="19" rx="9" ry="2" fill="currentColor"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// CART
// ─────────────────────────────────────────────────────────────
function summarizeItem(line, lang) {
  const parts = [];
  if (line.format) parts.push(_t(lang, line.format === 'rice' ? 'format_rice' : 'format_dish'));
  if (line.proteinLabel) parts.push(line.proteinLabel);
  if (line.spice && line.spice !== 'none') {
    const sl = window.SPICE_LEVELS.find(s => s.id === line.spice);
    parts.push(_t(lang, 'spice') + ' ' + _t(lang, sl.key));
  }
  if (line.addons && line.addons.length) {
    line.addons.forEach(id => {
      const a = window.ADDONS.find(x => x.id === id);
      if (a) parts.push(_t(lang, a.key));
    });
  }
  return parts.join(' · ');
}

function CartLine({ line, lang, onRemove, onChangeQty }) {
  const name = line.name[lang];
  const sum = summarizeItem(line, lang);
  return (
    <div style={{
      background: 'var(--paper)', borderRadius: 18, padding: 12,
      border: '1px solid var(--cream-200)',
      display: 'flex', gap: 12,
      boxShadow: 'var(--shadow-sm)',
    }}>
      <div style={{ width: 64, height: 64, borderRadius: 12, overflow: 'hidden', flexShrink: 0 }}>
        <FoodPlaceholder c1={line.c1} c2={line.c2} label={`[ ${name} ]`} size="sm"/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--brown-900)' }}>{name}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700, color: 'var(--terra-700)' }}>{fmtBaht(line.total)}</div>
        </div>
        {sum && <div style={{ fontSize: 11, color: 'var(--brown-500)', lineHeight: 1.4, marginTop: 2 }}>{sum}</div>}
        {line.note && <div style={{ fontSize: 11, color: 'var(--brown-700)', marginTop: 4, fontStyle: 'italic' }}>“{line.note}”</div>}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
          <QtyStepper qty={line.qty} setQty={(q) => onChangeQty(q)} size="sm" />
          <button onClick={onRemove} className="press" style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 12, color: 'var(--brown-500)', padding: '4px 8px',
          }}>
            <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              <path d="M3 4h10M6 4V3a1 1 0 011-1h2a1 1 0 011 1v1M5 4l1 9h4l1-9"/>
            </svg>
            {_t(lang, 'remove')}
          </button>
        </div>
      </div>
    </div>
  );
}

function CartScreen({ lang, cart, setCart, onCheckout, onBrowse, tableNo }) {
  const subtotal = cart.reduce((s, l) => s + l.total, 0);
  const service = Math.round(subtotal * 0.0); // 0% — dine-in no service charge for this place
  const total = subtotal + service;

  if (cart.length === 0) {
    return (
      <div style={{ position: 'absolute', inset: 0, background: 'var(--cream-50)', display: 'flex', flexDirection: 'column' }}>
        <AppHeader title={_t(lang, 'cart_title')} subtitle={`${_t(lang, 'welcome_table')} ${tableNo}`} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 32px', textAlign: 'center' }}>
          <div style={{
            width: 110, height: 110, borderRadius: '50%',
            background: 'var(--cream-100)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 16, color: 'var(--brown-300)',
          }}>
            <svg width="46" height="46" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M6 7h13l-1.5 9a2 2 0 0 1-2 1.7H9.5a2 2 0 0 1-2-1.7L5.5 4H3"/>
              <circle cx="9" cy="20" r="1"/><circle cx="17" cy="20" r="1"/>
            </svg>
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, color: 'var(--brown-900)' }}>{_t(lang, 'cart_empty')}</div>
          <div style={{ fontSize: 13, color: 'var(--brown-500)', marginTop: 6 }}>{_t(lang, 'cart_empty_sub')}</div>
          <button onClick={onBrowse} className="press" style={{
            marginTop: 20, padding: '12px 22px',
            background: 'var(--terra)', color: 'white', borderRadius: 14,
            fontWeight: 600, fontSize: 14,
          }}>{_t(lang, 'cart_browse')}</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--cream-50)', overflow: 'auto' }} className="scroll-hide">
      <AppHeader title={_t(lang, 'cart_title')} subtitle={`${_t(lang, 'welcome_table')} ${tableNo} · ${cart.length} ${_t(lang, 'items')}`} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: '0 18px 16px' }}>
        {cart.map((line, i) => (
          <CartLine
            key={i}
            line={line}
            lang={lang}
            onRemove={() => setCart(cart.filter((_, j) => j !== i))}
            onChangeQty={(q) => {
              const u = [...cart];
              u[i] = { ...u[i], qty: q, total: u[i].unitPrice * q };
              setCart(u);
            }}
          />
        ))}
      </div>

      {/* totals */}
      <div style={{ padding: '0 18px 200px' }}>
        <div style={{
          background: 'var(--paper)', borderRadius: 18, padding: 16,
          border: '1px solid var(--cream-200)', display: 'flex', flexDirection: 'column', gap: 8,
        }}>
          <Row label={_t(lang, 'subtotal')} val={fmtBaht(subtotal)} />
          {service > 0 && <Row label={_t(lang, 'service')} val={fmtBaht(service)} sub />}
          <div style={{ borderTop: '1px dashed var(--cream-300)', paddingTop: 10, marginTop: 4 }}>
            <Row label={_t(lang, 'total')} val={fmtBaht(total)} big />
          </div>
        </div>
      </div>

      {/* Checkout CTA — floating above tab bar */}
      <div style={{
        position: 'absolute', bottom: 112, left: 18, right: 18, zIndex: 25,
      }}>
        <button onClick={() => onCheckout(total)} className="press" style={{
          width: '100%', padding: '15px 18px',
          background: 'var(--terra)', color: 'white',
          borderRadius: 18, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          boxShadow: '0 14px 30px -10px rgba(194,65,12,0.55)',
          gap: 10, whiteSpace: 'nowrap',
        }}>
          <span style={{ whiteSpace: 'nowrap' }}>{_t(lang, 'checkout')}</span>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, whiteSpace: 'nowrap' }}>{fmtBaht(total)}</span>
        </button>
      </div>
    </div>
  );
}

function Row({ label, val, sub, big }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
      <div style={{
        fontSize: big ? 15 : 14, color: sub ? 'var(--brown-500)' : 'var(--brown-700)',
        fontWeight: big ? 600 : 500, whiteSpace: 'nowrap',
      }}>{label}</div>
      <div style={{
        fontFamily: 'var(--font-display)',
        fontSize: big ? 24 : 16, fontWeight: 700,
        color: big ? 'var(--terra-700)' : 'var(--brown-900)',
        whiteSpace: 'nowrap',
      }}>{val}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CHECKOUT
// ─────────────────────────────────────────────────────────────
function CheckoutScreen({ lang, cart, total, tableNo, onBack, onConfirm }) {
  const [method, setMethod] = useState2('qr');

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--cream-50)', overflow: 'auto' }} className="scroll-hide">
      <AppHeader title={_t(lang, 'checkout_title')} subtitle={`${_t(lang, 'welcome_table')} ${tableNo}`} onBack={onBack} />

      {/* Compact order summary */}
      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          background: 'var(--paper)', borderRadius: 18, padding: 14,
          border: '1px solid var(--cream-200)',
        }}>
          <div style={{ fontSize: 12, color: 'var(--brown-500)', fontWeight: 600, letterSpacing: '0.04em', marginBottom: 8 }}>
            {_t(lang, 'items').toUpperCase()} ({cart.length})
          </div>
          {cart.map((line, i) => (
            <div key={i} style={{
              display: 'flex', justifyContent: 'space-between', gap: 8,
              padding: '6px 0',
              borderTop: i === 0 ? 'none' : '1px dashed var(--cream-200)',
            }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--brown-900)' }}>
                  {line.qty}× {line.name[lang]}
                </div>
                <div style={{ fontSize: 11, color: 'var(--brown-500)', marginTop: 1 }}>{summarizeItem(line, lang)}</div>
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, color: 'var(--brown-700)' }}>
                {fmtBaht(line.total)}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Payment method */}
      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          fontSize: 12, color: 'var(--brown-500)', fontWeight: 600,
          letterSpacing: '0.06em', padding: '0 4px 8px',
        }}>{_t(lang, 'pay_method').toUpperCase()}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { id: 'qr', title: _t(lang, 'pay_qr'), sub: _t(lang, 'pay_qr_sub'), icon: <QRSmall /> },
            { id: 'cash', title: _t(lang, 'pay_cash'), sub: _t(lang, 'pay_cash_sub'), icon: <CashIcon /> },
          ].map(m => {
            const active = method === m.id;
            return (
              <button key={m.id} onClick={() => setMethod(m.id)} className="press" style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 14px', borderRadius: 14,
                background: active ? 'var(--terra-100)' : 'var(--paper)',
                border: '2px solid ' + (active ? 'var(--terra)' : 'var(--cream-200)'),
                textAlign: 'left',
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10,
                  background: 'var(--cream-50)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--brown-700)',
                }}>{m.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--brown-900)' }}>{m.title}</div>
                  <div style={{ fontSize: 11, color: 'var(--brown-500)', marginTop: 1 }}>{m.sub}</div>
                </div>
                <div style={{
                  width: 22, height: 22, borderRadius: '50%',
                  background: active ? 'var(--terra)' : 'transparent',
                  border: '2px solid ' + (active ? 'var(--terra)' : 'var(--brown-300)'),
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {active && <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'white' }}/>}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* QR section */}
      {method === 'qr' && (
        <div style={{ padding: '0 18px 16px' }} className="fade-up">
          <div style={{
            background: 'linear-gradient(180deg, #FFFCF5 0%, #F5EBD7 100%)',
            borderRadius: 22, padding: 18, textAlign: 'center',
            border: '1px solid var(--cream-200)',
            boxShadow: 'var(--shadow-md)',
          }}>
            <div style={{ fontSize: 12, color: 'var(--brown-700)', fontWeight: 600, letterSpacing: '0.04em' }}>
              PromptPay · {_t(lang, 'scan_qr')}
            </div>
            <div style={{
              width: 200, height: 200, margin: '14px auto',
              background: 'white', borderRadius: 18, padding: 14,
              boxShadow: 'var(--shadow-md)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <QRGraphic />
            </div>
            <div style={{ fontSize: 11, color: 'var(--brown-500)' }}>คุณแม่ ชิดชนก</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, color: 'var(--brown-700)', marginTop: 2 }}>
              081-XXX-XX42
            </div>
            <div style={{
              marginTop: 14, padding: '10px 14px',
              background: 'var(--paper)', borderRadius: 12,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              border: '1px dashed var(--cream-300)',
            }}>
              <div style={{ fontSize: 12, color: 'var(--brown-500)' }}>{_t(lang, 'amount')}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: 'var(--terra-700)' }}>
                {fmtBaht(total)}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Confirm */}
      <div style={{ padding: '0 18px 200px' }}>
        <button onClick={() => onConfirm(method)} className="press" style={{
          width: '100%', padding: '16px 18px',
          background: 'var(--brown-900)', color: 'var(--cream-50)',
          borderRadius: 18, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          boxShadow: '0 14px 28px -10px rgba(42,26,14,0.5)',
        }}>
          <span>
            {method === 'qr' ? _t(lang, 'mark_paid') : _t(lang, 'confirm')}
          </span>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19 }}>{fmtBaht(total)}</span>
        </button>
        <div style={{ fontSize: 11, color: 'var(--brown-500)', textAlign: 'center', marginTop: 10 }}>
          {lang === 'th'
            ? 'หากชำระด้วย QR กรุณาแนบสลิปให้พนักงานตรวจสอบ'
            : 'If paying by QR, please show the slip to staff for verification.'}
        </div>
      </div>
    </div>
  );
}

function QRSmall() {
  return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="currentColor">
      <rect x="1" y="1" width="7" height="7" rx="1" fill="none" stroke="currentColor" strokeWidth="1.5"/>
      <rect x="14" y="1" width="7" height="7" rx="1" fill="none" stroke="currentColor" strokeWidth="1.5"/>
      <rect x="1" y="14" width="7" height="7" rx="1" fill="none" stroke="currentColor" strokeWidth="1.5"/>
      <rect x="3.5" y="3.5" width="2" height="2"/><rect x="16.5" y="3.5" width="2" height="2"/><rect x="3.5" y="16.5" width="2" height="2"/>
      <rect x="11" y="11" width="3" height="3"/><rect x="17" y="11" width="2" height="2"/><rect x="14" y="17" width="2" height="2"/><rect x="19" y="19" width="2" height="2"/>
    </svg>
  );
}
function CashIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="6" width="18" height="11" rx="2"/>
      <circle cx="11" cy="11.5" r="2.5"/>
      <path d="M5 9v.01M17 14v.01"/>
    </svg>
  );
}

// Pseudo-QR: deterministic grid
function QRGraphic() {
  const N = 21;
  const cells = useMemo2(() => {
    const arr = [];
    for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
      // finder squares
      const inFinder = (
        (x < 7 && y < 7) || (x > N-8 && y < 7) || (x < 7 && y > N-8)
      );
      if (inFinder) {
        const fx = x < 7 ? x : (N-1-x);
        const fy = y < 7 ? y : (N-1-y);
        const ring = (fx === 0 || fy === 0 || fx === 6 || fy === 6);
        const inner = (fx >= 2 && fx <= 4 && fy >= 2 && fy <= 4);
        arr.push({ x, y, on: ring || inner });
      } else {
        // pseudo random but stable
        const h = (x * 73856093) ^ (y * 19349663);
        arr.push({ x, y, on: (h & 7) > 3 });
      }
    }
    return arr;
  }, []);
  const size = 172;
  const s = size / N;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <rect width={size} height={size} fill="white"/>
      {cells.map((c, i) => c.on && <rect key={i} x={c.x*s} y={c.y*s} width={s} height={s} fill="#2A1A0E"/>)}
      {/* center logo */}
      <circle cx={size/2} cy={size/2} r="18" fill="white"/>
      <circle cx={size/2} cy={size/2} r="15" fill="var(--terra)"/>
      <text x={size/2} y={size/2 + 5} textAnchor="middle" fill="white" fontSize="14" fontFamily="Charm, serif" fontWeight="700">ม</text>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// ORDER STATUS
// ─────────────────────────────────────────────────────────────
function OrderStatusScreen({ lang, order, onReceipt, onMore, tableNo }) {
  // simulate progression: received → cooking → ready
  const stages = ['received', 'cooking', 'ready'];
  const [stageIdx, setStageIdx] = useState2(0);

  useEffect2(() => {
    if (stageIdx >= stages.length - 1) return;
    const timeouts = [];
    timeouts.push(setTimeout(() => setStageIdx(s => Math.min(s + 1, stages.length - 1)), 4500));
    return () => timeouts.forEach(clearTimeout);
  }, [stageIdx]);

  const labels = {
    received: { key: 'status_received', icon: <ReceivedIcon/>, etaTh: 'ครัวกำลังจัดเตรียม', etaEn: 'Kitchen is preparing' },
    cooking:  { key: 'status_cooking',  icon: <CookingIcon/>,  etaTh: 'กำลังปรุงอาหารด้วยใจ', etaEn: 'Cooking with care' },
    ready:    { key: 'status_ready',    icon: <ReadyIcon/>,    etaTh: 'พร้อมเสิร์ฟแล้ว', etaEn: 'Ready to serve' },
  };
  const cur = stages[stageIdx];
  const label = labels[cur];

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--cream-50)', overflow: 'auto' }} className="scroll-hide">
      <AppHeader title={_t(lang, 'status_title')} subtitle={`${_t(lang, 'order_no')} ${order.id}`} />

      {/* big status card */}
      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          background: cur === 'ready'
            ? 'linear-gradient(180deg, #DFE7CC 0%, #C7D8A4 100%)'
            : 'linear-gradient(180deg, #FBE3D2 0%, #F0C9A8 100%)',
          borderRadius: 24, padding: '24px 18px', textAlign: 'center',
          border: '1px solid rgba(154,51,10,0.18)',
          boxShadow: 'var(--shadow-md)',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            width: 96, height: 96, margin: '0 auto 14px',
            borderRadius: '50%',
            background: 'rgba(255,252,245,0.85)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: cur === 'ready' ? '#3F6212' : 'var(--terra)',
            boxShadow: 'inset 0 0 0 4px rgba(255,252,245,0.5), 0 8px 20px rgba(154,51,10,0.2)',
            position: 'relative',
          }}>
            {label.icon}
            {cur === 'cooking' && (
              <div style={{
                position: 'absolute', inset: -8, borderRadius: '50%',
                border: '3px solid var(--terra)', borderTopColor: 'transparent',
                animation: 'spin 1.4s linear infinite',
              }}/>
            )}
            <style>{`@keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }`}</style>
          </div>
          <div style={{
            fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 700,
            color: cur === 'ready' ? '#3F6212' : 'var(--terra-700)',
            lineHeight: 1.1,
          }}>{_t(lang, label.key)}</div>
          <div style={{ fontSize: 13, color: 'var(--brown-700)', marginTop: 6 }}>
            {lang === 'th' ? label.etaTh : label.etaEn}
          </div>
        </div>
      </div>

      {/* progress timeline */}
      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          background: 'var(--paper)', borderRadius: 18, padding: '16px 18px',
          border: '1px solid var(--cream-200)',
        }}>
          {stages.map((s, i) => {
            const done = i <= stageIdx;
            const isLast = i === stages.length - 1;
            return (
              <div key={s} style={{ display: 'flex', gap: 12, position: 'relative' }}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: '50%',
                    background: done ? (cur === 'ready' && isLast ? '#5F7A3C' : 'var(--terra)') : 'var(--cream-100)',
                    color: done ? 'white' : 'var(--brown-300)',
                    border: done ? 'none' : '2px solid var(--cream-300)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 13, fontWeight: 700, zIndex: 2,
                  }}>
                    {done ? (
                      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8l3.5 3.5L13 4"/></svg>
                    ) : i + 1}
                  </div>
                  {!isLast && (
                    <div style={{
                      width: 2, flex: 1, minHeight: 28,
                      background: done && i < stageIdx ? 'var(--terra)' : 'var(--cream-200)',
                      marginTop: -2,
                    }}/>
                  )}
                </div>
                <div style={{ flex: 1, paddingBottom: isLast ? 0 : 18 }}>
                  <div style={{
                    fontSize: 14, fontWeight: 600,
                    color: done ? 'var(--brown-900)' : 'var(--brown-300)',
                  }}>{_t(lang, labels[s].key)}</div>
                  <div style={{ fontSize: 11, color: 'var(--brown-500)', marginTop: 1 }}>
                    {done
                      ? (lang === 'th' ? labels[s].etaTh : labels[s].etaEn)
                      : (lang === 'th' ? 'รอดำเนินการ' : 'Pending')}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* order summary line */}
      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          background: 'var(--paper)', borderRadius: 18, padding: 14,
          border: '1px solid var(--cream-200)',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
            <span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'table')}</span>
            <span style={{ color: 'var(--brown-900)', fontWeight: 600 }}>{tableNo}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginTop: 6 }}>
            <span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'items')}</span>
            <span style={{ color: 'var(--brown-900)', fontWeight: 600 }}>{order.cart.length}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginTop: 6 }}>
            <span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'total')}</span>
            <span style={{ fontFamily: 'var(--font-display)', color: 'var(--terra-700)', fontWeight: 700, fontSize: 18 }}>
              {fmtBaht(order.total)}
            </span>
          </div>
        </div>
      </div>

      {/* CTAs */}
      <div style={{ padding: '0 18px 200px', display: 'flex', gap: 10 }}>
        <button onClick={onReceipt} className="press" style={{
          flex: 1, padding: '13px 14px',
          background: 'var(--paper)', color: 'var(--brown-900)',
          borderRadius: 14, fontWeight: 600, fontSize: 14,
          border: '1.5px solid var(--brown-900)',
        }}>{_t(lang, 'receipt')}</button>
        <button onClick={onMore} className="press" style={{
          flex: 1, padding: '13px 14px',
          background: 'var(--terra)', color: 'white',
          borderRadius: 14, fontWeight: 600, fontSize: 14,
        }}>{_t(lang, 'order_more')}</button>
      </div>
    </div>
  );
}

function ReceivedIcon() { return (
  <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 4h11l4 4v12H5z"/><path d="M16 4v4h4"/><path d="M9 13h7M9 17h5"/>
  </svg>
); }
function CookingIcon() { return (
  <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 13a7 7 0 0 1 14 0v1H5z"/><path d="M3 17h18v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
    <path d="M8 7c0-1 1-2 2-2M12 6c0-1 1-2 2-2"/>
  </svg>
); }
function ReadyIcon() { return (
  <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="9"/><path d="M8 12l3 3 5-6"/>
  </svg>
); }

// ─────────────────────────────────────────────────────────────
// RECEIPT
// ─────────────────────────────────────────────────────────────
function ReceiptScreen({ lang, order, tableNo, onBack }) {
  const date = new Date();
  const dateStr = lang === 'th'
    ? date.toLocaleDateString('th-TH', { day: '2-digit', month: 'long', year: 'numeric' })
    : date.toLocaleDateString('en-US', { day: '2-digit', month: 'long', year: 'numeric' });
  const timeStr = date.toLocaleTimeString(lang === 'th' ? 'th-TH' : 'en-US', { hour: '2-digit', minute: '2-digit' });

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#E0CCA0', overflow: 'auto', padding: '48px 18px 200px' }} className="scroll-hide">
      <div style={{
        position: 'absolute', top: 14, left: 14, zIndex: 5,
      }}>
        <button onClick={onBack} className="press" style={{
          width: 36, height: 36, borderRadius: 999,
          background: 'rgba(255,252,245,0.92)',
          border: '1px solid var(--cream-300)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--brown-700)',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
        </button>
      </div>

      {/* paper */}
      <div style={{
        background: 'var(--paper)',
        boxShadow: '0 30px 60px -20px rgba(42,26,14,0.4)',
        padding: '24px 22px 0', position: 'relative',
        backgroundImage:
          'repeating-linear-gradient(0deg, transparent 0 26px, rgba(94,56,22,0.04) 26px 27px)',
      }}>
        {/* top scallop */}
        <div style={{
          position: 'absolute', top: -10, left: 0, right: 0, height: 10,
          background: `radial-gradient(circle at 8px 0, transparent 7px, var(--paper) 7.5px)`,
          backgroundSize: '16px 10px',
        }}/>

        <div style={{ textAlign: 'center' }}>
          <div style={{
            fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 700,
            color: 'var(--brown-900)',
          }}>{_t(lang, 'brand')}</div>
          <div style={{ fontSize: 11, color: 'var(--brown-500)', marginTop: 2 }}>
            {lang === 'th' ? 'ตำรับคุณแม่ · 24 ถ.บางลำพู กรุงเทพฯ' : 'Mom\'s recipes · 24 Banglampu Rd., Bangkok'}
          </div>
          <div style={{ fontSize: 11, color: 'var(--brown-500)' }}>TAX ID 0-9999-99999-99-9</div>
        </div>

        <div style={{
          marginTop: 14, padding: '10px 0',
          borderTop: '1px dashed var(--brown-300)',
          borderBottom: '1px dashed var(--brown-300)',
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4,
          fontSize: 12,
        }}>
          <div><span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'receipt_no')}</span> <b>{order.id}</b></div>
          <div><span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'table')}</span> <b>{tableNo}</b></div>
          <div><span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'receipt_date')}</span> <b>{dateStr}</b></div>
          <div><span style={{ color: 'var(--brown-500)' }}>เวลา</span> <b>{timeStr}</b></div>
        </div>

        <div style={{ padding: '14px 0' }}>
          {order.cart.map((line, i) => (
            <div key={i} style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, fontWeight: 600, color: 'var(--brown-900)' }}>
                <span>{line.qty}× {line.name[lang]}</span>
                <span style={{ fontFamily: 'var(--font-display)' }}>{fmtBaht(line.total)}</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--brown-500)', paddingLeft: 14, marginTop: 1 }}>
                {summarizeItem(line, lang)}
              </div>
            </div>
          ))}
        </div>

        <div style={{
          borderTop: '1px dashed var(--brown-300)',
          padding: '12px 0',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
            <span style={{ color: 'var(--brown-500)' }}>{_t(lang, 'subtotal')}</span>
            <span>{fmtBaht(order.total)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, alignItems: 'baseline' }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>{_t(lang, 'total')}</span>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, color: 'var(--terra-700)' }}>
              {fmtBaht(order.total)}
            </span>
          </div>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            marginTop: 8, fontSize: 11, fontWeight: 600,
            color: 'var(--leaf)',
            background: 'var(--leaf-100)', padding: '4px 8px', borderRadius: 6,
          }}>
            <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8l3.5 3.5L13 4"/></svg>
            {_t(lang, 'paid')} · {order.paymentMethod === 'qr' ? 'QR PromptPay' : _t(lang, 'pay_cash')}
          </div>
        </div>

        <div style={{
          textAlign: 'center', padding: '16px 0 20px',
          fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700,
          color: 'var(--brown-700)',
          borderTop: '1px dashed var(--brown-300)',
        }}>
          {_t(lang, 'receipt_thanks')} ♥
        </div>

        {/* bottom scallop */}
        <div style={{ height: 10, position: 'relative',
          background: 'radial-gradient(circle at 8px 10px, transparent 7px, var(--paper) 7.5px)',
          backgroundSize: '16px 10px',
        }}/>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HISTORY
// ─────────────────────────────────────────────────────────────
function HistoryScreen({ lang, sessionOrders, tableNo }) {
  const [dbOrders, setDbOrders] = useState2([]);
  const [loadState, setLoadState] = useState2('loading'); // 'loading' | 'ok' | 'error'

  useEffect2(() => {
    fetch('/api/orders')
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) { setDbOrders(data); setLoadState('ok'); }
        else setLoadState('error');
      })
      .catch(() => setLoadState('error'));
  }, []);

  const sessionIds = new Set(sessionOrders.map(o => o.id));
  const today = new Date().toISOString().slice(0, 10);

  const fmtDate = (created_at, fresh) => {
    if (fresh) return _t(lang, 'today');
    const d = (created_at || '').slice(0, 10);
    if (d === today) return _t(lang, 'today');
    try {
      const dt = new Date(created_at);
      return lang === 'th'
        ? dt.toLocaleDateString('th-TH', { day: '2-digit', month: 'short', year: 'numeric' })
        : dt.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' });
    } catch (_) { return created_at?.slice(0, 10) || ''; }
  };

  // DB is authoritative; fallback to session + mock when offline
  const all = loadState === 'ok' && dbOrders.length > 0
    ? dbOrders.map(o => ({
        id: o.id,
        dateStr: fmtDate(o.created_at, sessionIds.has(o.id)),
        table: o.table_no,
        total: o.total,
        items: o.items,
        fresh: sessionIds.has(o.id),
      }))
    : [
        ...sessionOrders.map(o => ({
          id: o.id, dateStr: _t(lang, 'today'), table: tableNo,
          total: o.total,
          items: o.cart.map(l => ({ name: l.name, qty: l.qty, price: l.total })),
          fresh: true,
        })),
        ...window.MOCK_HISTORY.map(o => ({
          id: o.id, dateStr: lang === 'th' ? o.date : o.dateEn, table: o.table,
          total: o.total, items: o.items,
        })),
      ];

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--cream-50)', overflow: 'auto' }} className="scroll-hide">
      <AppHeader title={_t(lang, 'history_title')} subtitle={lang === 'th' ? 'ออเดอร์ของคุณ' : 'Your orders'} />

      {loadState === 'loading' && (
        <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--brown-500)', fontSize: 14 }}>
          {lang === 'th' ? 'กำลังโหลด...' : 'Loading…'}
        </div>
      )}

      <div style={{ padding: '0 18px 200px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {loadState !== 'loading' && all.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--brown-500)', padding: '40px 0', fontSize: 14 }}>
            {_t(lang, 'history_empty')}
          </div>
        )}
        {all.map(o => (
          <div key={o.id} style={{
            background: 'var(--paper)', borderRadius: 18, padding: 16,
            border: '1px solid var(--cream-200)',
            boxShadow: 'var(--shadow-sm)',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div>
                <div style={{
                  fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 700,
                  color: 'var(--brown-900)',
                }}>
                  #{o.id}
                  {o.fresh && (
                    <span style={{
                      marginLeft: 8, fontSize: 9, padding: '2px 6px', borderRadius: 4,
                      background: 'var(--leaf-100)', color: 'var(--leaf)',
                      fontFamily: 'var(--font-body)', fontWeight: 700, verticalAlign: 'middle',
                    }}>NEW</span>
                  )}
                </div>
                <div style={{ fontSize: 11, color: 'var(--brown-500)', marginTop: 2 }}>
                  {o.dateStr} · {_t(lang, 'table')} {o.table}
                </div>
              </div>
              <div style={{
                fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700,
                color: 'var(--terra-700)',
              }}>{fmtBaht(o.total)}</div>
            </div>
            <div style={{
              marginTop: 10, paddingTop: 10,
              borderTop: '1px dashed var(--cream-200)',
              display: 'flex', flexDirection: 'column', gap: 4,
            }}>
              {o.items.map((it, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                  <span style={{ color: 'var(--brown-700)' }}>{it.qty}× {it.name[lang]}</span>
                  <span style={{ color: 'var(--brown-500)' }}>{fmtBaht(it.price)}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  ItemDetail, CartScreen, CheckoutScreen, OrderStatusScreen, ReceiptScreen, HistoryScreen,
  summarizeItem,
});
