/* ============ หัก ณ ที่จ่าย (จ่ายออก) → 50 ทวิ + ภ.ง.ด.3/53 ============ */
function thDateW(iso) { const d = new Date(iso); if (isNaN(d)) return ''; return d.getDate() + ' ' + D.thMonthsShort[d.getMonth()] + ' ' + String((d.getFullYear() + 543) % 100).padStart(2, '0'); }

/* ----- พิมพ์หนังสือรับรองการหักภาษี ณ ที่จ่าย (50 ทวิ) ----- */
function print50tawi(rec) {
  const c = D.company || {};
  const f = (n) => D.fmt(n || 0);
  const types = [
    ['1. เงินเดือน ค่าจ้าง (40(1))', rec.incomeCode === '40(1)'],
    ['2. ค่าธรรมเนียม ค่านายหน้า (40(2))', rec.incomeCode === '40(2)'],
    ['3. ค่าแห่งลิขสิทธิ์ (40(3))', rec.incomeCode === '40(3)'],
    ['4. ค่าเช่าทรัพย์สิน (40(5))', rec.incomeCode === '40(5)'],
    ['5. ค่าจ้างทำของ / รับเหมา / บริการ (40(7)(8))', rec.incomeCode === '40(7)/(8)' || rec.incomeCode === 'other' || rec.incomeCode === 'transport' || rec.incomeCode === 'ads'],
  ];
  const w = window.open('', '_blank'); if (!w) return;
  const html = `<!DOCTYPE html><html lang="th"><head><meta charset="utf-8"><title>50 ทวิ ${rec.payee || ''}</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;600;700&display=swap">
<style>
  *{box-sizing:border-box} body{font-family:'Sarabun',sans-serif;color:#111;margin:0;padding:28px 34px;font-size:13px}
  .hd{text-align:center;margin-bottom:6px} .hd h1{font-size:17px;margin:0} .hd .s{font-size:12px;color:#555}
  .party{border:1px solid #bbb;border-radius:6px;padding:9px 12px;margin-top:12px;line-height:1.7}
  .party .t{font-weight:700;color:#1f6f54;font-size:12px}
  table{width:100%;border-collapse:collapse;margin-top:12px}
  th,td{border:1px solid #bbb;padding:7px 9px} th{background:#eef4f1;font-size:12px}
  td.r,th.r{text-align:right;font-variant-numeric:tabular-nums}
  .chk{margin:10px 0;line-height:1.9;font-size:12.5px}
  .words{background:#f6faf8;border:1px solid #cdd9d4;border-radius:6px;padding:8px 12px;margin-top:8px;font-weight:600}
  .cond{margin-top:10px;font-size:12.5px}
  .sign{display:flex;justify-content:flex-end;margin-top:34px} .sign div{text-align:center;width:46%}
  .ln{border-top:1px dotted #888;margin-top:38px;padding-top:5px;font-size:12px;color:#555}
  .note{font-size:11px;color:#888;margin-top:14px}
  @media print{body{padding:0}}
</style></head><body>
<div class="hd"><h1>หนังสือรับรองการหักภาษี ณ ที่จ่าย</h1><div class="s">ตามมาตรา 50 ทวิ แห่งประมวลรัษฎากร</div></div>
<div class="party"><div class="t">ผู้มีหน้าที่หักภาษี ณ ที่จ่าย (ผู้จ่ายเงิน)</div>
  <div>${c.name || '-'}</div><div>${c.address || ''}</div>
  <div>เลขประจำตัวผู้เสียภาษี ${c.taxId || '-'}</div></div>
<div class="party"><div class="t">ผู้ถูกหักภาษี ณ ที่จ่าย (ผู้รับเงิน)</div>
  <div><b>${rec.payee || '-'}</b></div><div>${rec.payeeAddress || ''}</div>
  <div>เลขประจำตัวผู้เสียภาษี ${rec.payeeTax || '-'} &nbsp; (${rec.payeeType === 'company' ? 'นิติบุคคล — ภ.ง.ด.53' : 'บุคคลธรรมดา — ภ.ง.ด.3'})</div></div>
<div class="chk"><b>ประเภทเงินได้พึงประเมินที่จ่าย:</b><br>${types.map(([l, on]) => (on ? '☑' : '☐') + ' ' + l).join('<br>')}<br>
  รายละเอียด: ${rec.description || '-'}</div>
<table><thead><tr><th>วันเดือนปีที่จ่าย</th><th class="r">จำนวนเงินที่จ่าย</th><th class="r">ภาษีที่หักและนำส่ง</th></tr></thead>
<tbody><tr><td>${rec.payDate || thDateW(rec.payDateISO)}</td><td class="r">${f(rec.amount)}</td><td class="r">${f(rec.wht)}</td></tr>
<tr><td style="text-align:right;font-weight:700">รวม</td><td class="r" style="font-weight:700">${f(rec.amount)}</td><td class="r" style="font-weight:700">${f(rec.wht)}</td></tr></tbody></table>
<div class="words">ภาษีที่หักนำส่ง (ตัวอักษร): ${bahtText(rec.wht)}</div>
<div class="cond"><b>ผู้จ่ายเงิน:</b> ☑ หักภาษี ณ ที่จ่าย &nbsp; ☐ ออกภาษีให้ตลอดไป &nbsp; ☐ ออกภาษีให้ครั้งเดียว</div>
<div class="sign"><div><div class="ln">ผู้จ่ายเงิน / วันที่</div></div></div>
<div class="note">⚠️ เอกสารช่วยจัดเตรียมจากระบบบัญชี·ภาษี — โปรดตรวจสอบกับสำนักงานบัญชีก่อนใช้จริง</div>
<script>window.onload=function(){setTimeout(function(){window.print()},350)}</script>
</body></html>`;
  w.document.write(html); w.document.close();
}

