/* ============ ทะเบียนคู่ค้า / ผู้ขาย (vendor registry) ============ */
function VendorsPage({ role, toast }) {
  const canEdit = role === 'owner' || role === 'staff';
  const canDelete = role === 'owner';
  const [, setVer] = useState(0);
  const refresh = () => setVer((v) => v + 1);
  const [q, setQ] = useState('');
  const [modal, setModal] = useState(null);   // 'new' | vendor object
  const [delRow, setDelRow] = useState(null);

  const all = D.vendors || [];
  const qq = q.trim().toLowerCase();
  const list = (qq ? all.filter((v) => (v.name || '').toLowerCase().includes(qq) || (v.taxId || '').replace(/\D/g, '').includes(qq.replace(/\D/g, ''))) : all)
    .slice().sort((a, b) => (b.uses || 0) - (a.uses || 0) || (a.name || '').localeCompare(b.name || ''));

  const save = async (rec) => {
    const res = await API.saveVendor(rec);
    if (res.ok && res.data.ok) {
      const saved = res.data.record || rec; D.vendors = D.vendors || [];
      const i = D.vendors.findIndex((x) => (x.taxId || '').replace(/\D/g, '') === (saved.taxId || '').replace(/\D/g, ''));
      if (i >= 0) D.vendors[i] = saved; else D.vendors.push(saved);
      toast('บันทึกคู่ค้าแล้ว'); setModal(null); refresh(); return true;
    }
    toast((res.data && (res.data.msg || res.data.error)) || 'บันทึกไม่สำเร็จ', 'warn'); return false;
  };
  const doDelete = async () => {
    const res = await API.deleteVendor((delRow.taxId || '').replace(/\D/g, ''));
    if (res.ok && res.data.ok) { const i = D.vendors.findIndex((x) => x.taxId === delRow.taxId); if (i >= 0) D.vendors.splice(i, 1); toast('ลบคู่ค้าแล้ว'); refresh(); }
    else toast('ลบไม่สำเร็จ', 'warn');
    setDelRow(null);
  };

  return (
    <>
      <div className="page-head">
        <div><div className="pt">ทะเบียนคู่ค้า / ผู้ขาย</div><div className="ps">สมุดจำชื่อ↔เลขผู้เสียภาษี — พิมพ์เลขภาษีตอนบันทึกบิลแล้วชื่อขึ้นเอง · ระบบจดจำเพิ่มเองทุกครั้งที่บันทึกเอกสาร</div></div>
        <div className="spacer"></div>
        {canEdit && <button className="btn btn-primary" onClick={() => setModal('new')}><Icon name="plus" className="ic" />เพิ่มคู่ค้า</button>}
      </div>

      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', marginBottom: 16 }}>
        <Stat label="คู่ค้าทั้งหมด" icon="users" value={all.length} unit=" ราย" />
        <Stat label="มีเลขผู้เสียภาษี" icon="check" iconBg="var(--ok-bg)" iconColor="var(--ok)" value={all.filter((v) => (v.taxId || '').replace(/\D/g, '').length === 13).length} unit=" ราย" />
      </div>

      <div className="card card-pad" style={{ marginBottom: 14 }}>
        <div style={{ position: 'relative' }}>
          <Icon name="search" size={17} style={{ position: 'absolute', left: 12, top: 10, color: 'var(--ink-3)' }} />
          <input className="input" style={{ paddingLeft: 36 }} placeholder="ค้นหาชื่อ หรือ เลขผู้เสียภาษี…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
      </div>

      <div className="card">
        <div className="card-head"><h3>รายชื่อคู่ค้า</h3><span className="badge muted" style={{ marginLeft: 'auto' }}>{list.length} ราย</span></div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>ชื่อคู่ค้า</th><th>เลขผู้เสียภาษี</th><th className="hide-sm">สาขา</th><th>หมวด</th><th className="r hide-sm">ใช้ไป</th>{canEdit && <th className="c sticky-act">จัดการ</th>}</tr></thead>
            <tbody>
              {list.map((v) => (
                <tr key={v.taxId}>
                  <td style={{ fontWeight: 500, minWidth: 160 }}>{v.name}</td>
                  <td className="mono" style={{ fontSize: 12.5 }}>{v.taxId}</td>
                  <td className="hide-sm" style={{ color: 'var(--ink-3)' }}>{v.branch || '—'}</td>
                  <td><span className="chip" style={{ background: 'var(--surface-2)', borderColor: 'transparent' }}><span style={{ width: 7, height: 7, borderRadius: 2, background: D.catColor(v.cat) }}></span>{D.catLabel(v.cat)}</span></td>
                  <td className="r num hide-sm" style={{ color: 'var(--ink-3)' }}>{v.uses || 1}</td>
                  {canEdit && (
                    <td className="c sticky-act">
                      <div style={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
                        <button className="x-btn" title="แก้ไข" onClick={() => setModal(v)}><Icon name="edit" size={16} /></button>
                        {canDelete && <button className="x-btn" title="ลบ" style={{ color: 'var(--danger)' }} onClick={() => setDelRow(v)}><Icon name="trash" size={16} /></button>}
                      </div>
                    </td>
                  )}
                </tr>
              ))}
              {list.length === 0 && <tr><td colSpan={canEdit ? 6 : 5} style={{ textAlign: 'center', color: 'var(--ink-3)', padding: '26px 12px' }}>{all.length === 0 ? 'ยังไม่มีคู่ค้า — ระบบจะจดจำเองเมื่อบันทึกเอกสาร หรือกด “เพิ่มคู่ค้า”' : 'ไม่พบคู่ค้าที่ค้นหา'}</td></tr>}
            </tbody>
          </table>
        </div>
      </div>

      {modal && <VendorModal record={modal === 'new' ? null : modal} onClose={() => setModal(null)} onSave={save} />}
      {delRow && (
        <Modal title="ยืนยันการลบคู่ค้า" icon="trash" onClose={() => setDelRow(null)}
          footer={<><button className="btn btn-ghost" onClick={() => setDelRow(null)}>ยกเลิก</button><button className="btn btn-danger" onClick={doDelete}><Icon name="trash" className="ic" />ลบ</button></>}>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>ลบ <b>{delRow.name}</b> (เลขภาษี {delRow.taxId}) ออกจากทะเบียน?<div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 6 }}>เอกสารเดิมไม่ถูกแตะต้อง — แค่ระบบจะไม่เติมชื่อนี้อัตโนมัติอีก</div></div>
        </Modal>
      )}
    </>
  );
}

