/* JE BAR — หน้าแก้ตารางราคากลาง (ฝั่งแอดมิน)
 *
 * 🔴 10/09/2026 เจ้าของร้านสั่ง "แก้ราคาเอง ทำเลยครับ"
 *
 * ⚠️ ราคาที่แก้ที่นี่คือ **ราคาที่ลูกค้าเห็น** — บันทึกขึ้น Supabase เสมอ
 * ถ้าเก็บแค่ในเครื่อง เจ้าของร้านแก้บนคอมหลังร้านแล้วลูกค้าจะยังเห็นราคาเดิม
 * โดยไม่มีอะไรบอกว่าสองฝั่งไม่ตรงกัน
 */
function AdminPrices() {
  const T = window.JEBAR_PRICE_TABLE;
  const [data, setData] = React.useState(() => T.read());
  const [state, setState] = React.useState('loading');

  React.useEffect(() => {
    let alive = true;
    T.load().then((v) => { if (alive) { setData(v); setState(''); } });
    return () => { alive = false; };
  }, []);

  const money = (n) => '฿' + Number(n || 0).toLocaleString('th-TH');

  function setPage(key, value) { setData((p) => ({ ...p, page: { ...p.page, [key]: value } })); }

  /* ---- ขนาด (หัวคอลัมน์) ---- */
  function setSize(i, value) {
    setData((p) => ({ ...p, sizes: p.sizes.map((s, k) => (k === i ? value : s)) }));
  }
  function addSize() {
    setData((p) => ({
      ...p,
      sizes: [...p.sizes, 'ขนาดใหม่'],
      rows: p.rows.map((r) => ({ ...r, prices: [...(r.prices || []), null] })),
    }));
  }
  function removeSize(i) {
    if (data.sizes.length <= 1) { alert('ต้องมีอย่างน้อย 1 ขนาด'); return; }
    if (!confirm('ลบขนาด "' + data.sizes[i] + '" ออกจากตาราง? ราคาในคอลัมน์นี้จะหายไปด้วย')) return;
    setData((p) => ({
      ...p,
      sizes: p.sizes.filter((_, k) => k !== i),
      rows: p.rows.map((r) => ({ ...r, prices: (r.prices || []).filter((_, k) => k !== i) })),
    }));
  }

  /* ---- แถว (แบบเค้ก) ---- */
  function setRow(i, key, value) {
    setData((p) => ({ ...p, rows: p.rows.map((r, k) => (k === i ? { ...r, [key]: value } : r)) }));
  }
  /**
   * ⚠️ ช่องว่าง = "สอบถาม" ไม่ใช่ ฿0
   * ถ้าแปลงช่องว่างเป็น 0 ลูกค้าจะเห็นว่าเค้กแถวนั้นราคาศูนย์บาท
   */
  function setPrice(rowIdx, colIdx, raw) {
    const clean = String(raw).replace(/[^\d]/g, '');
    const value = clean === '' ? null : Number(clean);
    setData((p) => ({
      ...p,
      rows: p.rows.map((r, k) => (k === rowIdx ? { ...r, prices: (r.prices || []).map((v, c) => (c === colIdx ? value : v)) } : r)),
    }));
  }
  function addRow() {
    setData((p) => ({
      ...p,
      rows: [...p.rows, { id: 'row_' + Date.now().toString(36), name: 'แบบใหม่', sub: '', prices: p.sizes.map(() => null) }],
    }));
  }
  function removeRow(i) {
    if (!confirm('ลบ "' + data.rows[i].name + '" ออกจากตารางราคา?')) return;
    setData((p) => ({ ...p, rows: p.rows.filter((_, k) => k !== i) }));
  }
  function moveRow(i, delta) {
    const j = i + delta;
    if (j < 0 || j >= data.rows.length) return;
    setData((p) => { const rows = [...p.rows]; [rows[i], rows[j]] = [rows[j], rows[i]]; return { ...p, rows }; });
  }

  /* ---- ไส้ / แพคเกจ / แบบอื่น ---- */
  function setItem(group, i, key, value) {
    setData((p) => ({ ...p, [group]: p[group].map((x, k) => (k === i ? { ...x, [key]: value } : x)) }));
  }
  function setItemNum(group, i, key, raw) {
    const clean = String(raw).replace(/[^\d]/g, '');
    setItem(group, i, key, clean === '' ? 0 : Number(clean));
  }
  function addItem(group, item) {
    setData((p) => ({ ...p, [group]: [...(p[group] || []), { id: group + '_' + Date.now().toString(36), ...item }] }));
  }
  function removeItem(group, i) {
    if (!confirm('ลบรายการนี้?')) return;
    setData((p) => ({ ...p, [group]: p[group].filter((_, k) => k !== i) }));
  }

  async function save() {
    setState('saving');
    try {
      const res = await T.save(data);
      setState(res.cloud ? 'saved' : 'local');
    } catch (e) {
      setState('error');
      console.warn('[JEBAR] บันทึกตารางราคาไม่สำเร็จ:', e.message);
    }
  }
  function resetDefaults() {
    if (confirm('คืนราคาทั้งหมดเป็นค่าเริ่มต้น? ราคาที่แก้ไว้จะหายไป')) setData(T.clone(T.defaults));
  }

  const inputStyle = { width: '100%', padding: '7px 9px', border: '1px solid var(--line,#ddd)', borderRadius: 8, fontSize: 14 };
  const numStyle = { ...inputStyle, width: 92, textAlign: 'right' };

  return (
    <div className="diy-admin">
      <div className="diy-admin__bar">
        <div>
          <h2>ตารางราคากลาง</h2>
          <p className="muted">ราคาที่ลูกค้าเห็นในหน้า “ราคา” — แก้แล้วกดบันทึก ลูกค้าทุกเครื่องจะเห็นค่าใหม่</p>
        </div>
        <div className="diy-admin__actions">
          <a className="btn btn--sm" href="index.html" target="_blank"><Icon name="arrow" size={17} /> ดูหน้าลูกค้า</a>
          <button className="btn btn--primary btn--sm" onClick={save} disabled={state === 'saving'}>
            <Icon name="check" size={17} /> {state === 'saving' ? 'กำลังบันทึก...' : 'บันทึกราคา'}
          </button>
        </div>
      </div>
      {state === 'saved' && <div className="diy-admin__status ok">บันทึกขึ้น Supabase แล้ว ลูกค้าทุกเครื่องจะเห็นราคาใหม่</div>}
      {state === 'local' && <div className="diy-admin__status">บันทึกไว้ในเครื่องนี้แล้ว — แต่ยังไม่ขึ้นคลาวด์ ลูกค้าจะยังเห็นราคาเดิม</div>}
      {state === 'error' && <div className="diy-admin__status">บันทึกไม่สำเร็จ ลองใหม่อีกครั้ง</div>}

      {/* ── ข้อความหัวหน้า ── */}
      <div className="card" style={{ marginBottom: 16 }}>
        <h3 style={{ marginBottom: 12 }}>ข้อความบนหน้า</h3>
        <div style={{ display: 'grid', gap: 10 }}>
          <label><div className="muted" style={{ fontSize: 13, marginBottom: 4 }}>หัวข้อ</div>
            <input style={inputStyle} value={data.page.title} onChange={(e) => setPage('title', e.target.value)} /></label>
          <label><div className="muted" style={{ fontSize: 13, marginBottom: 4 }}>คำอธิบายใต้หัวข้อ</div>
            <input style={inputStyle} value={data.page.subtitle} onChange={(e) => setPage('subtitle', e.target.value)} /></label>
          <label><div className="muted" style={{ fontSize: 13, marginBottom: 4 }}>หมายเหตุท้ายหน้า</div>
            <textarea style={{ ...inputStyle, minHeight: 64 }} value={data.page.notice} onChange={(e) => setPage('notice', e.target.value)} /></label>
        </div>
      </div>

      {/* ── ตารางหลัก ── */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, gap: 8, flexWrap: 'wrap' }}>
          <h3 style={{ margin: 0 }}>ราคาตามขนาด</h3>
          <span style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn--sm" onClick={addSize}><Icon name="plus" size={15} /> เพิ่มขนาด</button>
            <button className="btn btn--sm" onClick={addRow}><Icon name="plus" size={15} /> เพิ่มแบบเค้ก</button>
          </span>
        </div>
        <p className="muted" style={{ fontSize: 13, marginBottom: 12 }}>เว้นช่องราคาว่างไว้ = ลูกค้าเห็นคำว่า “สอบถาม” (ไม่ใช่ ฿0)</p>

        <div style={{ overflowX: 'auto' }}>
          <table style={{ borderCollapse: 'collapse', minWidth: 640 }}>
            <thead>
              <tr>
                <th style={{ textAlign: 'left', padding: 8, minWidth: 190 }}>แบบเค้ก</th>
                {data.sizes.map((s, i) => (
                  <th key={i} style={{ padding: 8, minWidth: 110 }}>
                    <input style={{ ...inputStyle, textAlign: 'center', fontSize: 13 }} value={s} onChange={(e) => setSize(i, e.target.value)} />
                    <button className="btn btn--ghost btn--sm" style={{ marginTop: 4, width: '100%' }} onClick={() => removeSize(i)} title="ลบขนาดนี้">
                      <Icon name="trash" size={14} />
                    </button>
                  </th>
                ))}
                <th style={{ width: 92 }} />
              </tr>
            </thead>
            <tbody>
              {data.rows.map((r, ri) => (
                <tr key={r.id} style={{ borderTop: '1px solid var(--line,#eee)' }}>
                  <td style={{ padding: 8 }}>
                    <input style={inputStyle} value={r.name} onChange={(e) => setRow(ri, 'name', e.target.value)} placeholder="ชื่อแบบเค้ก" />
                    <input style={{ ...inputStyle, marginTop: 6, fontSize: 13 }} value={r.sub || ''} onChange={(e) => setRow(ri, 'sub', e.target.value)} placeholder="คำอธิบายสั้น เช่น วิปครีม" />
                  </td>
                  {data.sizes.map((_, ci) => (
                    <td key={ci} style={{ padding: 8, textAlign: 'right' }}>
                      <input style={numStyle} inputMode="numeric"
                        value={(r.prices || [])[ci] == null ? '' : (r.prices || [])[ci]}
                        onChange={(e) => setPrice(ri, ci, e.target.value)} placeholder="สอบถาม" />
                    </td>
                  ))}
                  <td style={{ padding: 8, whiteSpace: 'nowrap' }}>
                    <button className="btn btn--ghost btn--sm" onClick={() => moveRow(ri, -1)} title="เลื่อนขึ้น">↑</button>
                    <button className="btn btn--ghost btn--sm" onClick={() => moveRow(ri, 1)} title="เลื่อนลง">↓</button>
                    <button className="btn btn--ghost btn--sm" onClick={() => removeRow(ri)} title="ลบแบบนี้"><Icon name="trash" size={14} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* ── ไส้ ── */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
          <h3 style={{ margin: 0 }}>ไส้ (คิดตามปอนด์)</h3>
          <button className="btn btn--sm" onClick={() => addItem('fillings', { name: 'ไส้ใหม่', first: 0, next: 0 })}><Icon name="plus" size={15} /> เพิ่มไส้</button>
        </div>
        <p className="muted" style={{ fontSize: 13, marginBottom: 12 }}>ปอนด์แรกราคาหนึ่ง ปอนด์ถัดไปอีกราคาหนึ่ง — หน้าลูกค้าจะคิดตัวเลขทุกขนาดให้เอง</p>
        <div style={{ display: 'grid', gap: 12 }}>
          {(data.fillings || []).map((f, i) => (
            <div key={f.id} style={{ borderTop: '1px solid var(--line,#eee)', paddingTop: 12, display: 'grid', gap: 8 }}>
              <input style={inputStyle} value={f.name} onChange={(e) => setItem('fillings', i, 'name', e.target.value)} />
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
                <label className="muted" style={{ fontSize: 13 }}>ปอนด์แรก +
                  <input style={{ ...numStyle, marginLeft: 6 }} inputMode="numeric" value={f.first} onChange={(e) => setItemNum('fillings', i, 'first', e.target.value)} /></label>
                <label className="muted" style={{ fontSize: 13 }}>ปอนด์ถัดไป +
                  <input style={{ ...numStyle, marginLeft: 6 }} inputMode="numeric" value={f.next} onChange={(e) => setItemNum('fillings', i, 'next', e.target.value)} /></label>
                <span className="muted" style={{ fontSize: 13 }}>เช่น 3 ปอนด์ = +{money(T.fillingPrice(f, 3))}</span>
                <button className="btn btn--ghost btn--sm" onClick={() => removeItem('fillings', i)}><Icon name="trash" size={14} /></button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── แพคเกจ ── */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
          <h3 style={{ margin: 0 }}>แพคเกจ / ตกแต่ง</h3>
          <button className="btn btn--sm" onClick={() => addItem('packaging', { name: 'รายการใหม่', price: 0 })}><Icon name="plus" size={15} /> เพิ่มรายการ</button>
        </div>
        <p className="muted" style={{ fontSize: 13, marginBottom: 12 }}>ราคาเดียว ไม่ขึ้นกับขนาดเค้ก</p>
        <div style={{ display: 'grid', gap: 10 }}>
          {(data.packaging || []).map((p, i) => (
            <div key={p.id} style={{ borderTop: '1px solid var(--line,#eee)', paddingTop: 10, display: 'flex', gap: 8, alignItems: 'center' }}>
              <input style={inputStyle} value={p.name} onChange={(e) => setItem('packaging', i, 'name', e.target.value)} />
              <input style={numStyle} inputMode="numeric" value={p.price} onChange={(e) => setItemNum('packaging', i, 'price', e.target.value)} />
              <button className="btn btn--ghost btn--sm" onClick={() => removeItem('packaging', i)}><Icon name="trash" size={14} /></button>
            </div>
          ))}
        </div>
      </div>

      {/* ── แบบอื่น ๆ ── */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
          <h3 style={{ margin: 0 }}>แบบที่ไม่มีราคาตายตัว</h3>
          <button className="btn btn--sm" onClick={() => addItem('special', { name: 'แบบใหม่', detail: '' })}><Icon name="plus" size={15} /> เพิ่มรายการ</button>
        </div>
        <p className="muted" style={{ fontSize: 13, marginBottom: 12 }}>ไม่ต้องใส่ตัวเลข แต่ต้องบอกวิธีคิดให้ลูกค้าเข้าใจ</p>
        <div style={{ display: 'grid', gap: 12 }}>
          {(data.special || []).map((s, i) => (
            <div key={s.id} style={{ borderTop: '1px solid var(--line,#eee)', paddingTop: 12, display: 'grid', gap: 8 }}>
              <div style={{ display: 'flex', gap: 8 }}>
                <input style={inputStyle} value={s.name} onChange={(e) => setItem('special', i, 'name', e.target.value)} />
                <button className="btn btn--ghost btn--sm" onClick={() => removeItem('special', i)}><Icon name="trash" size={14} /></button>
              </div>
              <textarea style={{ ...inputStyle, minHeight: 56 }} value={s.detail} onChange={(e) => setItem('special', i, 'detail', e.target.value)} placeholder="อธิบายวิธีคิดราคา" />
            </div>
          ))}
        </div>
      </div>

      <button className="btn btn--ghost btn--sm" onClick={resetDefaults}>คืนค่าเริ่มต้นทั้งหมด</button>
    </div>
  );
}

Object.assign(window, { AdminPrices });