/* ----- พิมพ์ใบแนบ ภ.ง.ด.3 (บุคคล) / ภ.ง.ด.53 (นิติบุคคล) ----- */
function printPND(list, payeeType, pLong) {
  const c = D.company || {};
  const f = (n) => D.fmt(n || 0);
  const formNo = payeeType === 'company' ? '53' : '3';
  const totalAmt = list.reduce((a, r) => a + (r.amount || 0), 0);
  const totalWht = list.reduce((a, r) => a + (r.wht || 0), 0);
  const w = window.open('', '_blank'); if (!w) return;
  const rows = list.map((r, i) => `<tr><td class="c">${i + 1}</td><td class="mono">${r.payeeTax || '-'}</td><td>${r.payee || '-'}<div style="font-size:10.5px;color:#888">${r.payeeAddress || ''}</div></td><td>${r.payDate || thDateW(r.payDateISO)}</td><td>${r.incomeLabel || ''}</td><td class="r">${f(r.amount)}</td><td class="c">${r.whtRate}%</td><td class="r">${f(r.wht)}</td></tr>`).join('');
  const html = `<!DOCTYPE html><html lang="th"><head><meta charset="utf-8"><title>ภ.ง.ด.${formNo} ${pLong}</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;600;700&display=swap">
<style>
  *{box-sizing:border-box} body{font-family:'Sarabun',sans-serif;color:#111;margin:0;padding:24px 28px;font-size:12px}
  .hd{display:flex;justify-content:space-between;align-items:flex-end;border-bottom:2px solid #1f6f54;padding-bottom:10px}
  .hd h1{font-size:17px;margin:0} .hd .s{font-size:12px;color:#555}
  .co{font-size:12px;line-height:1.5;margin:10px 0}
  table{width:100%;border-collapse:collapse;margin-top:6px} th,td{border:1px solid #bbb;padding:6px 8px;vertical-align:top}
  th{background:#eef4f1;font-size:11.5px} td.r,th.r{text-align:right;font-variant-numeric:tabular-nums} td.c,th.c{text-align:center}
  .mono{font-family:monospace} tr.tot td{background:#f6faf8;font-weight:700}
  .words{background:#f6faf8;border:1px solid #cdd9d4;border-radius:6px;padding:8px 12px;margin-top:8px;font-weight:600}
  .note{font-size:11px;color:#888;margin-top:12px}
  @media print{body{padding:0}}
</style></head><body>
<div class="hd"><div><h1>ใบแนบ ภ.ง.ด.${formNo}</h1><div class="s">รายการภาษีหัก ณ ที่จ่าย — ${payeeType === 'company' ? 'ผู้รับเงินเป็นนิติบุคคล' : 'ผู้รับเงินเป็นบุคคลธรรมดา'} · ประจำเดือน ${pLong}</div></div>
  <div style="text-align:right;font-size:11px;color:#666">พิมพ์ ${new Date().toLocaleDateString('th-TH')}</div></div>
<div class="co"><b>ผู้มีหน้าที่หักภาษี:</b> ${c.name || '-'} · เลขผู้เสียภาษี ${c.taxId || '-'} · ${c.address || ''}</div>
<table><thead><tr><th class="c" style="width:34px">ที่</th><th style="width:120px">เลขผู้เสียภาษี</th><th>ผู้ถูกหัก / ที่อยู่</th><th>วันที่จ่าย</th><th>ประเภทเงินได้</th><th class="r">จำนวนเงิน</th><th class="c">อัตรา</th><th class="r">ภาษีหัก</th></tr></thead>
<tbody>${rows || '<tr><td colspan="8" class="c" style="padding:18px;color:#999">ไม่มีรายการในเดือนนี้</td></tr>'}
<tr class="tot"><td colspan="5" class="r">รวมทั้งสิ้น ${list.length} ราย</td><td class="r">${f(totalAmt)}</td><td></td><td class="r">${f(totalWht)}</td></tr></tbody></table>
<div class="words">ภาษีหักนำส่งทั้งสิ้น (ตัวอักษร): ${bahtText(totalWht)}</div>
<div class="note">⚠️ เอกสารช่วยจัดเตรียม (ใบแนบ ภ.ง.ด.${formNo}) — โปรดตรวจสอบกับสำนักงานบัญชี/ยื่นผ่านระบบกรมสรรพากร · กำหนดยื่นภายในวันที่ 7 ของเดือนถัดไป</div>
<script>window.onload=function(){setTimeout(function(){window.print()},350)}</script>
</body></html>`;
  w.document.write(html); w.document.close();
}