function VendorModal({ record, onClose, onSave }) {
  const r = record || {};
  const [f, setF] = useState({ taxId: r.taxId || '', name: r.name || '', branch: r.branch || 'สำนักงานใหญ่', cat: r.cat || 'material', type: r.type || 'full' });
  const [err, setErr] = useState('');
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const save = () => {
    const tax = f.taxId.replace(/\D/g, '');
    if (tax.length !== 13) { setErr('เลขผู้เสียภาษีต้องมี 13 หลัก'); return; }
    if (!f.name.trim()) { setErr('กรุณากรอกชื่อคู่ค้า'); return; }
    onSave({ taxId: tax, name: f.name.trim(), branch: f.branch.trim() || 'สำนักงานใหญ่', cat: f.cat, type: f.type });
  };
  return (
    <Modal title={record ? 'แก้ไขคู่ค้า' : 'เพิ่มคู่ค้า'} icon="users" onClose={onClose}
      footer={<><button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button><button className="btn btn-primary" onClick={save}><Icon name="check" className="ic" />บันทึก</button></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        {err && <div className="callout warn" style={{ padding: '9px 12px' }}><Icon name="alert" className="ic" />{err}</div>}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="เลขผู้เสียภาษี (13 หลัก)"><input className="input mono" value={f.taxId} onChange={(e) => set('taxId', e.target.value)} placeholder="0xxxxxxxxxxxx" disabled={!!record} /></Field>
          <Field label="สาขา"><input className="input" value={f.branch} onChange={(e) => set('branch', e.target.value)} placeholder="สำนักงานใหญ่" /></Field>
        </div>
        <Field label="ชื่อคู่ค้า / ร้าน / หจก. / บริษัท"><input className="input" value={f.name} onChange={(e) => set('name', e.target.value)} placeholder="เช่น บริษัท เจริญชัยค้าวัสดุ จำกัด" /></Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="หมวดรายจ่าย (เริ่มต้น)"><select className="select" value={f.cat} onChange={(e) => set('cat', e.target.value)}>{D.expCats.map((c) => <option key={c.id} value={c.id}>{c.label}</option>)}</select></Field>
          <Field label="ประเภทเอกสาร (เริ่มต้น)"><select className="select" value={f.type} onChange={(e) => set('type', e.target.value)}>{Object.entries(D.docTypes).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></Field>
        </div>
        {record && <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>* แก้ชื่อ/หมวดที่นี่ = ทุกบิลที่พิมพ์เลขภาษีนี้จะใช้ค่าที่ถูกต้อง (จำผิดแก้ได้ ไม่เพี้ยนทั้งระบบ)</div>}
      </div>
    </Modal>
  );
}

window.VendorsPage = VendorsPage;
