/* ============ JE BAR — Admin: Ingredients & Cost ============ */

function ConnBanner({ source }) {
  const live = source === 'supabase' || source === 'jebar-data';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px', borderRadius: 'var(--r)',
      background: live ? '#E7ECDF' : '#FBEBD2', border: '1px solid ' + (live ? '#CDE0C0' : '#F0DDB6'),
      marginBottom: 18, fontSize: 13.5, fontWeight: 600, color: live ? '#5E7A45' : '#9A7322' }}>
      <span style={{ width: 9, height: 9, borderRadius: '50%', background: 'currentColor' }} />
      {source === 'jebar-data'
        ? 'เชื่อมต่อ JEBAR DATA สำเร็จ — วัตถุดิบ/สูตร/ต้นทุนดึงจากระบบหลังร้านจริง (แก้ไขในโปรแกรม JEBAR DATA)'
        : live
          ? 'เชื่อมต่อ Supabase สำเร็จ — ต้นทุนดึงจากฐานข้อมูลจริง'
          : 'กำลังใช้ข้อมูลตัวอย่าง (ยังเชื่อม Supabase ไม่ได้ / ยังไม่มีตาราง) — รัน supabase-schema.sql แล้วรีเฟรช'}
    </div>
  );
}

function AdminIngredients({ data, setData, fmt }) {
  const C = window.JECOST;
  const J = window.JEBAR;
  const [markup, setMarkup] = React.useState(C.MARKUP);
  const [tab, setTab] = React.useState(window.__costTab || 'ing'); // ing | cost | calc
  React.useEffect(() => { if (window.__costTab) { setTab(window.__costTab); window.__costTab = null; } }, []);
  const [expand, setExpand] = React.useState(null);

  if (!data) return <p className="muted">กำลังโหลดข้อมูลต้นทุน…</p>;
  const { ingredients, recipes, source } = data;

  function setCost(id, v) {
    const n = parseFloat(String(v).replace(/[^\d.]/g, '')) || 0;
    setData(prev => ({ ...prev, ingredients: prev.ingredients.map(x => x.id === id ? { ...x, unit_cost: n } : x) }));
    // เวอร์ชันจริง: ยิงอัปเดตกลับ Supabase
    if (window.JECOST.isConfigured()) window.JECOST.sbUpdateIngredientCost(id, n);
  }

  // group ingredients by category
  const cats = [];
  ingredients.forEach(i => { if (!cats.includes(i.category)) cats.push(i.category); });

  // cost table for catalog cakes
  const costRows = J.CAKES.map(c => {
    const bd = C.costBreakdown(c.id, ingredients, recipes, '1lb');
    const sug = C.suggestedPrice(bd.total, markup);
    return { cake: c, cost: bd.total, rows: bd.rows, suggested: sug, current: c.base, margin: C.marginPct(bd.total, c.base) };
  });

  return (
    <div>
      <ConnBanner source={source} />

      <div className="tabs" style={{ marginBottom: 18 }}>
        <button className={'tab' + (tab === 'ing' ? ' on' : '')} onClick={() => setTab('ing')}>วัตถุดิบ ({ingredients.length})</button>
        <button className={'tab' + (tab === 'cost' ? ' on' : '')} onClick={() => setTab('cost')}>ต้นทุนเค้ก ({J.CAKES.length})</button>
        <button className={'tab' + (tab === 'calc' ? ' on' : '')} onClick={() => setTab('calc')}>เครื่องคิดต้นทุน</button>
      </div>

      {tab === 'calc' && <CostCalculator ingredients={ingredients} recipes={recipes} fmt={fmt} defaultMarkup={C.MARKUP} />}

      {tab === 'ing' && (
        <div className="panel">
          <div className="panel__head"><h3>ราคาวัตถุดิบ</h3><div className="sp" />
            <span className="muted" style={{ fontSize: 13 }}>แก้ราคาแล้วต้นทุนเค้กอัปเดตทันที</span></div>
          <table className="tbl">
            <thead><tr><th>วัตถุดิบ</th><th>หมวด</th><th>หน่วย</th><th>ต้นทุน/หน่วย</th></tr></thead>
            <tbody>
              {ingredients.map(i => (
                <tr key={i.id} style={{ cursor: 'default' }}>
                  <td data-l="วัตถุดิบ"><span className="nm">{i.name}</span><div className="sub">{i.id}</div></td>
                  <td data-l="หมวด"><span className="sub" style={{ fontWeight: 700, color: 'var(--brand)' }}>{i.category}</span></td>
                  <td data-l="หน่วย"><span className="sub">ต่อ {i.unit}</span></td>
                  <td data-l="ต้นทุน">
                    <span className="priceedit">
                      <input value={i.unit_cost} onChange={e => setCost(i.id, e.target.value)} inputMode="decimal" />
                      <span className="cur">฿/{i.unit}</span>
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'cost' && (
        <div>
          <div className="set-item" style={{ maxWidth: 320, marginBottom: 18 }}>
            <label>มาร์จิน (ราคาขาย = ต้นทุน × ?)</label>
            <div className="sub">ใช้คำนวณราคาขายแนะนำ</div>
            <div className="inrow">
              <input value={markup} inputMode="decimal"
                onChange={e => setMarkup(parseFloat(e.target.value.replace(/[^\d.]/g, '')) || 0)} />
              <span className="unit">เท่า</span>
            </div>
          </div>

          <div className="panel">
            <div className="panel__head"><h3>ต้นทุน & ราคาขาย (เค้กฐาน 1 ปอนด์)</h3></div>
            <table className="tbl">
              <thead><tr><th>เค้ก</th><th>ต้นทุนวัตถุดิบ</th><th>ราคาขายแนะนำ</th><th>ราคาปัจจุบัน</th><th>กำไรขั้นต้น</th></tr></thead>
              <tbody>
                {costRows.map(r => (
                  <React.Fragment key={r.cake.id}>
                    <tr onClick={() => setExpand(r.cake.id === expand ? null : r.cake.id)} style={{ cursor: 'pointer' }}>
                      <td data-l="เค้ก">
                        <span className="nm">{r.cake.name}</span>
                        <div className="sub" style={{ color: 'var(--primary)', fontWeight: 700 }}>
                          {expand === r.cake.id ? '▾ ซ่อนสูตร' : '▸ ดูสูตร/วัตถุดิบ'}</div>
                      </td>
                      <td data-l="ต้นทุน"><span style={{ fontWeight: 700 }}>{J.formatMoney(Math.round(r.cost), fmt)}</span></td>
                      <td data-l="แนะนำ"><span className="price" style={{ fontFamily: 'var(--font-head)', fontWeight: 700, color: 'var(--primary)' }}>{J.formatMoney(r.suggested, fmt)}</span></td>
                      <td data-l="ปัจจุบัน">{J.formatMoney(r.current, fmt)}</td>
                      <td data-l="กำไร"><span className="stp" style={{ background: r.margin >= 65 ? '#E7ECDF' : '#FBEBD2', color: r.margin >= 65 ? '#5E7A45' : '#9A7322' }}>{r.margin}%</span></td>
                    </tr>
                    {expand === r.cake.id && (
                      <tr style={{ cursor: 'default' }}>
                        <td colSpan={5} style={{ background: 'var(--cream)', padding: '4px 18px 14px' }}>
                          <div style={{ display: 'grid', gap: 4, maxWidth: 560 }}>
                            {r.rows.map(b => (
                              <div key={b.id} style={{ display: 'flex', justifyContent: 'space-between',
                                fontSize: 13.5, padding: '5px 0', borderBottom: '1px dashed var(--line)' }}>
                                <span className="muted">{b.name} · {b.qty} {b.unit} × {J.formatMoney(b.unit_cost, fmt)}</span>
                                <span style={{ fontWeight: 700 }}>{J.formatMoney(Math.round(b.cost), fmt)}</span>
                              </div>
                            ))}
                            <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 6, fontWeight: 800 }}>
                              <span>รวมต้นทุน</span><span>{J.formatMoney(Math.round(r.cost), fmt)}</span>
                            </div>
                          </div>
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          </div>
          <p className="muted center" style={{ fontSize: 12.5, marginTop: 14 }}>
            ระบบ “ออกแบบกับโจ” และ “ออกแบบเอง” ใช้ชุดต้นทุนนี้ในการประเมินราคาให้ลูกค้า</p>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AdminIngredients, ConnBanner });

/* ---------------- Cost Calculator (เครื่องคิดต้นทุนเค้กสั่งทำ) ---------------- */
function CostCalculator({ ingredients, recipes, fmt, defaultMarkup }) {
  const J = window.JEBAR;
  const SKEY = 'jebar_quote_calc_v1', QKEY = 'jebar_quotes_v1';
  const init = (() => { try { return JSON.parse(localStorage.getItem(SKEY) || 'null') || {}; } catch (e) { return {}; } })();
  const [comps, setComps] = React.useState(init.comps || []);     // สูตรฐาน/ส่วนประกอบ {label, qty, unitCost}
  const [rows, setRows] = React.useState(init.rows || []);        // วัตถุดิบ {ing, qty}
  const [pkgRows, setPkgRows] = React.useState(init.pkgRows || []);  // แพ็กเกจ {id, qty}
  const [other, setOther] = React.useState(init.other || 0);
  const [labor, setLabor] = React.useState(init.labor || 0);
  const [markup, setMarkup] = React.useState(String(init.markup != null ? init.markup : (defaultMarkup || 3.3)));
  const [cakeImg, setCakeImg] = React.useState(init.cakeImg || '');
  const [refImgs, setRefImgs] = React.useState(init.refImgs || []);
  const [customer, setCustomer] = React.useState(init.customer || '');
  const [phone, setPhone] = React.useState(init.phone || '');
  const [cakeName, setCakeName] = React.useState(init.cakeName || '');
  const [qtyNum, setQtyNum] = React.useState(init.qtyNum != null ? init.qtyNum : 1);
  const [unit, setUnit] = React.useState(init.unit || 'ปอนด์');
  const [requirements, setRequirements] = React.useState(init.requirements || '');
  // รูปเค้กในแคตตาล็อก (สำหรับเลือกลิงก์มาใส่ใบเสนอราคา)
  const catalogPics = React.useMemo(() => (window.JEBAR.CAKES || [])
    .filter(c => !c.hidden && ((window.CAKE_IMG && window.CAKE_IMG[c.id]) || c.image_url))
    .map(c => ({ id: c.id, name: c.name || 'เค้ก', code: (window.cakeCode ? window.cakeCode(c.id) : ''), img: (window.CAKE_IMG && window.CAKE_IMG[c.id]) || c.image_url })), []);
  const [codeInput, setCodeInput] = React.useState('');
  function normCode(s) {
    s = String(s).trim().toLowerCase().replace(/\s/g, '');
    if (/^\d+$/.test(s)) return 'jbc' + s.padStart(3, '0');
    if (/^jbc\d+$/.test(s)) return 'jbc' + s.slice(3).padStart(3, '0');
    return s;
  }
  function addByCode() {
    const code = normCode(codeInput);
    const c = window.cakeByCode && window.cakeByCode(code);
    if (!c) { alert('ไม่พบรหัส ' + code); return; }
    const img = (window.CAKE_IMG && window.CAKE_IMG[c.id]) || c.image_url;
    if (img) { setCakeImg(img); setCodeInput(''); } else alert('เค้กนี้ยังไม่มีรูป');
  }
  function addRefImg(file) { if (!file) return; const r = new FileReader(); r.onload = () => setRefImgs(prev => [...prev, r.result]); r.readAsDataURL(file); }
  function delRefImg(i) { setRefImgs(prev => prev.filter((_, k) => k !== i)); }
  const [packages, setPackages] = React.useState([]);
  const [qidx, setQidx] = React.useState(null);
  const [quotes, setQuotes] = React.useState(() => { try { return JSON.parse(localStorage.getItem(QKEY) || '[]'); } catch (e) { return []; } });
  const [busy, setBusy] = React.useState(false);
  const [importText, setImportText] = React.useState('');
  const [showCost, setShowCost] = React.useState(false); // พับส่วนคิดต้นทุน (เฉพาะแอดมิน)
  const [jobId, setJobId] = React.useState(init.jobId || null);
  const [jobNo, setJobNo] = React.useState(init.jobNo || null);

  function nextNo() { return (quotes.reduce((m, q) => Math.max(m, Number(q.no) || 0), 0) || 0) + 1; }
  function jobCode(n) { return n ? 'JBW-' + String(n).padStart(4, '0') : '(ใบใหม่)'; }
  function collectData() {
    return { comps, rows, pkgRows, other, labor, markup, cakeImg, refImgs, customer, phone, cakeName, qtyNum, unit, requirements };
  }
  function applyData(d) {
    d = d || {};
    setComps(d.comps || []); setRows(d.rows || []); setPkgRows(d.pkgRows || []);
    setOther(d.other || 0); setLabor(d.labor || 0); setMarkup(String(d.markup != null ? d.markup : (defaultMarkup || 3.3)));
    setCakeImg(d.cakeImg || ''); setRefImgs(d.refImgs || []);
    setCustomer(d.customer || ''); setPhone(d.phone || '');
    setCakeName(d.cakeName || ''); setQtyNum(d.qtyNum != null ? d.qtyNum : 1); setUnit(d.unit || 'ปอนด์');
    setRequirements(d.requirements || '');
  }
  function resetFields() { applyData({}); }
  function newJob() {
    if ((comps.length || customer || cakeName) && !confirm('เปิดใบงานใหม่? (ข้อมูลที่ยังไม่บันทึกจะหาย)')) return;
    resetFields(); setJobId(null); setJobNo(nextNo());
  }
  function openJob(q) {
    applyData(q.data || {}); setJobId(q.id); setJobNo(q.no);
  }
  async function saveJob() {
    if (busy) return;
    if (!cloud) { alert('ต้องล็อกอินแอดมินเพื่อบันทึกใบงานขึ้นคลาวด์'); return; }
    setBusy(true);
    try {
      const no = jobNo || nextNo();
      const items = [{ name: itemTitle || 'เค้กสั่งทำตามแบบ' }];
      const row = await window.JEAPI.saveQuote({ id: jobId, quoteNo: no, customer, phone, totalCost, price, requirements, items, data: collectData() });
      setJobId(row.id); setJobNo(row.quote_no || no);
      await reloadQuotes();
      alert('บันทึกใบงาน ' + jobCode(row.quote_no || no) + ' แล้ว ✓');
    } catch (e) { alert('บันทึกใบงานไม่สำเร็จ: ' + e.message); }
    setBusy(false);
  }

  // นำเข้าจากสรุปของโจ (AI) → แยกใส่ช่องอัตโนมัติ
  function importSummary() {
    const t = importText || '';
    if (!t.trim()) return;
    const field = (label) => { const m = t.match(new RegExp(label + '[^:：\\n]*[:：]\\s*([^\\n]*)')); return m ? m[1].trim() : ''; };
    const clean = (v) => (v && v !== '(ยังไม่ระบุ)') ? v : '';
    const cakeType = clean(field('ชนิดเค้ก'));
    const deco = clean(field('ข้อความบนเค้ก') || field('รูปแบบการแต่ง'));
    const size = clean(field('ขนาด'));
    const date = clean(field('วันรับ'));
    const who = field('ช่องทางติดต่อกลับ') || field('ชื่อผู้สั่ง');
    const special = clean(field('ความต้องการพิเศษ'));
    const ref = clean(field('แบบอ้างอิง'));
    const phoneM = t.match(/0\d[\d\- ]{7,}/); if (phoneM) setPhone(phoneM[0].replace(/[^\d]/g, ''));
    const name = (who.split('/')[0] || '').replace(/โทร|เบอร์/g, '').trim();
    if (name && name !== '(ยังไม่ระบุ)') setCustomer(name);
    if (cakeType) setCakeName(cakeType);
    if (size) {
      const numM = size.match(/[\d.]+/); if (numM) setQtyNum(parseFloat(numM[0]) || 1);
      if (/ชิ้น/.test(size)) setUnit('ชิ้น'); else if (/กล่อง/.test(size)) setUnit('กล่อง'); else if (/ปอนด์/.test(size)) setUnit('ปอนด์');
    }
    const req = [deco, date ? ('รับ: ' + date) : '', special ? ('พิเศษ: ' + special) : '', ref ? ('อ้างอิง: ' + ref) : ''].filter(Boolean).join('\n');
    if (req) setRequirements(req);
    setImportText('');
  }

  const cloud = window.JEAPI && window.JEAPI.ready() && window.JEAPI.hasSession();
  async function reloadQuotes() {
    if (!cloud) return;
    try {
      const rows = await window.JEAPI.listQuotes();
      setQuotes(rows.map(r => ({ id: r.id, no: r.quote_no, customer: r.customer, phone: r.phone, price: r.price, data: r.data || {}, title: (r.quote_no ? 'JBW-' + String(r.quote_no).padStart(4, '0') + ' · ' : '') + (r.customer || 'ใบงาน') + ' · ' + J.formatMoney(r.price, fmt), dataUrl: r.image_url, createdAt: r.created_at, cloud: true })));
    } catch (e) { console.warn('[JEBAR] โหลดใบเสนอราคา cloud ไม่สำเร็จ:', e.message); }
  }

  React.useEffect(() => {
    if (window.JEBRIDGE) window.JEBRIDGE.load().then(d => setPackages((d.db && d.db.packages) || [])).catch(() => {});
    if (window.JEQUOTE) window.JEQUOTE.load().then(setQidx).catch(() => {});
    reloadQuotes();
  }, []);

  // จำสถานะข้ามรีเฟรช (ไม่ล้างจนกว่าจะกด "ล้างข้อมูล")
  React.useEffect(() => {
    try { localStorage.setItem(SKEY, JSON.stringify({ comps, rows, pkgRows, other, labor, markup, cakeImg, refImgs, customer, phone, cakeName, qtyNum, unit, requirements, jobId, jobNo })); } catch (e) {}
  }, [comps, rows, pkgRows, other, labor, markup, cakeImg, refImgs, customer, phone, cakeName, qtyNum, unit, requirements, jobId, jobNo]);

  function pickImg(file, set) { if (!file) return; const r = new FileReader(); r.onload = () => set(r.result); r.readAsDataURL(file); }
  async function delQuote(id) {
    if (id === jobId) { setJobId(null); setJobNo(null); }
    const q = quotes.find(x => x.id === id);
    if (q && q.cloud && window.JEAPI) { try { await window.JEAPI.deleteQuote(id); } catch (e) {} await reloadQuotes(); return; }
    const next = quotes.filter(x => x.id !== id); setQuotes(next); try { localStorage.setItem(QKEY, JSON.stringify(next)); } catch (e) {}
  }

  // สูตรฐานเบเกอรี่จาก JEBAR DATA (พร้อมต้นทุนต่อหน่วยที่คำนวณจากวัตถุดิบ)
  const baseList = React.useMemo(() => {
    if (!qidx || !window.JEQUOTE) return [];
    return Object.keys(qidx.batch).map(id => {
      const b = qidx.batch[id];
      const c = window.JEQUOTE.costOfUsage(qidx, qidx.batchLines[id] || []);
      return { id: id, name: b.name || id, unit: b.outputUnit || 'หน่วย', unitCost: Math.round(c.total * 100) / 100 };
    });
  }, [qidx]);

  // ── สูตรฐาน/ส่วนประกอบ ──
  function setComp(i, patch) { setComps(prev => prev.map((r, k) => k === i ? { ...r, ...patch } : r)); }
  function addComp() { setComps(prev => [...prev, { label: '', qty: 1, unitCost: 0 }]); }
  function addBase(id) { const b = baseList.find(x => x.id === id); if (b) setComps(prev => [...prev, { label: b.name, qty: 1, unitCost: b.unitCost }]); }
  function delComp(i) { setComps(prev => prev.filter((_, k) => k !== i)); }

  // ── วัตถุดิบ ──
  function ingOf(id) { return ingredients.find(x => x.id === id); }
  function setRow(i, patch) { setRows(prev => prev.map((r, k) => k === i ? { ...r, ...patch } : r)); }
  function addRow() { setRows(prev => [...prev, { ing: ingredients[0] ? ingredients[0].id : '', qty: 0 }]); }
  function delRow(i) { setRows(prev => prev.filter((_, k) => k !== i)); }

  // ── แพ็กเกจ ──
  function pkgOf(id) { return packages.find(p => p.id === id); }
  function setPkgRow(i, patch) { setPkgRows(prev => prev.map((r, k) => k === i ? { ...r, ...patch } : r)); }
  function addPkgRow() { if (packages[0]) setPkgRows(prev => [...prev, { id: packages[0].id, qty: 1 }]); }
  function delPkgRow(i) { setPkgRows(prev => prev.filter((_, k) => k !== i)); }

  const compLines = comps.map(r => ({ ...r, cost: (parseFloat(r.qty) || 0) * (parseFloat(r.unitCost) || 0) }));
  const compTotal = compLines.reduce((s, l) => s + l.cost, 0);
  const ingLines = rows.map(r => { const ing = ingOf(r.ing); const q = parseFloat(r.qty) || 0; return { ...r, ing, q, cost: ing ? q * ing.unit_cost : 0 }; });
  const material = ingLines.reduce((s, l) => s + l.cost, 0);
  const pkgLines = pkgRows.map(r => { const p = pkgOf(r.id); const q = parseFloat(r.qty) || 0; return { ...r, p, q, cost: p ? q * (Number(p.costPerPiece) || 0) : 0 }; });
  const pkgTotal = pkgLines.reduce((s, l) => s + l.cost, 0);
  const recipeCost = compTotal + material;       // ส่วนที่คิดมาร์จิน
  const extra = (parseFloat(other) || 0) + (parseFloat(labor) || 0) + pkgTotal; // ผ่านตามต้นทุน
  const totalCost = recipeCost + extra;
  const price = Math.round((recipeCost * (parseFloat(markup) || 0) + extra) / 10) * 10;
  const margin = price ? Math.round((1 - totalCost / price) * 100) : 0;
  const itemTitle = [String(cakeName).trim(), (Number(qtyNum) ? (qtyNum + ' ' + unit) : '')].filter(Boolean).join(' ');

  const cats = [];
  ingredients.forEach(i => { if (!cats.includes(i.category)) cats.push(i.category); });

  async function exportQuote() {
    if (busy || !window.JEDOC) return;
    setBusy(true);
    try {
      // รายการในใบเสนอราคา = ชื่อเค้ก + ขนาด/จำนวน (ไม่โชว์สูตรฐาน/ต้นทุนให้ลูกค้า)
      const items = [{ name: itemTitle || 'เค้กสั่งทำตามแบบ' }];
      const who = customer + (phone ? ' · โทร ' + phone : '');
      const no = jobNo || nextNo();           // เลขใบงาน = เลขใบเสนอราคา (ตัวเดียวกัน)
      const noStr = jobCode(no);
      const dataUrl = await window.JEDOC.buildQuoteImage({ cakeImg, extraImgs: refImgs, customer: who, requirements, items, price, quoteNo: noStr });
      const a = document.createElement('a'); a.href = dataUrl; a.download = noStr + '-' + (customer || 'JEBAR') + '.png'; a.click();
      if (cloud) {
        // บันทึกทั้งใบงาน (upsert) + รูปใบเสนอราคา ขึ้น Supabase
        try { const row = await window.JEAPI.saveQuote({ id: jobId, quoteNo: no, customer, phone, totalCost, price, requirements, items, data: collectData(), dataUrl }); setJobId(row.id); setJobNo(row.quote_no || no); await reloadQuotes(); }
        catch (e) { alert('บันทึกขึ้นคลาวด์ไม่สำเร็จ (ดาวน์โหลดไฟล์ให้แล้ว): ' + e.message); }
      } else { alert('ดาวน์โหลดไฟล์ให้แล้ว — ล็อกอินแอดมินเพื่อบันทึกใบงานขึ้นคลาวด์'); }
    } catch (e) { alert('สร้างรูปใบเสนอราคาไม่สำเร็จ: ' + e.message); }
    setBusy(false);
  }

  return (
   <div>
    <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, alignItems: 'start' }} className="calc-grid">
      <div className="panel">
        <div className="panel__head" style={{ flexWrap: 'wrap', gap: 8 }}>
          <h3>ใบงาน {jobCode(jobNo)}</h3><div className="sp" style={{ flex: 1 }} />
          <button className="btn btn--ghost btn--sm" onClick={newJob}><Icon name="plus" size={14} /> เปิดใบงานใหม่</button>
          <button className="btn btn--primary btn--sm" onClick={saveJob} disabled={busy}><Icon name="check" size={14} /> บันทึกใบงาน</button>
        </div>

        {/* ข้อมูลใบเสนอราคา (เรียงเป็นขั้นตอน) */}
        <div style={{ padding: 18, borderBottom: '1px solid var(--line)', background: 'var(--cream)' }}>

          {/* ก) นำเข้าจากสรุปของโจ */}
          <div className="muted" style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>ก · วางสรุปจากโจ แล้วกดนำเข้า (กรอกช่องให้อัตโนมัติ)</div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', marginBottom: 16 }}>
            <textarea className="input" rows={2} value={importText} onChange={e => setImportText(e.target.value)}
              placeholder="วางข้อความสรุป 7 ข้อจากโจที่นี่…" style={{ flex: 1, resize: 'vertical' }} />
            <button className="btn btn--dark btn--sm" onClick={importSummary} disabled={!importText.trim()} style={{ flexShrink: 0 }}>
              <Icon name="arrow" size={15} /> นำเข้า</button>
          </div>

          {/* ข) ข้อมูลลูกค้า */}
          <div className="muted" style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>ข · ลูกค้า</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
            <input className="input" value={customer} onChange={e => setCustomer(e.target.value)} placeholder="ชื่อลูกค้า" style={{ flex: 1 }} />
            <input className="input" value={phone} onChange={e => setPhone(e.target.value)} placeholder="เบอร์โทร" inputMode="tel" style={{ width: 130 }} />
          </div>

          {/* ค) รายการ + รายละเอียด */}
          <div className="muted" style={{ fontSize: 12.5, fontWeight: 700, margin: '8px 0 6px' }}>ค · รายการเค้ก & รายละเอียด</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
            <input className="input" value={cakeName} onChange={e => setCakeName(e.target.value)} placeholder="ชื่อเค้ก เช่น เค้กผลไม้" style={{ flex: 1, minWidth: 160 }} />
            <span className="qty">
              <button onClick={() => setQtyNum(n => Math.max(0, (Number(n) || 0) - 1))}><Icon name="minus" size={15} /></button>
              <input value={qtyNum} inputMode="decimal" onChange={e => setQtyNum(e.target.value.replace(/[^\d.]/g, ''))} style={{ width: 44, textAlign: 'center', border: 0, background: 'none', fontFamily: 'inherit', fontWeight: 700 }} />
              <button onClick={() => setQtyNum(n => (Number(n) || 0) + 1)}><Icon name="plus" size={15} /></button>
            </span>
            <select className="input" value={unit} onChange={e => setUnit(e.target.value)} style={{ width: 'auto', padding: '8px 10px' }}>
              <option value="ปอนด์">ปอนด์</option>
              <option value="ชิ้น">ชิ้น</option>
              <option value="กล่อง">กล่อง</option>
              <option value="ชุด">ชุด</option>
            </select>
          </div>
          <div className="muted" style={{ fontSize: 11.5, marginBottom: 8 }}>จะขึ้นในใบเสนอราคาว่า: <b>{itemTitle || '—'}</b></div>
          <textarea className="input" rows={3} value={requirements} onChange={e => setRequirements(e.target.value)}
            placeholder="รายละเอียด/ข้อความที่ลูกค้าต้องการ" style={{ resize: 'vertical' }} />

          {/* ง) รูปเค้กหลัก */}
          <div className="muted" style={{ fontSize: 12.5, fontWeight: 700, margin: '14px 0 6px' }}>ง · รูปเค้ก (ขึ้นบนใบเสนอราคา)</div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', flexWrap: 'wrap' }}>
            <div style={{ width: 96, height: 96, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', background: '#fff', flexShrink: 0 }}>
              {cakeImg ? <img src={cakeImg} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                : <div style={{ display: 'grid', placeItems: 'center', height: '100%', color: 'var(--muted)', fontSize: 12 }}>รูปเค้ก</div>}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label className="btn btn--ghost btn--sm" style={{ display: 'inline-flex', cursor: 'pointer' }}>
                <Icon name="plus" size={14} /> อัปโหลดรูป
                <input type="file" accept="image/*" style={{ display: 'none' }} onChange={e => pickImg(e.target.files && e.target.files[0], setCakeImg)} />
              </label>
              {catalogPics.length > 0 &&
                <select className="input" value="" onChange={e => { if (e.target.value) setCakeImg(e.target.value); }}
                  style={{ padding: '6px 8px', fontSize: 12, maxWidth: 180 }}>
                  <option value="">เลือกจากแคตตาล็อก…</option>
                  {catalogPics.map(c => <option key={c.id} value={c.img}>{(c.code ? c.code + ' · ' : '') + c.name}</option>)}
                </select>}
              <div style={{ display: 'flex', gap: 4 }}>
                <input className="input" value={codeInput} onChange={e => setCodeInput(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') addByCode(); }} placeholder="รหัส เช่น 27" style={{ width: 100, padding: '6px 8px', fontSize: 12 }} />
                <button className="btn btn--ghost btn--sm" onClick={addByCode} disabled={!codeInput.trim()} style={{ padding: '4px 8px' }}>ใส่</button>
              </div>
            </div>
          </div>

          {/* จ) รูปเพิ่มเติมจากลูกค้า */}
          <div className="muted" style={{ fontSize: 12.5, fontWeight: 700, margin: '14px 0 6px' }}>จ · รูปเพิ่มเติมจากลูกค้า (ให้ครัวดู)</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            {refImgs.map((src, i) => (
              <div key={i} style={{ position: 'relative' }}>
                <img src={src} alt="" style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 8 }} />
                <button onClick={() => delRefImg(i)} style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', border: 0, background: 'rgba(0,0,0,.6)', color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center' }}><Icon name="x" size={12} /></button>
              </div>
            ))}
            <label className="btn btn--ghost btn--sm" style={{ display: 'inline-flex', cursor: 'pointer' }}>
              <Icon name="plus" size={14} /> เพิ่มรูป
              <input type="file" accept="image/*" multiple style={{ display: 'none' }}
                onChange={e => { Array.from(e.target.files || []).forEach(addRefImg); e.target.value = ''; }} />
            </label>
          </div>
        </div>

        <div style={{ padding: '12px 18px', borderBottom: showCost ? '1px solid var(--line)' : 0 }}>
          <button className="btn btn--ghost btn--sm" onClick={() => setShowCost(v => !v)} style={{ fontWeight: 700 }}>
            <Icon name="ruler" size={15} /> คิดต้นทุน (เฉพาะแอดมิน) {showCost ? '▾' : '▸'}</button>
        </div>

        {showCost && <div style={{ padding: 18 }}>
          {/* 1) สูตรฐาน / ส่วนประกอบ */}
          <div className="muted" style={{ fontSize: 13, fontWeight: 700, marginBottom: 10 }}>1 · สูตรฐาน / ส่วนประกอบ</div>
          {compLines.map((l, i) => (
            <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'center', marginBottom: 10 }}>
              <input className="input" value={l.label} placeholder="เช่น เนื้อเค้กชิฟฟ่อน 1 ปอนด์" onChange={e => setComp(i, { label: e.target.value })}
                style={{ flex: 1, minWidth: 0, padding: '9px 11px' }} />
              <span className="priceedit" style={{ padding: '6px 9px' }}>
                <input value={l.qty} inputMode="decimal" onChange={e => setComp(i, { qty: e.target.value })} style={{ width: 40 }} />
                <span className="cur">x</span>
              </span>
              <span className="priceedit" style={{ padding: '6px 9px' }}>
                <input value={l.unitCost} inputMode="decimal" onChange={e => setComp(i, { unitCost: e.target.value })} style={{ width: 56 }} />
                <span className="cur">฿</span>
              </span>
              <span style={{ width: 64, textAlign: 'right', fontWeight: 700, fontSize: 14 }}>{J.formatMoney(Math.round(l.cost), fmt)}</span>
              <button onClick={() => delComp(i)} style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 4, flexShrink: 0 }}><Icon name="x" size={17} /></button>
            </div>
          ))}
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 4, flexWrap: 'wrap' }}>
            <button className="btn btn--ghost btn--sm" onClick={addComp}><Icon name="plus" size={16} /> เพิ่มสูตรฐาน/ส่วนประกอบ</button>
            {baseList.length > 0 &&
              <select className="input" value="" onChange={e => { if (e.target.value) addBase(e.target.value); }}
                style={{ width: 'auto', padding: '7px 10px', fontSize: 13 }}>
                <option value="">+ จากสูตรฐาน DATA…</option>
                {baseList.map(b => <option key={b.id} value={b.id}>{b.name} (฿{b.unitCost}/{b.unit})</option>)}
              </select>}
          </div>

          {/* 2) วัตถุดิบ */}
          <div className="muted" style={{ fontSize: 13, fontWeight: 700, margin: '18px 0 10px', borderTop: '1px solid var(--line)', paddingTop: 14 }}>2 · วัตถุดิบ (จาก JEBAR DATA)</div>
          {ingLines.map((l, i) => (
            <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'center', marginBottom: 10 }}>
              <select className="input" value={l.ing ? l.ing.id : ''} onChange={e => setRow(i, { ing: e.target.value })}
                style={{ flex: 1, minWidth: 0, padding: '9px 11px' }}>
                {cats.map(cat => (
                  <optgroup key={cat} label={cat}>
                    {ingredients.filter(x => x.category === cat).map(x => <option key={x.id} value={x.id}>{x.name} (฿{x.unit_cost}/{x.unit})</option>)}
                  </optgroup>
                ))}
              </select>
              <span className="priceedit" style={{ padding: '6px 9px' }}>
                <input value={l.qty} inputMode="decimal" onChange={e => setRow(i, { qty: e.target.value })} style={{ width: 56 }} />
                <span className="cur">{l.ing ? l.ing.unit : ''}</span>
              </span>
              <span style={{ width: 64, textAlign: 'right', fontWeight: 700, fontSize: 14 }}>{J.formatMoney(Math.round(l.cost), fmt)}</span>
              <button onClick={() => delRow(i)} style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 4, flexShrink: 0 }}><Icon name="x" size={17} /></button>
            </div>
          ))}
          <button className="btn btn--ghost btn--sm" onClick={addRow} style={{ marginTop: 4 }}><Icon name="plus" size={16} /> เพิ่มวัตถุดิบ</button>

          {/* 3) แพ็กเกจ */}
          <div className="muted" style={{ fontSize: 13, fontWeight: 700, margin: '18px 0 10px', borderTop: '1px solid var(--line)', paddingTop: 14 }}>3 · แพ็กเกจ (กล่อง/ฐาน/เทียน · จาก JEBAR DATA)</div>
          {pkgLines.map((l, i) => (
            <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'center', marginBottom: 10 }}>
              <select className="input" value={l.id} onChange={e => setPkgRow(i, { id: e.target.value })} style={{ flex: 1, minWidth: 0, padding: '9px 11px' }}>
                {packages.map(p => <option key={p.id} value={p.id}>{p.name} (฿{p.costPerPiece}/{p.unit || 'ชิ้น'})</option>)}
              </select>
              <span className="priceedit" style={{ padding: '6px 9px' }}>
                <input value={l.qty} inputMode="decimal" onChange={e => setPkgRow(i, { qty: e.target.value })} style={{ width: 56 }} />
                <span className="cur">{l.p ? (l.p.unit || 'ชิ้น') : ''}</span>
              </span>
              <span style={{ width: 64, textAlign: 'right', fontWeight: 700, fontSize: 14 }}>{J.formatMoney(Math.round(l.cost), fmt)}</span>
              <button onClick={() => delPkgRow(i)} style={{ border: 0, background: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 4, flexShrink: 0 }}><Icon name="x" size={17} /></button>
            </div>
          ))}
          <button className="btn btn--ghost btn--sm" onClick={addPkgRow} disabled={!packages.length} style={{ marginTop: 4 }}>
            <Icon name="plus" size={16} /> เพิ่มแพ็กเกจ{!packages.length ? ' (กำลังโหลด…)' : ''}</button>
        </div>}
      </div>

      {/* result */}
      <div className="panel" style={{ position: 'sticky', top: 90 }}>
        <div className="panel__head"><h3>สรุปต้นทุน</h3></div>
        <div style={{ padding: 18 }}>
          {compTotal > 0 && <div className="kv"><span className="k">สูตรฐาน/ส่วนประกอบ</span><span className="v">{J.formatMoney(Math.round(compTotal), fmt)}</span></div>}
          {material > 0 && <div className="kv"><span className="k">วัตถุดิบ</span><span className="v">{J.formatMoney(Math.round(material), fmt)}</span></div>}
          {pkgTotal > 0 && <div className="kv"><span className="k">แพ็กเกจ</span><span className="v">{J.formatMoney(Math.round(pkgTotal), fmt)}</span></div>}
          <div className="set-item" style={{ margin: '12px 0', border: 0, padding: 0 }}>
            <label>อื่นๆ (ป้าย/ของแต่งพิเศษ)</label>
            <div className="inrow"><span className="unit">+</span>
              <input value={other} inputMode="numeric" onChange={e => setOther(e.target.value.replace(/[^\d]/g, ''))} />
              <span className="unit">บาท</span></div>
          </div>
          <div className="set-item" style={{ margin: '12px 0', border: 0, padding: 0 }}>
            <label>ค่าแรง / งานทำมือ</label>
            <div className="inrow"><span className="unit">+</span>
              <input value={labor} inputMode="numeric" onChange={e => setLabor(e.target.value.replace(/[^\d]/g, ''))} />
              <span className="unit">บาท</span></div>
          </div>
          <div className="kv"><span className="k">ต้นทุนรวม</span><span className="v" style={{ fontSize: 16 }}>{J.formatMoney(Math.round(totalCost), fmt)}</span></div>

          <div className="set-item" style={{ margin: '12px 0', border: 0, padding: 0 }}>
            <label>มาร์จิน (× สูตรฐาน+วัตถุดิบ)</label>
            <div className="inrow">
              <input value={markup} inputMode="decimal" onChange={e => setMarkup(e.target.value.replace(/[^\d.]/g, ''))} />
              <span className="unit">เท่า</span></div>
          </div>

          <div style={{ background: 'var(--primary-soft)', borderRadius: 'var(--r)', padding: '15px 16px', marginTop: 8 }}>
            <div className="muted" style={{ fontSize: 13, fontWeight: 700 }}>ราคาขายแนะนำ</div>
            <div style={{ fontFamily: 'var(--font-head)', fontSize: 30, fontWeight: 700, color: 'var(--brand)', marginTop: 2 }}>{J.formatMoney(price, fmt)}</div>
            <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span className="muted" style={{ fontSize: 13 }}>กำไรขั้นต้น</span>
              <span className="stp" style={{ background: margin >= 60 ? '#E7ECDF' : '#FBEBD2', color: margin >= 60 ? '#5E7A45' : '#9A7322' }}>{margin}%</span>
            </div>
          </div>
          <button className="btn btn--primary" style={{ width: '100%', marginTop: 14 }} onClick={exportQuote} disabled={busy}>
            <Icon name="check" size={18} /> {busy ? 'กำลังสร้าง…' : 'บันทึก & ส่งออกรูปใบเสนอราคา'}</button>
          <p className="muted" style={{ fontSize: 12, marginTop: 12, lineHeight: 1.5 }}>
            ราคาขาย = (สูตรฐาน+วัตถุดิบ × มาร์จิน) + แพ็กเกจ + อื่นๆ + ค่าแรง · ต้นทุนดึงจาก JEBAR DATA</p>
        </div>
      </div>
    </div>

    {/* ใบงานที่บันทึกไว้ (เปิด/ดาวน์โหลด/ลบ) */}
    {quotes.length > 0 &&
      <div className="panel" style={{ marginTop: 18 }}>
        <div className="panel__head"><h3>ใบงานที่บันทึกไว้ ({quotes.length})</h3></div>
        <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(160px,1fr))', gap: 12 }}>
          {quotes.map(q => (
            <div key={q.id} style={{ border: '1px solid ' + (q.id === jobId ? 'var(--primary)' : 'var(--line)'), borderRadius: 10, overflow: 'hidden', background: '#fff' }}>
              {q.dataUrl
                ? <img src={q.dataUrl} alt="" style={{ width: '100%', display: 'block', cursor: 'pointer' }} onClick={() => openJob(q)} />
                : <div onClick={() => openJob(q)} style={{ aspectRatio: '4/3', display: 'grid', placeItems: 'center', color: 'var(--muted)', fontSize: 13, cursor: 'pointer', background: 'var(--cream)' }}>ใบงาน (ยังไม่มีรูป)</div>}
              <div style={{ padding: '6px 8px' }}>
                <div style={{ fontSize: 11.5, marginBottom: 6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{q.title}</div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button className="btn btn--ghost btn--sm" style={{ flex: 1, padding: '4px 6px', fontSize: 12 }} onClick={() => openJob(q)}>เปิด</button>
                  {q.dataUrl && <a className="btn btn--ghost btn--sm" style={{ padding: '4px 6px', fontSize: 12 }} href={q.dataUrl} download={q.title + '.png'}>โหลด</a>}
                  <button onClick={() => delQuote(q.id)} style={{ border: 0, background: 'none', cursor: 'pointer', color: '#B25543', padding: 2 }}><Icon name="x" size={15} /></button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>}
   </div>
  );
}

Object.assign(window, { CostCalculator });