function WHTPage({ role, toast, pShort, pLong, period }) {
  const canEdit = role === 'owner' || role === 'staff';
  const canDelete = role === 'owner';
  const [, setVer] = useState(0);
  const refresh = () => setVer((v) => v + 1);
  const [modal, setModal] = useState(null);
  const [delRow, setDelRow] = useState(null);

  const isCurrent = period.m === CURRENT_PERIOD.m && period.y === CURRENT_PERIOD.y;
  const defaultISO = (period.y - 543) + '-' + String(period.m + 1).padStart(2, '0') + '-' + String(isCurrent ? new Date().getDate() : 1).padStart(2, '0');

  const handleSave = async (rec) => {
    const exists = (D.wht || []).some((x) => x.id === rec.id);
    const res = exists ? await API.updateWht(rec) : await API.addWht(rec);
    if (res.ok && res.data.ok) {
      const saved = res.data.record || rec;
      D.wht = D.wht || [];
      const i = D.wht.findIndex((x) => x.id === saved.id);
      if (i >= 0) D.wht[i] = saved; else D.wht.push(saved);
      toast(exists ? 'แก้ไขแล้ว' : 'บันทึกการหัก ณ ที่จ่ายแล้ว');
      setModal(null); refresh();
    } else toast((res.data && (res.data.msg || res.data.error)) || 'บันทึกไม่สำเร็จ', 'warn');
  };
  const handleDelete = async () => {
    const res = await API.deleteWht(delRow.id);
    if (res.ok && res.data.ok) { const i = D.wht.findIndex((x) => x.id === delRow.id); if (i >= 0) D.wht.splice(i, 1); toast('ลบแล้ว'); refresh(); }
    else toast('ลบไม่สำเร็จ', 'warn');
    setDelRow(null);
  };

  const rows = (D.wht || []).filter((r) => inPeriod(r.payDateISO, period));
  const totalAmt = rows.reduce((a, r) => a + (r.amount || 0), 0);
  const totalWht = rows.reduce((a, r) => a + (r.wht || 0), 0);
  const pnd3 = rows.filter((r) => r.payeeType !== 'company');
  const pnd53 = rows.filter((r) => r.payeeType === 'company');

  return (
    <>
      <div className="page-head">
        <div><div className="pt">หัก ณ ที่จ่าย (จ่ายออก)</div><div className="ps">บันทึกภาษีที่หักเมื่อจ่ายค่าแรง/จ้างช่วง → ออก 50 ทวิ + ภ.ง.ด.3/53 · {pShort}</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="expense" value={D.baht(totalAmt, 0)} />
        <Stat label="ภาษีหัก ณ ที่จ่ายรวม" icon="vat" iconBg="var(--warn-bg)" iconColor="var(--warn)" value={D.baht(totalWht, 0)} sub="นำส่งกรมสรรพากร" />
        <Stat label="ภ.ง.ด.3 (บุคคล)" icon="person" iconBg="var(--info-bg)" iconColor="var(--info)" value={pnd3.length} unit=" ราย" sub={D.baht(pnd3.reduce((a, r) => a + r.wht, 0), 0)} />
        <Stat label="ภ.ง.ด.53 (นิติบุคคล)" icon="bank" iconBg="var(--surface-2)" iconColor="var(--ink-2)" value={pnd53.length} unit=" ราย" sub={D.baht(pnd53.reduce((a, r) => a + r.wht, 0), 0)} />
      </div>

      <div className="callout info" style={{ marginBottom: 14 }}>
        <Icon name="info" className="ic" />
        <div>บันทึกทุกครั้งที่<b>จ่ายค่าแรง/จ้างผู้รับเหมาช่วง</b>แล้วหักภาษีไว้ — ระบบออก<b>หนังสือรับรองหัก ณ ที่จ่าย (50 ทวิ)</b>ให้ผู้รับ และรวมเป็น<b>ใบแนบ ภ.ง.ด.3/53</b>ยื่นภายในวันที่ 7 ของเดือนถัดไป</div>
      </div>

      <div className="card">
        <div className="card-head"><h3>รายการหัก ณ ที่จ่าย</h3>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button className="btn btn-sm btn-ghost" disabled={!pnd3.length} onClick={() => printPND(pnd3, 'individual', pLong)}><Icon name="download" className="ic" />ภ.ง.ด.3</button>
            <button className="btn btn-sm btn-ghost" disabled={!pnd53.length} onClick={() => printPND(pnd53, 'company', pLong)}><Icon name="download" className="ic" />ภ.ง.ด.53</button>
          </div>
        </div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>วันที่จ่าย</th><th>ผู้ถูกหัก</th><th>ประเภทเงินได้</th><th className="r">จำนวนเงิน</th><th className="c">อัตรา</th><th className="r">ภาษีหัก</th><th className="c">แบบ</th>{canEdit && <th className="c sticky-act">จัดการ</th>}</tr></thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.id}>
                  <td className="num" style={{ whiteSpace: 'nowrap', color: 'var(--ink-2)' }}>{r.payDate || thDateW(r.payDateISO)}</td>
                  <td style={{ minWidth: 150 }}><div style={{ fontWeight: 500 }}>{r.payee}</div><div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.payeeTax}</div></td>
                  <td style={{ fontSize: 12.5 }}>{r.incomeLabel}{r.description ? <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.description}</div> : null}</td>
                  <td className="r num">{D.fmt(r.amount)}</td>
                  <td className="c">{r.whtRate}%</td>
                  <td className="r num" style={{ fontWeight: 700, color: 'var(--warn)' }}>{D.fmt(r.wht)}</td>
                  <td className="c"><span className={'badge ' + (r.payeeType === 'company' ? 'muted' : 'info')}>{r.payeeType === 'company' ? 'ภ.ง.ด.53' : 'ภ.ง.ด.3'}</span></td>
                  {canEdit && (
                    <td className="c sticky-act">
                      <div style={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
                        <button className="x-btn" title="พิมพ์ 50 ทวิ" style={{ color: 'var(--primary)' }} onClick={() => print50tawi(r)}><Icon name="receipt" size={16} /></button>
                        <button className="x-btn" title="แก้ไข" onClick={() => setModal(r)}><Icon name="edit" size={16} /></button>
                        {canDelete && <button className="x-btn" title="ลบ" style={{ color: 'var(--danger)' }} onClick={() => setDelRow(r)}><Icon name="trash" size={16} /></button>}
                      </div>
                    </td>
                  )}
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={canEdit ? 8 : 7} style={{ textAlign: 'center', color: 'var(--ink-3)', padding: '26px 12px' }}>ยังไม่มีรายการหัก ณ ที่จ่ายในเดือนนี้ — กด “เพิ่มการจ่าย”</td></tr>}
            </tbody>
            {rows.length > 0 && <tfoot><tr style={{ background: 'var(--surface-2)', fontWeight: 700 }}>
              <td colSpan="3" style={{ padding: 12 }}>รวม {rows.length} ราย</td>
              <td className="r num" style={{ padding: 12 }}>{D.fmt(totalAmt)}</td><td></td>
              <td className="r num" style={{ padding: 12, color: 'var(--warn)' }}>{D.fmt(totalWht)}</td><td></td>{canEdit && <td className="sticky-act"></td>}
            </tr></tfoot>}
          </table>
        </div>
      </div>

      {modal && <WhtModal record={modal === 'new' ? null : modal} defaultISO={defaultISO} onClose={() => setModal(null)} onSave={handleSave} />}
      {delRow && (
        <Modal title="ยืนยันการลบ" icon="trash" onClose={() => setDelRow(null)}
          footer={<><button className="btn btn-ghost" onClick={() => setDelRow(null)}>ยกเลิก</button><button className="btn btn-danger" onClick={handleDelete}><Icon name="trash" className="ic" />ลบ</button></>}>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>ลบรายการหัก ณ ที่จ่ายของ <b>{delRow.payee}</b> ยอดภาษีหัก <b>{D.baht(delRow.wht)}</b> ใช่หรือไม่?</div>
        </Modal>
      )}
    </>
  );
}

