/* ============ JE BAR — Admin: Catalog + Settings ============ */

/* ---------------- Catalog management ---------------- */
function AdminCatalog({ cakes, setCakes, categories, setCategories, sync, fmt }) {
  const cats = categories || window.JEBAR.CATEGORIES;
  const realCats = cats.filter(c => c.id !== 'all');
  const [q, setQ] = React.useState('');
  const [filterCat, setFilterCat] = React.useState('all');
  const [dense, setDense] = React.useState(false);
  const [newCat, setNewCat] = React.useState('');
  const [mgrOpen, setMgrOpen] = React.useState(false);
  const [bulkOpen, setBulkOpen] = React.useState(false);
  const [editId, setEditId] = React.useState(null);
  const [createOpen, setCreateOpen] = React.useState(false);

  function readAsDataURL(file) {
    return new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsDataURL(file); });
  }

  async function createCake(data) {
    const id = 'new_' + Date.now().toString(36);
    const prices = data.prices || {};
    const firstPrice = ['1lb', '2lb', '3lb', '4lb', '5lb'].map(k => prices[k]).find(v => v > 0) || 0;
    let imageUrl = '';
    const cloud = window.JEAPI && window.JEAPI.ready() && window.JEAPI.hasSession();
    if (data.file) {
      if (cloud) {
        const ext = (data.file.name.match(/\.[^.]+$/) || ['.jpg'])[0].toLowerCase();
        imageUrl = await window.JEAPI.uploadImage(id + ext, data.file);
      } else {
        imageUrl = await readAsDataURL(data.file);
      }
      window.setCakeImg(id, imageUrl);
    }
    const cake = {
      id, name: data.name || 'เค้กใหม่', cat: data.cat || '', base: firstPrice,
      tag: data.tag || '', desc: data.desc || '', hidden: !data.showOnStore,
      image_url: imageUrl || null, prices
    };
    if (cloud && window.JEAPI.insertCake) await window.JEAPI.insertCake(cake);
    else window.addDraftCake(cake);
    setCakes(prev => [cake, ...prev]);
    setCreateOpen(false);
  }
  function saveCakeFull(id, data) {
    const prices = data.prices || {};
    const meta = data.meta || {};
    let base;
    if (meta.priceMode === 'custom' || meta.priceMode === 'single') {
      const ts = (meta.tiers || []).map(t => Number(t.price) || 0).filter(v => v > 0);
      base = ts.length ? Math.min.apply(null, ts) : 0;
    } else {
      base = ['1lb', '2lb', '3lb', '4lb', '5lb'].map(k => prices[k]).find(v => v > 0) || 0;
    }
    const patch = { name: data.name, cat: data.cat, desc: data.desc, prices, base: base || undefined, meta };
    setCakes(prev => prev.map(c => c.id === id ? { ...c, ...patch, base: base || c.base } : c));
    if (window.isDraftId && window.isDraftId(id)) window.updateDraftCake(id, { ...patch, base: base || undefined });
    if (sync) sync.cake(id, patch);
    setEditId(null);
  }

  function setPrice(id, v) {
    const n = parseInt(String(v).replace(/\D/g, ''), 10) || 0;
    setCakes(prev => prev.map(c => c.id === id ? { ...c, base: n } : c));
    if (window.isDraftId && window.isDraftId(id)) window.updateDraftCake(id, { base: n });
  }
  function setName(id, v) {
    setCakes(prev => prev.map(c => c.id === id ? { ...c, name: v } : c));
  }
  function commitName(id) {
    const c = cakes.find(x => x.id === id);
    if (!c) return;
    if (window.isDraftId && window.isDraftId(id)) window.updateDraftCake(id, { name: c.name });
    if (sync) sync.cake(id, { name: c.name });
  }
  function toggle(id) {
    const c = cakes.find(x => x.id === id);
    const nextHidden = !(c && c.hidden);
    setCakes(prev => prev.map(x => x.id === id ? { ...x, hidden: nextHidden } : x));
    if (window.isDraftId && window.isDraftId(id)) window.updateDraftCake(id, { hidden: nextHidden });
    if (sync) sync.cake(id, { hidden: nextHidden });
  }
  function setCakeCat(id, cat) {
    setCakes(prev => prev.map(c => c.id === id ? { ...c, cat } : c));
    if (window.isDraftId && window.isDraftId(id)) window.updateDraftCake(id, { cat });
    if (sync) sync.cake(id, { cat });
  }
  function delDraft(id) {
    if (!confirm('ลบเค้กนี้ถาวร? (ลบทั้งในเครื่องและคลาวด์)')) return;
    window.removeDraftCake(id);
    if (sync && window.JEAPI.deleteCake) window.JEAPI.deleteCake(id).catch(() => {});
    setCakes(prev => prev.filter(c => c.id !== id));
  }

  function delCake(id) {
    const c = cakes.find(x => x.id === id);
    if (!confirm('ลบเค้ก "' + (c ? c.name : '') + '" ถาวร? ลบออกจากทั้งระบบ (รวมหน้าร้าน)')) return;
    if (window.isDraftId && window.isDraftId(id)) window.removeDraftCake(id);
    else if (!sync && window.addDeletedCake) window.addDeletedCake(id); // tombstone เฉพาะโหมด local/demo
    if (sync && window.JEAPI.deleteCake) window.JEAPI.deleteCake(id).catch(() => {});
    setCakes(prev => prev.filter(c => c.id !== id));
  }

  async function purgeEmptyDrafts() {
    const drafts = cakes.filter(c => window.isDraftId && window.isDraftId(c.id));
    const junk = drafts.filter(c => !c.image_url && !window.CAKE_IMG[c.id] && !c.base && !(c.name && c.name.trim()));
    if (!junk.length) { alert('ไม่มีเค้กว่างที่ต้องลบ (รูปผลงานจะไม่ถูกลบ)'); return; }
    if (!confirm('ล้างเค้กว่าง (ไม่มีรูป/ชื่อ/ราคา) ' + junk.length + ' รายการ?')) return;
    const keep = (window.loadDraftCakes ? window.loadDraftCakes() : []).filter(d => !junk.some(j => j.id === d.id));
    if (window.saveDraftCakes) window.saveDraftCakes(keep);
    if (sync && window.JEAPI.deleteCake) { for (const j of junk) { try { await window.JEAPI.deleteCake(j.id); } catch (e) {} } }
    setCakes(prev => prev.filter(c => !junk.some(j => j.id === c.id)));
    setTimeout(() => alert('ล้างเค้กว่างแล้ว ' + junk.length + ' รายการ ✅'), 100);
  }

  async function deleteAllCakes() {
    if (!confirm('⚠️ ลบเค้กทั้งหมด ' + cakes.length + ' รายการ?\nใช้สำหรับเริ่มต้นใหม่ทั้งหมด — ลบจากคลาวด์ด้วย กู้คืนไม่ได้')) return;
    if (!confirm('ยืนยันอีกครั้ง — ลบเค้กทุกตัวจริงๆ ใช่ไหม?')) return;
    if (sync && window.JEAPI.deleteAllCakes) { try { await window.JEAPI.deleteAllCakes(); } catch (e) { console.warn('[JEBAR] deleteAll:', e.message); } }
    if (!sync) cakes.forEach(c => { if (!(window.isDraftId && window.isDraftId(c.id)) && window.addDeletedCake) window.addDeletedCake(c.id); });
    if (window.saveDraftCakes) window.saveDraftCakes([]);
    setCakes([]);
    setTimeout(() => alert('ลบเค้กทั้งหมดแล้ว — เริ่มต้นใหม่ได้เลยค่ะ ✅'), 100);
  }

  function addCategory() {
    const name = newCat.trim();
    if (!name) return;
    const id = 'cat_' + Date.now().toString(36);
    setCategories(prev => [...prev, { id, name }]);
    if (sync) sync.addCat({ id, name });
    setNewCat('');
  }
  function delCategory(id) {
    const used = cakes.filter(c => c.cat === id).length;
    if (used > 0 && !confirm('หมวดนี้มีเค้ก ' + used + ' รายการ — ลบแล้วเค้กจะย้ายไป “ไม่ระบุหมวด” ยืนยันไหม?')) return;
    setCategories(prev => prev.filter(c => c.id !== id));
    setCakes(prev => prev.map(c => c.cat === id ? { ...c, cat: '' } : c));
    if (sync) sync.delCat(id);
    if (filterCat === id) setFilterCat('all');
  }
  function renameCategory(id, name) { setCategories(prev => prev.map(c => c.id === id ? { ...c, name } : c)); }
  function commitRename(id) {
    if (!sync) return;
    const c = (categories || []).find(x => x.id === id);
    if (c) sync.renameCat({ id: c.id, name: c.name });
  }
  function commitPrice(id) {
    const c = cakes.find(x => x.id === id);
    if (!c) return;
    if (window.isDraftId && window.isDraftId(id)) window.updateDraftCake(id, { base: c.base });
    if (sync) sync.cake(id, { base: c.base });
  }

  // รหัสอ้างอิง jbcXXX — ใช้ตัวเดียวกับทั้งระบบ (window.cakeCodeMap คำนวณจาก JEBAR.CAKES)
  const codeMap = (window.cakeCodeMap ? window.cakeCodeMap() : {});

  let list = cakes.filter(c => filterCat === 'all' || c.cat === filterCat);
  if (q.trim()) { const s = q.trim().toLowerCase(); list = list.filter(c => c.name.toLowerCase().includes(s) || (c.desc || '').toLowerCase().includes(s) || (codeMap[c.id] || '').includes(s)); }

  const pad = dense ? '7px 14px' : '14px 18px';
  const thumb = dense ? 64 : 104;

  return (
    <div>
      {/* toolbar */}
      <div className="between" style={{ marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ position: 'relative', minWidth: 220 }}>
            <input className="input" value={q} onChange={e => setQ(e.target.value)}
              placeholder="ค้นหาเค้ก" style={{ paddingLeft: 38, padding: '9px 12px 9px 38px' }} />
            <Icon name="grid" size={16} style={{ position: 'absolute', left: 13, top: 11, color: 'var(--muted)' }} />
          </div>
          <select className="input" value={filterCat} onChange={e => setFilterCat(e.target.value)}
            style={{ width: 'auto', minWidth: 150, padding: '9px 12px', fontWeight: 600 }}>
            <option value="all">ทุกหมวด ({cakes.length})</option>
            {realCats.map(c => <option key={c.id} value={c.id}>{c.name} ({cakes.filter(x => x.cat === c.id).length})</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button className="tab" onClick={() => setDense(d => !d)} title="ปรับขนาดแถว">
            <Icon name="ruler" size={16} /> {dense ? 'แถวปกติ' : 'แถวกระชับ'}</button>
          {cakes.some(c => window.isDraftId && window.isDraftId(c.id) && !c.image_url && !window.CAKE_IMG[c.id] && !c.base && !(c.name && c.name.trim())) &&
            <button className="tab" onClick={purgeEmptyDrafts} title="ลบเค้กว่างที่ไม่มีรูป/ชื่อ/ราคา" style={{ color: '#B25543', borderColor: '#E2B7AE' }}>
              <Icon name="x" size={15} /> ล้างเค้กว่าง</button>}
          {cakes.length > 0 &&
            <button className="tab" onClick={deleteAllCakes} title="ลบเค้กทั้งหมด เริ่มต้นใหม่" style={{ color: '#fff', background: '#B25543', borderColor: '#B25543' }}>
              <Icon name="x" size={15} /> ลบทั้งหมด</button>}
          <button className={'tab' + (bulkOpen ? ' on' : '')} onClick={() => setBulkOpen(o => !o)}>
            <Icon name="spark" size={16} /> อัปโหลดรูปหลายรูป</button>
          <button className={'tab' + (mgrOpen ? ' on' : '')} onClick={() => setMgrOpen(o => !o)}>
            <Icon name="grid" size={16} /> จัดการหมวดหมู่</button>
        </div>
      </div>

      {/* bulk image upload */}
      {bulkOpen && <BulkImageUpload cakes={cakes} setCakes={setCakes} sync={sync} onClose={() => setBulkOpen(false)} />}

      {/* category manager */}
      {mgrOpen && (
        <div className="panel" style={{ marginBottom: 16 }}>
          <div className="panel__head"><h3>หมวดหมู่เค้ก</h3><div className="sp" />
            <span className="muted" style={{ fontSize: 13 }}>{realCats.length} หมวด</span></div>
          <div style={{ padding: 18 }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 16 }}>
              {realCats.map(c => (
                <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 7, background: 'var(--cream)',
                  border: '1px solid var(--line)', borderRadius: 999, padding: '5px 6px 5px 14px' }}>
                  <input value={c.name} onChange={e => renameCategory(c.id, e.target.value)}
                    onBlur={() => commitRename(c.id)}
                    style={{ border: 0, background: 'none', fontFamily: 'inherit', fontWeight: 700, fontSize: 14,
                      width: Math.max(60, c.name.length * 9 + 10), color: 'var(--brand)', outline: 'none' }} />
                  <span style={{ fontSize: 12, color: 'var(--muted)' }}>{cakes.filter(x => x.cat === c.id).length}</span>
                  <button onClick={() => delCategory(c.id)} title="ลบหมวด"
                    style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 2, display: 'grid' }}>
                    <Icon name="x" size={15} /></button>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 9, maxWidth: 380 }}>
              <input className="input" value={newCat} onChange={e => setNewCat(e.target.value)}
                placeholder="ชื่อหมวดใหม่ เช่น เค้กไขมันต่ำ" onKeyDown={e => { if (e.key === 'Enter') addCategory(); }} />
              <button className="btn btn--primary btn--sm" onClick={addCategory} disabled={!newCat.trim()}>
                <Icon name="plus" size={16} /> เพิ่ม</button>
            </div>
          </div>
        </div>
      )}

      <div className="between" style={{ marginBottom: 12 }}>
        <p className="muted" style={{ fontSize: 14 }}>
          แสดง {list.length} จาก {cakes.length} แบบ · แก้ราคา/หมวดได้ในตาราง
          {sync
            ? <span style={{ color: 'var(--good)', fontWeight: 700 }}> · บันทึกขึ้น Supabase อัตโนมัติ</span>
            : <span style={{ color: '#9A7322', fontWeight: 700 }}> · โหมดทดลอง (รีเฟรชแล้วรีเซ็ต — ล็อกอิน Supabase + สร้างตารางเพื่อบันทึกจริง)</span>}
        </p>
        <button className="btn btn--primary btn--sm" onClick={() => setCreateOpen(true)}>
          <Icon name="plus" size={18} /> เพิ่มเค้กใหม่</button>
      </div>

      <div className="panel">
        <div style={{ maxHeight: '64vh', overflowY: 'auto' }}>
          <table className="tbl">
            <thead style={{ position: 'sticky', top: 0, zIndex: 2, background: 'var(--card)' }}>
              <tr><th>เค้ก</th><th>หมวด</th><th>ราคาเริ่มต้น</th><th>แสดงหน้าร้าน</th></tr></thead>
            <tbody>
              {list.length === 0 && <tr><td colSpan={4} style={{ textAlign: 'center', color: 'var(--muted)', padding: 30 }}>ไม่พบเค้ก</td></tr>}
              {list.map(c => (
                <tr key={c.id} style={{ cursor: 'default', opacity: c.hidden ? .55 : 1 }}>
                  <td data-l="เค้ก" style={{ padding: pad }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <div style={{ width: thumb, height: thumb, borderRadius: dense ? 9 : 12, overflow: 'hidden', flexShrink: 0,
                        position: 'relative', background: 'linear-gradient(160deg,var(--primary-soft),#fff)' }}>
                        <CakeImg id={c.id} name={c.name} />
                      </div>
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--primary)', letterSpacing: .5, marginBottom: 3 }}>{codeMap[c.id]}</div>
                        {window.isDraftId && window.isDraftId(c.id)
                          ? <input value={c.name} onChange={e => setName(c.id, e.target.value)} onBlur={() => commitName(c.id)}
                              placeholder="ใส่ชื่อเค้ก…" style={{ border: '1px solid var(--line)', borderRadius: 8, padding: '5px 9px',
                                fontFamily: 'inherit', fontWeight: 700, fontSize: 14.5, width: '100%', maxWidth: 240, color: 'var(--brand)', background: 'var(--cream)' }} />
                          : <div className="nm">{c.name}</div>}
                        {window.isDraftId && window.isDraftId(c.id)
                          ? <span style={{ fontSize: 11.5, color: '#9A7322', fontWeight: 700 }}>🆕 เค้กใหม่ · ใส่ข้อมูลให้ครบแล้วเปิดแสดง</span>
                          : (!dense && <div className="sub" style={{ maxWidth: '34ch', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.desc}</div>)}
                      </div>
                    </div>
                  </td>
                  <td data-l="หมวด" style={{ padding: pad }}>
                    <select className="input" value={c.cat} onChange={e => setCakeCat(c.id, e.target.value)}
                      style={{ width: 'auto', minWidth: 120, padding: '7px 10px', fontWeight: 600, fontSize: 13.5 }}>
                      <option value="">— ไม่ระบุ —</option>
                      {realCats.map(x => <option key={x.id} value={x.id}>{x.name}</option>)}
                    </select>
                  </td>
                  <td data-l="ราคา" style={{ padding: pad }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span className="priceedit">
                        <input value={c.base} onChange={e => setPrice(c.id, e.target.value)}
                          onBlur={() => commitPrice(c.id)} inputMode="numeric" />
                        <span className="cur">บาท</span>
                      </span>
                      <button className="tab" onClick={() => setEditId(c.id)} title="แก้ไขข้อมูล + ราคา 5 ขนาด"
                        style={{ padding: '6px 10px', fontSize: 12.5 }}>
                        <Icon name="ruler" size={14} /> แก้เต็ม</button>
                    </div>
                    {c.prices && Object.keys(c.prices).some(k => c.prices[k] > 0) &&
                      <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                        {['1lb','2lb','3lb','4lb','5lb'].filter(k => c.prices[k] > 0).length} ขนาด</div>}
                  </td>
                  <td data-l="แสดง" style={{ padding: pad }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <button className={'switch' + (!c.hidden ? ' on' : '')} onClick={() => toggle(c.id)}
                        aria-label="toggle"><i></i></button>
                      <button onClick={() => delCake(c.id)} title="ลบเค้กนี้ถาวร"
                        style={{ border: 0, background: 'none', cursor: 'pointer', color: '#C07A6B', padding: 2, display: 'grid' }}>
                        <Icon name="x" size={16} /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {createOpen && <CreateCakeModal cats={realCats} onSave={createCake} onClose={() => setCreateOpen(false)} />}
      {editId && <EditCakeModal cake={cakes.find(c => c.id === editId)} cats={realCats}
        fmt={fmt} onSave={saveCakeFull} onClose={() => setEditId(null)} />}
    </div>
  );
}

/* ---------------- Create cake (name/category/prices/image) ---------------- */
function CreateCakeModal({ cats, onSave, onClose }) {
  const SIZES = window.JEBAR.SIZES;
  const [name, setName] = React.useState('');
  const [cat, setCat] = React.useState(cats[0] ? cats[0].id : '');
  const [desc, setDesc] = React.useState('');
  const [prices, setPrices] = React.useState({});
  const [file, setFile] = React.useState(null);
  const [preview, setPreview] = React.useState('');
  const [showOnStore, setShowOnStore] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  function setP(id, v) { setPrices(prev => ({ ...prev, [id]: parseInt(String(v).replace(/\D/g, ''), 10) || 0 })); }
  function pickFile(f) {
    if (!f) return;
    setFile(f);
    setPreview(URL.createObjectURL(f));
  }
  async function submit() {
    setErr('');
    if (!name.trim()) { setErr('กรอกชื่อเค้กก่อนนะคะ'); return; }
    if (!Object.keys(prices).some(k => prices[k] > 0)) { setErr('ใส่ราคาอย่างน้อย 1 ขนาดก่อนนะคะ'); return; }
    setBusy(true);
    try {
      await onSave({ name: name.trim(), cat, desc: desc.trim(), prices, file, showOnStore });
    } catch (e) {
      setErr(e.message || 'บันทึกเค้กไม่สำเร็จ');
      setBusy(false);
    }
  }

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 620, gridTemplateColumns: '220px 1fr' }} onClick={e => e.stopPropagation()}>
        <button className="modal__x" onClick={onClose}><Icon name="x" size={20} /></button>
        <div className="modal__art" style={{ minHeight: 260 }}>
          {preview ? <img src={preview} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> :
            <div style={{ display: 'grid', placeItems: 'center', width: '100%', height: '100%', color: 'var(--muted)', fontWeight: 700 }}>เลือกรูปเค้ก</div>}
        </div>
        <div className="modal__body" style={{ padding: '28px 26px' }}>
          <h2 style={{ fontSize: 23, marginBottom: 4 }}>เพิ่มเค้กใหม่</h2>
          <p className="muted" style={{ fontSize: 13.5, marginBottom: 18 }}>บันทึกชื่อ ราคา หมวด และรูปในครั้งเดียว</p>

          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>ชื่อเค้ก</label>
            <input className="input" style={{ marginTop: 6 }} value={name} onChange={e => setName(e.target.value)} placeholder="เช่น เค้กสตรอว์เบอร์รีสด" />
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>รูปเค้ก</label>
            <input className="input" style={{ marginTop: 6 }} type="file" accept="image/*" onChange={e => pickFile(e.target.files && e.target.files[0])} />
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>หมวดหมู่</label>
            <select className="input" style={{ marginTop: 6 }} value={cat} onChange={e => setCat(e.target.value)}>
              <option value="">-- ไม่ระบุ --</option>
              {cats.map(x => <option key={x.id} value={x.id}>{x.name}</option>)}
            </select>
          </div>

          <label style={{ fontWeight: 700, fontSize: 13.5 }}>ราคาตามขนาด (บาท)</label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 8, marginBottom: 12 }}>
            {SIZES.map(s => (
              <span key={s.id} className="priceedit">
                <input value={prices[s.id] || ''} onChange={e => setP(s.id, e.target.value)} inputMode="numeric" placeholder={s.label} />
                <span className="cur">บาท</span>
              </span>
            ))}
          </div>

          <textarea className="input" rows={2} style={{ resize: 'vertical', marginBottom: 12 }} value={desc}
            onChange={e => setDesc(e.target.value)} placeholder="คำอธิบาย/รายละเอียดเค้ก" />
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 700, fontSize: 13.5, marginBottom: 12 }}>
            <input type="checkbox" checked={showOnStore} onChange={e => setShowOnStore(e.target.checked)} /> แสดงหน้าร้านทันที
          </label>
          {err && <p style={{ color: '#B25543', fontSize: 13, fontWeight: 700, marginBottom: 12 }}>{err}</p>}
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn--ghost btn--lg" style={{ flex: 1 }} onClick={onClose} disabled={busy}>ยกเลิก</button>
            <button className="btn btn--primary btn--lg" style={{ flex: 2 }} onClick={submit} disabled={busy}>
              <Icon name="check" size={18} /> {busy ? 'กำลังบันทึก...' : 'บันทึกเค้ก'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
/* ---------------- Edit cake (ชื่อ/หมวด/ราคา 5 ขนาด/คำอธิบาย) ---------------- */
function EditCakeModal({ cake, cats, fmt, onSave, onClose }) {
  const SIZES = window.JEBAR.SIZES;
  const [name, setName] = React.useState(cake.name || '');
  const [cat, setCat] = React.useState(cake.cat || '');
  const [desc, setDesc] = React.useState(cake.desc || '');
  const [prices, setPrices] = React.useState(() => {
    const p = Object.assign({}, cake.prices || {});
    // ถ้ายังไม่มีราคาแยกขนาด เดาจาก base × ตัวคูณ ให้เริ่มกรอกง่าย
    if (!Object.keys(p).some(k => p[k] > 0) && cake.base > 0)
      SIZES.forEach(s => { p[s.id] = Math.round(cake.base * s.mult / 10) * 10; });
    return p;
  });
  function setP(id, v) { setPrices(prev => ({ ...prev, [id]: parseInt(String(v).replace(/\D/g, ''), 10) || 0 })); }

  const m0 = cake.meta || {};
  const [priceMode, setPriceMode] = React.useState(m0.priceMode || 'pound');
  const [tiers, setTiers] = React.useState(() => (m0.tiers && m0.tiers.length) ? m0.tiers.map(t => ({ label: t.label || '', price: t.price || '' })) : [{ label: '', price: '' }]);
  const [tags, setTags] = React.useState((m0.tags || []).join(', '));
  const [occasions, setOccasions] = React.useState((m0.occasions || []).join(', '));
  const [flavors, setFlavors] = React.useState((m0.flavors || []).join(', '));
  const [highlight, setHighlight] = React.useState(m0.highlight || '');
  function setTier(i, k, v) { setTiers(prev => prev.map((t, j) => j === i ? { ...t, [k]: k === 'price' ? String(v).replace(/\D/g, '') : v } : t)); }
  function addTier() { setTiers(prev => [...prev, { label: '', price: '' }]); }
  function delTier(i) { setTiers(prev => prev.filter((_, j) => j !== i)); }
  function toArr(s) { return String(s).split(',').map(x => x.trim()).filter(Boolean); }
  function buildMeta() {
    return {
      priceMode,
      tiers: priceMode === 'pound' ? [] : tiers.filter(t => t.label || t.price).map(t => ({ label: t.label, price: Number(t.price) || 0 })),
      tags: toArr(tags), occasions: toArr(occasions), flavors: toArr(flavors), highlight: highlight.trim()
    };
  }

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 560, gridTemplateColumns: '1fr' }} onClick={e => e.stopPropagation()}>
        <button className="modal__x" onClick={onClose}><Icon name="x" size={20} /></button>
        <div className="modal__body" style={{ padding: '28px 26px', maxHeight: '85vh', overflowY: 'auto' }}>
          <h2 style={{ fontSize: 23, marginBottom: 4 }}>แก้ไขข้อมูลเค้ก</h2>
          <p className="muted" style={{ fontSize: 13.5, marginBottom: 16 }}>ใส่ราคาแยกแต่ละขนาด — ปล่อยว่าง/0 = ไม่มีขนาดนั้น</p>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
            <div style={{ width: 84, height: 84, borderRadius: 12, overflow: 'hidden', flexShrink: 0, border: '1px solid var(--line)' }}>
              <CakeImg id={cake.id} name={cake.name} />
            </div>
            {window.cakeCode && <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--primary)', letterSpacing: .5 }}>{window.cakeCode(cake.id)}</span>}
          </div>

          <div className="field" style={{ marginBottom: 14 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>ชื่อเค้ก</label>
            <input className="input" style={{ marginTop: 6 }} value={name} onChange={e => setName(e.target.value)} placeholder="เช่น เค้กสตรอว์เบอร์รีสด" />
          </div>
          <div className="field" style={{ marginBottom: 14 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>หมวดหมู่</label>
            <select className="input" style={{ marginTop: 6 }} value={cat} onChange={e => setCat(e.target.value)}>
              <option value="">— ไม่ระบุ —</option>
              {cats.map(x => <option key={x.id} value={x.id}>{x.name}</option>)}
            </select>
          </div>

          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>วิธีคิดราคา</label>
            <select className="input" style={{ marginTop: 6 }} value={priceMode} onChange={e => setPriceMode(e.target.value)}>
              <option value="pound">ตามขนาดปอนด์ (เค้กปกติ)</option>
              <option value="custom">กำหนดเอง — ชิ้น/กล่อง (คัพเค้ก ฯลฯ)</option>
              <option value="single">ราคาเดียว</option>
            </select>
          </div>

          {priceMode === 'pound' &&
            <div style={{ display: 'grid', gap: 8, marginBottom: 16 }}>
              {SIZES.map(s => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ width: 96, flexShrink: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>{s.label}</div>
                    <div className="muted" style={{ fontSize: 10.5 }}>{s.note}</div>
                  </div>
                  <span className="priceedit" style={{ flex: 1 }}>
                    <input value={prices[s.id] || ''} onChange={e => setP(s.id, e.target.value)} inputMode="numeric"
                      placeholder="0" style={{ width: '100%' }} />
                    <span className="cur">บาท</span>
                  </span>
                </div>
              ))}
            </div>}

          {priceMode === 'custom' &&
            <div style={{ display: 'grid', gap: 8, marginBottom: 12 }}>
              {tiers.map((t, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input className="input" value={t.label} onChange={e => setTier(i, 'label', e.target.value)}
                    placeholder="เช่น 6 ชิ้น / กล่องเล็ก" style={{ flex: 1 }} />
                  <span className="priceedit" style={{ width: 120 }}>
                    <input value={t.price} onChange={e => setTier(i, 'price', e.target.value)} inputMode="numeric" placeholder="0" style={{ width: '100%' }} />
                    <span className="cur">บาท</span>
                  </span>
                  <button onClick={() => delTier(i)} style={{ border: 0, background: 'none', cursor: 'pointer', color: '#B25543', padding: 4 }}><Icon name="x" size={16} /></button>
                </div>
              ))}
              <button className="btn btn--ghost btn--sm" style={{ justifySelf: 'start' }} onClick={addTier}><Icon name="plus" size={15} /> เพิ่มขนาด/แพ็ก</button>
            </div>}

          {priceMode === 'single' &&
            <div style={{ marginBottom: 12 }}>
              <span className="priceedit" style={{ width: 160 }}>
                <input value={tiers[0] ? tiers[0].price : ''} onChange={e => setTier(0, 'price', e.target.value)} inputMode="numeric" placeholder="0" style={{ width: '100%' }} />
                <span className="cur">บาท</span>
              </span>
            </div>}

          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>จุดเด่น (สั้นๆ)</label>
            <input className="input" style={{ marginTop: 6 }} value={highlight} onChange={e => setHighlight(e.target.value)}
              placeholder="เช่น สตรอว์เบอร์รีสดเกรดพรีเมียม" />
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>แท็ก (คั่นด้วย , )</label>
            <input className="input" style={{ marginTop: 6 }} value={tags} onChange={e => setTags(e.target.value)}
              placeholder="ขายดี, มินิมอล, ธีมการ์ตูน" />
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>โอกาส (คั่นด้วย , )</label>
            <input className="input" style={{ marginTop: 6 }} value={occasions} onChange={e => setOccasions(e.target.value)}
              placeholder="วันเกิด, ครบรอบ, รับปริญญา" />
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>รสเนื้อเค้ก (คั่นด้วย , )</label>
            <input className="input" style={{ marginTop: 6 }} value={flavors} onChange={e => setFlavors(e.target.value)}
              placeholder="วานิลลา, ช็อกโกแลต, เรดเวลเวต" />
          </div>

          <div className="field" style={{ marginBottom: 18 }}>
            <label style={{ fontWeight: 700, fontSize: 13.5 }}>คำอธิบาย / หมายเหตุ</label>
            <textarea className="input" rows={3} style={{ marginTop: 6, resize: 'vertical' }} value={desc}
              onChange={e => setDesc(e.target.value)} placeholder="รายละเอียดเค้ก รส เนื้อ จุดเด่น หรือหมายเหตุการสั่ง" />
          </div>

          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn--ghost btn--lg" style={{ flex: 1 }} onClick={onClose}>ยกเลิก</button>
            <button className="btn btn--primary btn--lg" style={{ flex: 2 }}
              onClick={() => onSave(cake.id, { name, cat, desc, prices, meta: buildMeta() })}>
              <Icon name="check" size={18} /> บันทึก</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Settings: DIY pricing & shop ---------------- */
function AdminSettings({ diy, setDiy, shop, setShop, fmt }) {
  const DIY = window.JEBAR.DIY;
  function setAdd(group, id, v) {
    const n = parseInt(String(v).replace(/\D/g, ''), 10) || 0;
    setDiy(prev => ({ ...prev, [group + ':' + id]: n }));
  }
  function getAdd(group, opt) {
    const k = group + ':' + opt.id;
    return diy[k] !== undefined ? diy[k] : opt.add;
  }

  const groups = [
    ['size', 'ขนาดเค้ก'], ['tiers', 'จำนวนชั้น'], ['sponge', 'รสเนื้อเค้ก'],
    ['cream', 'ครีม / ไส้'], ['theme', 'หน้าเค้ก / ธีม'], ['plate', 'ป้ายข้อความ'], ['extras', 'ของแต่งเพิ่มเติม']
  ];

  return (
    <div style={{ maxWidth: 920 }}>
      {/* shop settings */}
      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="panel__head"><h3>ตั้งค่าร้าน</h3></div>
        <div style={{ padding: 20 }}>
          <div className="set-grid">
            <div className="set-item">
              <label>ค่าจัดส่ง (เดลิเวอรี)</label>
              <div className="sub">คิดเพิ่มต่อออเดอร์</div>
              <div className="inrow"><input value={shop.delivery} inputMode="numeric"
                onChange={e => setShop({ ...shop, delivery: parseInt(e.target.value.replace(/\D/g, '') || 0, 10) })} />
                <span className="unit">บาท</span></div>
            </div>
            <div className="set-item">
              <label>สั่งล่วงหน้าขั้นต่ำ</label>
              <div className="sub">จำนวนวันก่อนวันรับ</div>
              <div className="inrow"><input value={shop.leadDays} inputMode="numeric"
                onChange={e => setShop({ ...shop, leadDays: parseInt(e.target.value.replace(/\D/g, '') || 0, 10) })} />
                <span className="unit">วัน</span></div>
            </div>
            <div className="set-item">
              <label>ขั้นต่ำเดลิเวอรีฟรี</label>
              <div className="sub">ยอดที่ส่งฟรี (0 = ปิด)</div>
              <div className="inrow"><input value={shop.freeOver} inputMode="numeric"
                onChange={e => setShop({ ...shop, freeOver: parseInt(e.target.value.replace(/\D/g, '') || 0, 10) })} />
                <span className="unit">บาท</span></div>
            </div>
          </div>
        </div>
      </div>

      {/* DIY add-on costs */}
      <div className="panel">
        <div className="panel__head"><h3>ต้นทุน/ราคาตัวเลือก DIY</h3>
          <div className="sp" />
          <span className="muted" style={{ fontSize: 13 }}>ใช้คำนวณราคาในหน้า “ออกแบบเอง”</span></div>
        <div style={{ padding: 20, display: 'grid', gap: 22 }}>
          {groups.map(([g, label]) => (
            <div key={g}>
              <div style={{ fontWeight: 800, fontSize: 14.5, marginBottom: 11, color: 'var(--brand)' }}>{label}</div>
              <div className="set-grid">
                {DIY[g].options.map(opt => (
                  <div className="set-item" key={opt.id}>
                    <label>{opt.nm}</label>
                    <div className="sub">{g === 'color' ? 'ไม่มีค่าใช้จ่าย' : (opt.sub || '\u00a0')}</div>
                    <div className="inrow">
                      <span className="unit">+</span>
                      <input value={getAdd(g, opt)} inputMode="numeric" disabled={g === 'color'}
                        onChange={e => setAdd(g, opt.id, e.target.value)} />
                      <span className="unit">บาท</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
      <p className="muted center" style={{ fontSize: 12.5, marginTop: 16 }}>
        * ต้นแบบ — การแก้ไขจะอยู่จนกว่าจะรีเฟรช (เวอร์ชันจริงจะบันทึกลงฐานข้อมูล)</p>
    </div>
  );
}

/* ---------------- Bulk image upload (อัปโหลดรูปหลายรูป) ---------------- */
function matchCake(filename, cakes) {
  const base = filename.replace(/\.[^.]+$/, '').toLowerCase().replace(/[\s_-]+/g, '');
  // 1) filename contains cake id (c01, c12…)
  let hit = cakes.find(c => base.includes(String(c.id).toLowerCase()));
  if (hit) return hit.id;
  // 2) cake name (no spaces) appears in filename or vice versa
  hit = cakes.find(c => {
    const n = (c.name || '').toLowerCase().replace(/[\s_-]+/g, '');
    return n.length > 1 && (base.includes(n) || n.includes(base));
  });
  return hit ? hit.id : '';
}

function BulkImageUpload({ cakes, setCakes, sync, onClose }) {
  const cloud = window.JEAPI && window.JEAPI.ready() && window.JEAPI.hasSession();
  const [items, setItems] = React.useState([]); // {file, preview, cakeId, status}
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(0);
  const fileRef = React.useRef(null);

  function addFiles(fileList) {
    const arr = Array.from(fileList).filter(f => f.type.startsWith('image/'));
    setItems(prev => {
      const seen = {};
      prev.forEach(it => { seen[it.file.name + '|' + it.file.size] = true; });
      const next = [];
      let dup = 0;
      arr.forEach(f => {
        const key = f.name + '|' + f.size;
        if (seen[key]) { dup++; return; }   // กันไฟล์ซ้ำในรอบเดียวกัน
        seen[key] = true;
        next.push({ file: f, preview: URL.createObjectURL(f), cakeId: matchCake(f.name, cakes), status: '' });
      });
      if (dup) setTimeout(() => alert('ข้ามรูปซ้ำ ' + dup + ' รูป (ชื่อ+ขนาดไฟล์ซ้ำกัน) — ระบบข้ามให้แล้วค่ะ'), 100);
      return prev.concat(next);
    });
  }
  function setRowCake(i, cakeId) { setItems(prev => prev.map((it, k) => k === i ? { ...it, cakeId } : it)); }
  function setAllNew() { setItems(prev => prev.map(it => ({ ...it, cakeId: '__new__' }))); }
  function removeRow(i) { setItems(prev => prev.filter((_, k) => k !== i)); }

  function readAsDataURL(file) {
    return new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsDataURL(file); });
  }

  async function saveAll() {
    const ready = items.filter(it => it.cakeId);
    if (!ready.length) { alert('เลือกว่าแต่ละรูปเป็นเค้กไหนก่อนนะคะ'); return; }
    // กันเลือกเค้กเดิมซ้ำหลายรูป (ไม่นับ "สร้างใหม่")
    const counts = {};
    ready.forEach(it => { if (it.cakeId !== '__new__') counts[it.cakeId] = (counts[it.cakeId] || 0) + 1; });
    const dupCake = Object.keys(counts).filter(k => counts[k] > 1);
    if (dupCake.length) {
      const nm = (cakes.find(c => c.id === dupCake[0]) || {}).name || '';
      if (!confirm('มีเค้ก "' + nm + '" ถูกเลือกซ้ำ ' + counts[dupCake[0]] + ' รูป — รูปท้ายสุดจะทับรูปก่อนหน้า ต้องการไปต่อไหม?')) return;
    }
    // กันสร้างเค้กใหม่เยอะเกินโดยไม่ตั้งใจ (อัปทั้งอัลบั้ม)
    const newCount = ready.filter(it => it.cakeId === '__new__').length;
    if (newCount >= 8 && !confirm('คุณกำลังสร้าง "เค้กใหม่" ' + newCount + ' รายการพร้อมกัน\n(แต่ละรูป = 1 เค้กใหม่)\n\nถ้าเป็นรูปของเค้กตัวเดียวกันหลายมุม ควรเลือกเค้กเดิมแทน ไม่ใช่สร้างใหม่ทุกรูป\n\nยืนยันสร้าง ' + newCount + ' เค้กใหม่?')) return;
    setBusy(true); setDone(0);
    let n = 0;
    const newDrafts = [];
    const failedUploads = [];
    for (let i = 0; i < items.length; i++) {
      const it = items[i];
      if (!it.cakeId) continue;
      setItems(prev => prev.map((x, k) => k === i ? { ...x, status: 'up' } : x));
      try {
        const targetId = it.cakeId === '__new__' ? ('new_' + Date.now() + '_' + i) : it.cakeId;
        let url;
        if (cloud) {
          const ext = (it.file.name.match(/\.[^.]+$/) || ['.jpg'])[0].toLowerCase();
          const path = targetId + ext;   // path คงที่ต่อเค้ก → อัปซ้ำจะเขียนทับ ไม่เกิดรูปขยะ
          url = await window.JEAPI.uploadImage(path, it.file);
        } else {
          url = await readAsDataURL(it.file); // fallback: เก็บในเครื่อง (จำกัดพื้นที่)
        }
        window.setCakeImg(targetId, url);
        if (it.cakeId === '__new__') {
          const draft = { id: targetId, name: '', cat: '', base: 0, tag: '', desc: '', hidden: false, image_url: url };
          window.addDraftCake(draft);
          if (cloud && sync && window.JEAPI.insertCake) { try { await window.JEAPI.insertCake(draft); } catch (e) { console.warn('[JEBAR] sync เค้กใหม่ขึ้น cloud ไม่สำเร็จ:', e.message); } }
          newDrafts.push(draft);
        } else if (cloud) { await window.JEAPI.updateCake(it.cakeId, { image_url: url }); }
        setItems(prev => prev.map((x, k) => k === i ? { ...x, status: 'ok' } : x));
        n++; setDone(n);
      } catch (ex) {
        failedUploads.push({ index: i, err: ex.message || String(ex) });
        setItems(prev => prev.map((x, k) => k === i ? { ...x, status: 'err', err: ex.message } : x));
      }
    }
    // sync แผนที่รูปทั้งหมดขึ้น cloud (ให้เครื่องอื่นเห็น)
    if (cloud) {
      try { const map = JSON.parse(localStorage.getItem('jebar_cake_imgs_v1') || '{}'); await window.JEAPI.saveImageMap(map); } catch (e) {}
    }
    setCakes(prev => prev.concat(newDrafts)); // เพิ่มเค้กใหม่เข้าตาราง + re-render
    setBusy(false);
    // สรุปผล — ถ้ามีรูปอัปไม่สำเร็จ แจ้งสาเหตุให้ชัด
    const failed = failedUploads;
    if (failed.length) {
      const msg = (failed[0].err || '');
      let hint = '';
      if (/404|not found|bucket/i.test(msg)) hint = '\n\nสาเหตุ: ยังไม่ได้สร้าง bucket รูป — ให้รัน supabase-schema-images.sql ใน Supabase ก่อนค่ะ';
      else if (/403|denied|unauthor|row-level|policy/i.test(msg)) hint = '\n\nสาเหตุ: สิทธิ์ไม่พอ — ลองล็อกอินแอดมินใหม่ แล้วรัน supabase-schema-images.sql ให้ครบค่ะ';
      setTimeout(() => alert('อัปรูปไม่สำเร็จ ' + failed.length + ' รูป\nรายละเอียด: ' + msg + hint), 200);
      return;
    }
    if (newDrafts.length) setTimeout(() => alert('เพิ่มเค้กใหม่ ' + newDrafts.length + ' รายการ (ซ่อนไว้) — เลื่อนลงไปที่ตารางด้านล่าง ใส่ชื่อ/ราคา/หมวด แล้วกดเปิดแสดงหน้าร้านค่ะ'), 200);
  }

  const assigned = items.filter(it => it.cakeId).length;

  return (
    <div className="panel" style={{ marginBottom: 16 }}>
      <div className="panel__head">
        <h3>อัปโหลดรูปเค้กหลายรูป</h3><div className="sp" />
        <button onClick={onClose} style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--muted)', display: 'grid' }}><Icon name="x" size={18} /></button>
      </div>
      <div style={{ padding: 18 }}>
        {!cloud &&
          <div className="demo-note" style={{ marginTop: 0, marginBottom: 14 }}>
            <Icon name="spark" size={18} style={{ flexShrink: 0 }} />
            <span><b>ยังไม่ได้ล็อกอิน Supabase</b> — รูปจะเก็บในเครื่องนี้เท่านั้น (พื้นที่จำกัด).
              ล็อกอินแอดมิน + รัน <code>supabase-schema-images.sql</code> เพื่อเก็บขึ้นคลาวด์ใช้ได้ทุกเครื่องค่ะ</span>
          </div>}

        {/* dropzone */}
        <div onClick={() => fileRef.current && fileRef.current.click()}
          onDragOver={e => { e.preventDefault(); }} onDrop={e => { e.preventDefault(); addFiles(e.dataTransfer.files); }}
          style={{ border: '2px dashed var(--line)', borderRadius: 'var(--r)', padding: '26px 18px', textAlign: 'center',
            cursor: 'pointer', background: 'var(--cream)', transition: '.15s' }}>
          <Icon name="spark" size={26} style={{ color: 'var(--primary)' }} />
          <div style={{ fontWeight: 800, marginTop: 8, fontSize: 15.5 }}>ลากรูปวางที่นี่ หรือคลิกเพื่อเลือกหลายรูป</div>
          <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>เลือกได้ทีละหลายรูปพร้อมกัน · ระบบจะเดาว่าแต่ละรูปเป็นเค้กไหนให้</div>
          <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: 'none' }}
            onChange={e => { addFiles(e.target.files); e.target.value = ''; }} />
        </div>

        {items.length > 0 && <>
          <div className="between" style={{ margin: '16px 0 10px' }}>
            <span className="muted" style={{ fontSize: 13.5 }}>{items.length} รูป · จับคู่แล้ว {assigned}</span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="btn btn--primary btn--sm" onClick={setAllNew} disabled={busy} title="ตั้งทุกรูปเป็นเค้กใหม่ทีเดียว">
                <Icon name="plus" size={15} /> ตั้งทั้งหมดเป็นเค้กใหม่</button>
              <button className="btn btn--ghost btn--sm" onClick={() => setItems([])} disabled={busy}>ล้างทั้งหมด</button>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(180px,1fr))', gap: 12 }}>
            {items.map((it, i) => (
              <div key={i} style={{ border: '1px solid var(--line)', borderRadius: 'var(--r)', overflow: 'hidden', background: 'var(--card)' }}>
                <div style={{ position: 'relative', aspectRatio: '4/3', background: '#0001' }}>
                  <img src={it.preview} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  <button onClick={() => removeRow(i)} disabled={busy}
                    style={{ position: 'absolute', top: 6, right: 6, width: 26, height: 26, borderRadius: '50%', border: 0,
                      background: 'rgba(0,0,0,.55)', color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center' }}><Icon name="x" size={14} /></button>
                  {it.status === 'ok' && <span style={{ position: 'absolute', bottom: 6, left: 6, background: 'var(--good)', color: '#fff', fontSize: 11, fontWeight: 800, padding: '2px 8px', borderRadius: 999 }}>✓ บันทึกแล้ว</span>}
                  {it.status === 'up' && <span style={{ position: 'absolute', bottom: 6, left: 6, background: 'var(--primary)', color: '#fff', fontSize: 11, fontWeight: 800, padding: '2px 8px', borderRadius: 999 }}>กำลังอัปโหลด…</span>}
                  {it.status === 'err' && <span style={{ position: 'absolute', bottom: 6, left: 6, background: '#B25543', color: '#fff', fontSize: 11, fontWeight: 800, padding: '2px 8px', borderRadius: 999 }}>ผิดพลาด</span>}
                </div>
                <div style={{ padding: 8 }}>
                  <select className="input" value={it.cakeId} onChange={e => setRowCake(i, e.target.value)}
                    style={{ padding: '7px 9px', fontSize: 13, fontWeight: 600 }}>
                    <option value="">— เลือกเค้ก —</option>
                    <option value="__new__">➕ สร้างเค้กใหม่ (ใส่ข้อมูลทีหลัง)</option>
                    {cakes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
              </div>
            ))}
          </div>
          <div className="between" style={{ marginTop: 16 }}>
            <span className="muted" style={{ fontSize: 13 }}>{busy ? ('กำลังบันทึก ' + done + '/' + assigned + '…') : (cloud ? 'เก็บขึ้นคลาวด์ ใช้ได้ทุกเครื่อง' : 'เก็บในเครื่องนี้')}</span>
            <button className="btn btn--primary" onClick={saveAll} disabled={busy || !assigned}>
              <Icon name="check" size={18} /> บันทึกรูปทั้งหมด ({assigned})</button>
          </div>
        </>}
      </div>
    </div>
  );
}

Object.assign(window, { AdminCatalog, AdminSettings });