function WhtModal({ record, defaultISO, onClose, onSave }) {
  const r = record || {};
  const [payDateISO, setPayDateISO] = useState(r.payDateISO || defaultISO || new Date().toISOString().slice(0, 10));
  const [payee, setPayee] = useState(r.payee || '');
  const [payeeTax, setPayeeTax] = useState(r.payeeTax || '');
  const [payeeAddress, setPayeeAddress] = useState(r.payeeAddress || '');
  const [payeeType, setPayeeType] = useState(r.payeeType || 'individual');
  const [typeCode, setTypeCode] = useState(r.incomeCode || '40(7)/(8)');
  const [amount, setAmount] = useState(r.amount != null ? String(r.amount) : '');
  const [rate, setRate] = useState(r.whtRate != null ? String(r.whtRate) : '3');
  const [desc, setDesc] = useState(r.description || '');
  const [sug, setSug] = useState(false);
  const [err, setErr] = useState('');
  const [saving, setSaving] = useState(false);

  const amtN = parseFloat(amount) || 0;
  const rateN = parseFloat(rate) || 0;
  const whtN = Math.round(amtN * rateN / 100 * 100) / 100;
  const typeObj = D.whtTypes.find((t) => t.code === typeCode) || D.whtTypes[0];

  const pickType = (code) => { setTypeCode(code); const t = D.whtTypes.find((x) => x.code === code); if (t) setRate(String(t.rate)); };

  // ค้นผู้รับจากที่เคยบันทึก
  const payeeBook = React.useMemo(() => {
    const m = new Map();
    (D.wht || []).forEach((x) => { if (x.payee && !m.has(x.payee)) m.set(x.payee, { payee: x.payee, payeeTax: x.payeeTax, payeeAddress: x.payeeAddress, payeeType: x.payeeType }); });
    (D.docs || []).forEach((x) => { if (x.vendor && !m.has(x.vendor)) m.set(x.vendor, { payee: x.vendor, payeeTax: x.vendorTax, payeeAddress: '', payeeType: 'company' }); });
    return [...m.values()];
  }, []);
  const q = payee.trim().toLowerCase();
  const sugList = (q ? payeeBook.filter((c) => c.payee.toLowerCase().includes(q) || (c.payeeTax || '').includes(q)) : payeeBook).slice(0, 6);
  const pickPayee = (c) => { setPayee(c.payee); setPayeeTax(c.payeeTax && c.payeeTax !== '—' ? c.payeeTax : ''); if (c.payeeAddress) setPayeeAddress(c.payeeAddress); if (c.payeeType) setPayeeType(c.payeeType); setSug(false); };

  const save = async () => {
    setErr('');
    if (!payee.trim()) { setErr('กรุณากรอกชื่อผู้รับเงิน (ผู้ถูกหัก)'); return; }
    if (amtN <= 0) { setErr('กรุณากรอกจำนวนเงินที่จ่าย'); return; }
    setSaving(true);
    await onSave({
      id: r.id || ('W' + Date.now()),
      payDateISO, payDate: thDateW(payDateISO),
      payee: payee.trim(), payeeTax: payeeTax.trim(), payeeAddress: payeeAddress.trim(), payeeType,
      incomeCode: typeCode, incomeLabel: typeObj.label, description: desc.trim(),
      amount: amtN, whtRate: rateN, wht: whtN, condition: 'หัก', status: r.status || 'recorded',
    });
    setSaving(false);
  };

  return (
    <Modal title={record ? 'แก้ไขการหัก ณ ที่จ่าย' : 'บันทึกการจ่ายเงิน + หัก ณ ที่จ่าย'} icon="vat" onClose={onClose} wide
      footer={<><button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button><button className="btn btn-primary" onClick={save} disabled={saving}><Icon name="check" className="ic" />{saving ? 'กำลังบันทึก…' : 'บันทึก'}</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={{ position: 'relative' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
            <Field label="ผู้รับเงิน / ผู้ถูกหัก"><input className="input" value={payee} onFocus={() => setSug(true)} onChange={(e) => { setPayee(e.target.value); setSug(true); }} onBlur={() => setTimeout(() => setSug(false), 160)} placeholder="พิมพ์ชื่อเพื่อค้นหา/เพิ่มใหม่" /></Field>
            <Field label="เลขผู้เสียภาษีผู้รับ"><input className="input mono" value={payeeTax} onChange={(e) => setPayeeTax(e.target.value)} placeholder="13 หลัก" /></Field>
          </div>
          {sug && sugList.length > 0 && (
            <div className="card" style={{ position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 6, marginTop: 4, boxShadow: 'var(--shadow-lg)', maxHeight: 230, overflowY: 'auto', padding: 4 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', padding: '6px 10px 4px' }}><Icon name="search" size={12} /> ผู้รับที่เคยบันทึก</div>
              {sugList.map((c, i) => (
                <button type="button" key={i} onMouseDown={(e) => { e.preventDefault(); pickPayee(c); }} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '8px 10px', borderRadius: 8 }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--surface-2)'} onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{c.payee}</div><div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{c.payeeTax || '—'}</div>
                </button>
              ))}
            </div>
          )}
        </div>
        <Field label="ที่อยู่ผู้รับ"><input className="input" value={payeeAddress} onChange={(e) => setPayeeAddress(e.target.value)} placeholder="ที่อยู่ (สำหรับใบ 50 ทวิ)" /></Field>
        <Field label="ประเภทผู้รับเงิน (กำหนดแบบยื่น)">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {[['individual', 'บุคคลธรรมดา → ภ.ง.ด.3'], ['company', 'นิติบุคคล → ภ.ง.ด.53']].map(([k, l]) => (
              <button key={k} onClick={() => setPayeeType(k)} style={{ padding: '9px 8px', borderRadius: 10, border: '1px solid ' + (payeeType === k ? 'var(--primary)' : 'var(--line)'), background: payeeType === k ? 'var(--primary-tint)' : 'var(--surface)', fontWeight: 600, fontSize: 13 }}>{l}</button>
            ))}
          </div>
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
          <Field label="ประเภทเงินได้"><select className="select" value={typeCode} onChange={(e) => pickType(e.target.value)}>{D.whtTypes.map((t) => <option key={t.code} value={t.code}>{t.label} ({t.rate}%)</option>)}</select></Field>
          <Field label="วันที่จ่าย"><ThaiDatePicker value={payDateISO} onChange={setPayDateISO} /></Field>
        </div>
        <Field label="รายละเอียดงาน/รายการ"><input className="input" value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="เช่น งานเทพื้น คสล. โครงการ A" /></Field>
        <div style={{ background: 'var(--surface-2)', borderRadius: 11, padding: 14, display: 'grid', gridTemplateColumns: '1.3fr 1fr 1.3fr', gap: 12, alignItems: 'end' }}>
          <Field label="จำนวนเงินที่จ่าย"><input className="input right mono" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0.00" /></Field>
          <Field label="อัตราหัก %"><input className="input right mono" value={rate} onChange={(e) => setRate(e.target.value)} /></Field>
          <Field label="ภาษีที่หัก (คำนวณให้)"><input className="input right mono" value={D.fmt(whtN)} readOnly style={{ fontWeight: 700, color: 'var(--warn)', background: 'var(--surface)' }} /></Field>
        </div>
        <div className="callout info" style={{ padding: '9px 12px' }}><Icon name="info" className="ic" />ยอดจ่ายให้ผู้รับจริง = {D.baht(amtN - whtN)} (จ่าย {D.fmt0(amtN)} − หักภาษี {D.fmt0(whtN)}) · ออกใบ 50 ทวิ ให้ผู้รับ และยื่น{payeeType === 'company' ? ' ภ.ง.ด.53' : ' ภ.ง.ด.3'}</div>
      </div>
    </Modal>
  );
}

window.WHTPage = WHTPage;
