/* global React, I, UI, SSSData */
const { useState: useStateW, useMemo: useMemoW, useEffect: useEffectW } = React;

// ประเภทเงินได้ตามมาตรา 40 (แถวในแบบ 50 ทวิ)
const WHT_INCOME_ROWS = [
  { code: 1, label: "1. เงินเดือน ค่าจ้าง เบี้ยเลี้ยง โบนัส ฯลฯ ตามมาตรา 40 (1)" },
  { code: 2, label: "2. ค่าธรรมเนียม ค่านายหน้า ฯลฯ ตามมาตรา 40 (2)" },
  { code: 3, label: "3. ค่าแห่งลิขสิทธิ์ ฯลฯ ตามมาตรา 40 (3)" },
  { code: 4, label: "4. ค่าดอกเบี้ย เงินปันผล ฯลฯ ตามมาตรา 40 (4)" },
  { code: 5, label: "5. ค่าเช่าทรัพย์สิน ตามมาตรา 40 (5)" },
  { code: 6, label: "6. ค่าวิชาชีพอิสระ ตามมาตรา 40 (6)" },
  { code: 7, label: "7. ค่าจ้างทำของ ค่ารับเหมา ตามมาตรา 40 (7), (8)" },
  { code: 8, label: "8. อื่นๆ" }
];
const WHT_FORMS = ["ภ.ง.ด.1ก", "ภ.ง.ด.1ก พิเศษ", "ภ.ง.ด.2", "ภ.ง.ด.3", "ภ.ง.ด.2ก", "ภ.ง.ด.3ก", "ภ.ง.ด.53"];
const WHT_CONDITIONS = ["(1) หัก ณ ที่จ่าย", "(2) ออกให้ตลอดไป", "(3) ออกให้ครั้งเดียว", "(4) อื่นๆ"];

// =============== Printable paper: หนังสือรับรองการหักภาษี ณ ที่จ่าย (50 ทวิ) ===============
function WHTCertPaper({ cert }) {
  const C = window.SSSData.Company;
  const { fmtM, bahtText } = window.UI;
  const color = window.getDocColor("wht-cert");
  const colorSoft = window.hexA(color, 0.07);
  const colorLine = window.hexA(color, 0.22);

  const base = Number(cert.base) || 0;
  const wht = Number(cert.wht) || 0;
  const Chk = ({ on }) => (
    <span style={{display: "inline-flex", alignItems: "center", justifyContent: "center", width: 13, height: 13, border: "1.3px solid #44403c", borderRadius: 2, marginRight: 5, flexShrink: 0, background: on ? color : "white", color: "white", lineHeight: 1}}>
      {on ? <span style={{fontSize: 10, fontWeight: 700}}>✓</span> : null}
    </span>
  );

  const PartyBox = ({ title, name, taxId, address, idLabel }) => (
    <div style={{border: `1px solid ${colorLine}`, borderRadius: 6, overflow: "hidden"}}>
      <div style={{background: color, color: "white", padding: "5px 12px", fontSize: 10, fontWeight: 600, letterSpacing: "0.04em"}}>{title}</div>
      <div style={{padding: "9px 12px", fontSize: 11}}>
        <div style={{fontWeight: 700, fontSize: 12.5, color: "#0c0a09"}}>{name}</div>
        <div style={{color: "#57534e", marginTop: 3, lineHeight: 1.55}}>
          <div>{idLabel} <span className="mono" style={{color: "#0c0a09", letterSpacing: "0.04em"}}>{taxId}</span></div>
          <div style={{marginTop: 2}}>ที่อยู่ {address}</div>
        </div>
      </div>
    </div>
  );

  return (
    <div className="doc-paper print-target" style={{fontSize: 11.5, padding: 0, position: "relative", overflow: "hidden"}}>
      <div style={{height: 6, background: color}}/>
      <div style={{padding: "24px 34px 28px"}}>
        {/* Header */}
        <div style={{display: "grid", gridTemplateColumns: "1fr auto", gap: 20, marginBottom: 18, alignItems: "flex-start"}}>
          <div style={{display: "flex", gap: 16, alignItems: "flex-start"}}>
            <div style={{background: color, borderRadius: 6, alignSelf: "stretch", minHeight: 50, maxHeight: 74, display: "flex", alignItems: "center", justifyContent: "center", padding: "7px 14px", flexShrink: 0}}><img src="assets/logo-ink.png" alt={C.name} style={{width: 116, maxHeight: "100%", objectFit: "contain", display: "block"}}/></div>
            <div style={{paddingTop: 2}}>
              <div style={{fontWeight: 700, fontSize: 12.5, lineHeight: 1.25, color: "#0c0a09"}}>{C.name}</div>
              <div style={{fontSize: 10, color: "#78716c", marginTop: 1}}>{C.nameEn}</div>
              <div style={{fontSize: 10, color: "#57534e", marginTop: 5, lineHeight: 1.45, maxWidth: 320}}>{C.address}</div>
            </div>
          </div>
          <div style={{textAlign: "right", minWidth: 200}}>
            <h1 style={{margin: 0, fontSize: 19, fontWeight: 700, color, letterSpacing: "-0.01em", lineHeight: 1.15}}>หนังสือรับรองการหักภาษี ณ ที่จ่าย</h1>
            <div style={{fontSize: 10, color: "#78716c", marginTop: 3}}>ตามมาตรา 50 ทวิ แห่งประมวลรัษฎากร</div>
            <div style={{fontSize: 9, color: "#a8a29e", letterSpacing: "0.1em", marginTop: 2, fontWeight: 500}}>WITHHOLDING TAX CERTIFICATE</div>
            <div style={{marginTop: 10, display: "inline-block", textAlign: "left", background: colorSoft, padding: "8px 13px", borderRadius: 4, minWidth: 180}}>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 10.5}}><span style={{color: "#78716c"}}>เลขที่</span><b className="mono" style={{color: "#0c0a09"}}>{cert.no}</b></div>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 10.5, marginTop: 3}}><span style={{color: "#78716c"}}>วันที่ออกหนังสือ</span><b style={{color: "#0c0a09"}}>{cert.issueDate}</b></div>
            </div>
          </div>
        </div>

        {/* Parties */}
        <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14}}>
          <PartyBox title="ผู้มีหน้าที่หักภาษี ณ ที่จ่าย (ผู้จ่ายเงิน)" name={C.name} taxId={C.taxId} address={C.address} idLabel="เลขประจำตัวผู้เสียภาษีอากร"/>
          <PartyBox title="ผู้ถูกหักภาษี ณ ที่จ่าย (ผู้รับเงิน)" name={cert.payee} taxId={cert.payeeTaxId} address={cert.payeeAddress} idLabel={cert.payeeType === "corp" ? "เลขประจำตัวผู้เสียภาษีอากร" : "เลขประจำตัวประชาชน"}/>
        </div>

        {/* Form ticks */}
        <div style={{border: "1px solid #e7e5e4", borderRadius: 6, padding: "8px 12px", marginBottom: 12}}>
          <div style={{fontSize: 10, color: "#78716c", marginBottom: 6, fontWeight: 600}}>ลำดับที่ในแบบยื่นรายการ — รวมไว้ในแบบ</div>
          <div style={{display: "flex", flexWrap: "wrap", gap: "5px 16px"}}>
            {WHT_FORMS.map(f => (
              <span key={f} style={{display: "inline-flex", alignItems: "center", fontSize: 10.5, color: f === cert.form ? "#0c0a09" : "#78716c", fontWeight: f === cert.form ? 600 : 400}}>
                <Chk on={f === cert.form}/>{f}
              </span>
            ))}
          </div>
        </div>

        {/* Income table */}
        <table style={{borderCollapse: "separate", borderSpacing: 0, width: "100%"}}>
          <thead>
            <tr>
              <th style={{background: color, color: "white", padding: "8px 12px", fontSize: 10, fontWeight: 600, textAlign: "left", borderTopLeftRadius: 4}}>ประเภทเงินได้พึงประเมินที่จ่าย</th>
              <th style={{width: 96, background: color, color: "white", padding: "8px 8px", fontSize: 10, fontWeight: 600, textAlign: "center"}}>วัน เดือน ปี ที่จ่าย</th>
              <th style={{width: 104, background: color, color: "white", padding: "8px 10px", fontSize: 10, fontWeight: 600, textAlign: "right"}}>จำนวนเงินที่จ่าย</th>
              <th style={{width: 104, background: color, color: "white", padding: "8px 10px", fontSize: 10, fontWeight: 600, textAlign: "right", borderTopRightRadius: 4}}>ภาษีที่หักนำส่ง</th>
            </tr>
          </thead>
          <tbody>
            {WHT_INCOME_ROWS.map((row, i) => {
              const active = row.code === cert.incomeCode;
              return (
                <tr key={row.code} style={{background: active ? colorSoft : (i % 2 === 0 ? "white" : "#fafaf9")}}>
                  <td style={{padding: "7px 12px", borderBottom: "1px solid #f1efeb", fontSize: 10.5, color: active ? "#0c0a09" : "#57534e", fontWeight: active ? 600 : 400}}>
                    {row.label}
                    {active && cert.incomeLabel && <span style={{fontWeight: 400, color: "#57534e"}}> — {cert.incomeLabel}</span>}
                  </td>
                  <td style={{padding: "7px 8px", borderBottom: "1px solid #f1efeb", textAlign: "center", fontSize: 10.5, color: "#0c0a09"}}>{active ? cert.payDate : ""}</td>
                  <td style={{padding: "7px 10px", borderBottom: "1px solid #f1efeb", textAlign: "right", fontSize: 10.5, fontWeight: active ? 600 : 400, color: "#0c0a09"}}>{active ? fmtM(base) : ""}</td>
                  <td style={{padding: "7px 10px", borderBottom: "1px solid #f1efeb", textAlign: "right", fontSize: 10.5, fontWeight: active ? 600 : 400, color: "#0c0a09"}}>{active ? fmtM(wht) : ""}</td>
                </tr>
              );
            })}
            <tr style={{background: "#f3f1ee", fontWeight: 700}}>
              <td style={{padding: "9px 12px", fontSize: 11, color: "#0c0a09"}}>รวมเงินที่จ่ายและภาษีที่หักนำส่ง</td>
              <td style={{padding: "9px 8px"}}></td>
              <td style={{padding: "9px 10px", textAlign: "right", fontSize: 11, color: "#0c0a09"}}>{fmtM(base)}</td>
              <td style={{padding: "9px 10px", textAlign: "right", fontSize: 11.5, color}}>{fmtM(wht)}</td>
            </tr>
          </tbody>
        </table>

        {/* Amount in words */}
        <div style={{marginTop: 10, padding: "8px 13px", background: colorSoft, borderRadius: 5, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12}}>
          <span style={{fontSize: 11, color: "#44403c"}}>รวมเงินภาษีที่หักนำส่ง (ตัวอักษร)</span>
          <span style={{fontSize: 11.5, fontWeight: 700, color: "#0c0a09"}}>{bahtText(wht)}</span>
        </div>

        {/* Conditions */}
        <div style={{marginTop: 12, display: "flex", flexWrap: "wrap", gap: "5px 18px", alignItems: "center"}}>
          <span style={{fontSize: 10.5, color: "#78716c", fontWeight: 600}}>ผู้จ่ายเงิน:</span>
          {WHT_CONDITIONS.map((cond, i) => (
            <span key={cond} style={{display: "inline-flex", alignItems: "center", fontSize: 10.5, color: i === 0 ? "#0c0a09" : "#78716c"}}>
              <Chk on={i === 0}/>{cond}
            </span>
          ))}
        </div>

        {/* Warning */}
        <div style={{marginTop: 12, padding: "8px 12px", background: "#fefdf9", border: "1px solid #f1efeb", borderRadius: 4, fontSize: 9.5, color: "#78716c", lineHeight: 1.5}}>
          คำเตือน — ผู้มีหน้าที่ออกหนังสือรับรองการหักภาษี ณ ที่จ่าย ฝ่าฝืนไม่ปฏิบัติตามมาตรา 50 ทวิ แห่งประมวลรัษฎากร ต้องรับโทษทางอาญาตามมาตรา 35 แห่งประมวลรัษฎากร
        </div>

        {/* Signature */}
        <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 30, marginTop: 26, fontSize: 10.5}}>
          <div style={{fontSize: 10, color: "#57534e", lineHeight: 1.6}}>
            <div>อ้างอิงเอกสาร: <span className="mono" style={{color: "#0c0a09"}}>{cert.ref || "—"}</span></div>
            <div style={{marginTop: 2}}>นำส่งในแบบ <b style={{color: "#0c0a09"}}>{cert.form}</b> งวดเดือนที่จ่าย</div>
          </div>
          <div style={{textAlign: "center"}}>
            <div style={{borderTop: "1px dashed #57534e", paddingTop: 6, marginTop: 30}}>
              <div style={{fontWeight: 600, color: "#0c0a09"}}>ผู้มีอำนาจลงนาม / ผู้จ่ายเงิน</div>
              <div style={{color: "#78716c", fontSize: 9.5, marginTop: 2}}>( {C.currentUser.name} )</div>
              <div style={{color: "#a8a29e", fontSize: 9.5, marginTop: 2}}>ประทับตรานิติบุคคล (ถ้ามี) · วันที่ {cert.issueDate}</div>
            </div>
          </div>
        </div>

        <div style={{marginTop: 20, paddingTop: 9, borderTop: `2px solid ${color}`, fontSize: 9, color: "#78716c", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
          <span><b style={{color: "#44403c"}}>{C.name}</b> · หนังสือรับรองหัก ณ ที่จ่าย (50 ทวิ)</span>
          <span>{cert.no} · ออกโดยระบบ SSS</span>
        </div>
      </div>
    </div>
  );
}

// =============== List page ===============
function WHTCertificates({ navigate }) {
  const D = window.SSSData;
  const { Btn, Badge, Card, PageHead, Tabs, fmt0 } = window.UI;
  const [tab, setTab] = useStateW("all");
  const [q, setQ] = useStateW("");
  const [dateF, setDateF] = useStateW({ mode: "all" });
  const [active, setActive] = useStateW(null);
  const [creating, setCreating] = useStateW(false);
  const rows = D.WHTCertificates;

  const tabs = [
    { key: "all", label: "ทั้งหมด", count: rows.length },
    { key: "ภ.ง.ด.3", label: "ภ.ง.ด.3 (บุคคล)", count: rows.filter(r => r.form === "ภ.ง.ด.3").length },
    { key: "ภ.ง.ด.53", label: "ภ.ง.ด.53 (นิติบุคคล)", count: rows.filter(r => r.form === "ภ.ง.ด.53").length }
  ];
  const byTab = tab === "all" ? rows : rows.filter(r => r.form === tab);
  const byQ = q.trim() ? byTab.filter(r => (r.no + " " + r.payee + " " + r.payeeTaxId + " " + r.incomeLabel).toLowerCase().includes(q.trim().toLowerCase())) : byTab;
  const list = byQ.filter(r => !window.DocDates || window.DocDates.match(dateF, r.issueDate));
  const whtTotal = rows.reduce((s, r) => s + (r.wht || 0), 0);
  const baseTotal = rows.reduce((s, r) => s + (r.base || 0), 0);

  return (
    <>
      <PageHead
        title="หนังสือรับรองหัก ณ ที่จ่าย · 50 ทวิ"
        sub="ออกให้ผู้ถูกหักทุกครั้งที่จ่ายเงินและหักภาษีไว้ — เป็นหลักฐานว่าบริษัทนำส่งสรรพากรแทน (ตามมาตรา 50 ทวิ)"
        right={<>
          <Btn icon={I.download} kind="ghost" onClick={() => window.exportRowsCSV && window.exportRowsCSV("หนังสือรับรองหัก ณ ที่จ่าย", [
            { key: "no", label: "เลขที่" }, { key: "issueDate", label: "วันที่ออก" }, { key: "payee", label: "ผู้ถูกหัก" },
            { key: "payeeTaxId", label: "เลขผู้เสียภาษี" }, { key: "incomeLabel", label: "ประเภทเงินได้" },
            { key: "base", label: "จำนวนเงินที่จ่าย" }, { key: "rate", label: "อัตรา %" }, { key: "wht", label: "ภาษีหัก" }, { key: "form", label: "แบบ" }
          ], list)}>ส่งออก</Btn>
          <Btn icon={I.plus} kind="primary" onClick={() => setCreating(true)}>ออกหนังสือรับรอง</Btn>
        </>}
      />

      <div className="grid cols-4 mb-lg">
        <UI.Stat label="หนังสือรับรองเดือนนี้" value={rows.length} sub={`รวมหักภาษี ฿${fmt0(whtTotal)}`} icon={I.tax}/>
        <UI.Stat label="ฐานเงินได้ที่จ่าย" value={`฿${fmt0(baseTotal)}`} sub="ก่อนหักภาษี" icon={I.money}/>
        <UI.Stat label="ภ.ง.ด.3 (บุคคล)" value={rows.filter(r => r.form === "ภ.ง.ด.3").length} sub={`฿${fmt0(rows.filter(r=>r.form==='ภ.ง.ด.3').reduce((s,r)=>s+r.wht,0))}`} icon={I.user}/>
        <UI.Stat label="ภ.ง.ด.53 (นิติบุคคล)" value={rows.filter(r => r.form === "ภ.ง.ด.53").length} sub={`฿${fmt0(rows.filter(r=>r.form==='ภ.ง.ด.53').reduce((s,r)=>s+r.wht,0))}`} icon={I.building}/>
      </div>

      <div style={{display: "flex", gap: 10, padding: "12px 14px", marginBottom: 14, background: window.hexA(window.getDocColor("wht-cert"), 0.06), border: `1px solid ${window.hexA(window.getDocColor("wht-cert"), 0.2)}`, borderRadius: 10, fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.6}}>
        <I.calc size={16} style={{flexShrink: 0, marginTop: 1, color: window.getDocColor("wht-cert")}}/>
        <span><b style={{color: "var(--ink-1)"}}>ออกหัก ณ ที่จ่ายยังไง:</b> ตอนจ่ายเงิน — บันทึกยอดหักในใบสำคัญรับเงิน (บุคคล) หรือใบสำคัญจ่าย (นิติบุคคล) → กด <b>"ออกหนังสือรับรอง"</b> ที่นี่เพื่อมอบ 50 ทวิ ให้ผู้ถูกหัก → สิ้นเดือนระบบรวมยอดยื่น ภ.ง.ด.1/3/53 ที่หน้าบัญชี (ครบกำหนดวันที่ 7 ของเดือนถัดไป)</span>
      </div>

      <Card flush padded={false}>
        <div style={{padding: 12, borderBottom: "1px solid var(--line)", display: "flex", gap: 10, alignItems: "center"}}>
          <Tabs items={tabs} active={tab} onChange={setTab}/>
          <span className="spacer"/>
          <div className="search" style={{width: 240}}><I.search size={14}/><input placeholder="ค้นหาผู้ถูกหัก / เลขที่…" value={q} onChange={e => setQ(e.target.value)}/></div>
          {window.DateFilter && <window.DateFilter value={dateF} onChange={setDateF}/>}
        </div>
        <div className="table-wrap">
          <table className="t">
            <thead><tr>
              <th>เลขที่</th><th>วันที่ออก</th><th>ผู้ถูกหักภาษี</th><th>ประเภทเงินได้</th>
              <th className="right">เงินที่จ่าย</th><th className="right">อัตรา</th><th className="right">ภาษีหัก</th>
              <th>แบบยื่น</th><th>สถานะ</th><th></th>
            </tr></thead>
            <tbody>
              {list.map(r => (
                <tr key={r.no} className="row-clickable" onClick={() => setActive(r)}>
                  <td className="mono">{r.no}</td>
                  <td>{r.issueDate}</td>
                  <td>{r.payee}<div style={{fontSize: 11, color: "var(--ink-3)"}} className="mono">{r.payeeTaxId}</div></td>
                  <td className="muted" style={{maxWidth: 240}}><span style={{display: "block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{r.incomeLabel}</span></td>
                  <td className="right amount">฿{fmt0(r.base)}</td>
                  <td className="right">{r.rate}%</td>
                  <td className="right amount" style={{fontWeight: 600}}>฿{fmt0(r.wht)}</td>
                  <td><Badge tone={r.form === "ภ.ง.ด.53" ? "info" : ""}>{r.form}</Badge></td>
                  <td><Badge tone={r.status === "ออกแล้ว" ? "success" : "outline"}>{r.status}</Badge></td>
                  <td onClick={e => e.stopPropagation()}>
                    <Btn kind="ghost" size="sm" icon={I.chevronRight} onClick={() => setActive(r)}/>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {active && <WHTCertDrawer cert={active} onClose={() => setActive(null)}/>}
      {creating && <WHTCertCreate onClose={() => setCreating(false)}/>}
    </>
  );
}

// =============== Preview drawer (view + print) ===============
function WHTCertDrawer({ cert, onClose }) {
  const { Btn, Badge, fmt0 } = window.UI;
  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer wide" style={{width: 820}}>
        <div className="drawer-head">
          <I.tax size={16}/>
          <h3>หนังสือรับรองหัก ณ ที่จ่าย {cert.no}</h3>
          <span className="spacer"/>
          <Badge tone={cert.status === "ออกแล้ว" ? "success" : "outline"}>{cert.status}</Badge>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>
        <div className="drawer-body" style={{background: "var(--surface-2)"}}>
          <div style={{display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10, marginBottom: 14}}>
            <div className="field"><label>ผู้ถูกหัก</label><div className="input" style={{display: "flex", alignItems: "center"}}>{cert.payee}</div></div>
            <div className="field"><label>จำนวนเงินที่จ่าย</label><div className="input amount" style={{display: "flex", alignItems: "center"}}>฿{fmt0(cert.base)}</div></div>
            <div className="field"><label>ภาษีหัก ({cert.rate}%)</label><div className="input amount" style={{display: "flex", alignItems: "center", fontWeight: 600}}>฿{fmt0(cert.wht)}</div></div>
          </div>
          <WHTCertPaper cert={cert}/>
        </div>
        <div className="drawer-foot">
          <Btn kind="ghost" onClick={onClose}>ปิด</Btn>
          <Btn icon={I.print} kind="ghost" onClick={() => setTimeout(() => window.printDocPaperWithOptions(), 250)}>พิมพ์</Btn>
          <Btn icon={I.download} kind="primary" onClick={() => setTimeout(() => window.printDocPaperWithOptions(), 250)}>ดาวน์โหลด PDF</Btn>
        </div>
      </div>
    </>
  );
}

// =============== Create drawer (form + live preview) ===============
function WHTCertCreate({ onClose, initial }) {
  const C = window.SSSData.Company;
  const { Btn } = window.UI;
  const [no, setNo] = useStateW(initial?.no || "50ทวิ-2569-0008");
  const [issueDate, setIssueDate] = useStateW(initial?.issueDate || "22 พ.ค. 2569");
  const [payeeType, setPayeeType] = useStateW(initial?.payeeType || "individual");
  const [payee, setPayee] = useStateW(initial?.payee || "");
  const [payeeTaxId, setPayeeTaxId] = useStateW(initial?.payeeTaxId || "");
  const [payeeAddress, setPayeeAddress] = useStateW(initial?.payeeAddress || "");
  const [incomeCode, setIncomeCode] = useStateW(initial?.incomeCode || 8);
  const [incomeLabel, setIncomeLabel] = useStateW(initial?.incomeLabel || "");
  const [payDate, setPayDate] = useStateW(initial?.payDate || "22 พ.ค. 2569");
  const [base, setBase] = useStateW(initial?.base || 0);
  const [rate, setRate] = useStateW(initial?.rate != null ? initial.rate : 3);
  const [ref, setRef] = useStateW(initial?.ref || "");

  const form = payeeType === "corp" ? "ภ.ง.ด.53" : "ภ.ง.ด.3";
  const wht = Math.round((Number(base) || 0) * (Number(rate) || 0)) / 100;
  const cert = {
    no, issueDate, payeeType, form,
    payee: payee || "(ชื่อผู้ถูกหักภาษี)", payeeTaxId: payeeTaxId || "—",
    payeeAddress: payeeAddress || "—", incomeCode: Number(incomeCode),
    incomeLabel, payDate, base: Number(base) || 0, rate: Number(rate) || 0, wht, ref
  };

  const save = () => { onClose && onClose(); window.toast && window.toast(`ออกหนังสือรับรองหัก ณ ที่จ่าย ${no} แล้ว`); window.logActivity && window.logActivity("ออก 50 ทวิ", `${no} — ${payee} ฿${wht}`, "tax"); };

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer wide newdoc-drawer" style={{width: 1060}}>
        <div className="drawer-head">
          <I.tax size={16}/>
          <h3>ออกหนังสือรับรองหัก ณ ที่จ่าย (50 ทวิ)</h3>
          <span className="mono muted" style={{fontSize: 12}}>{no}</span>
          <span className="spacer"/>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>
        <div className="drawer-body" style={{padding: 0, display: "grid", gridTemplateColumns: "1fr 1fr"}}>
          <div style={{padding: 18, borderRight: "1px solid var(--line)", overflowY: "auto"}}>
            <div className="h2 mb">ข้อมูลเอกสาร</div>
            <div className="field-row cols-2 mb">
              <div className="field"><label>เลขที่</label><input className="input mono" value={no} onChange={e=>setNo(e.target.value)}/></div>
              <div className="field"><label>วันที่ออกหนังสือ</label><input className="input" value={issueDate} onChange={e=>setIssueDate(e.target.value)}/></div>
            </div>

            <div className="h2 mt-lg mb">ผู้ถูกหักภาษี ณ ที่จ่าย</div>
            <div className="field mb"><label>ประเภทผู้ถูกหัก</label>
              <select className="input" value={payeeType} onChange={e=>setPayeeType(e.target.value)}>
                <option value="individual">บุคคลธรรมดา → ยื่น ภ.ง.ด.3</option>
                <option value="corp">นิติบุคคล → ยื่น ภ.ง.ด.53</option>
              </select>
            </div>
            <div className="field mb"><label>ชื่อผู้ถูกหัก</label><input className="input" value={payee} onChange={e=>setPayee(e.target.value)} placeholder={payeeType === "corp" ? "เช่น บริษัท เหล็กไทยพานิช จำกัด" : "เช่น นายวีระ ช่างกล"}/></div>
            <div className="field-row cols-2 mb">
              <div className="field"><label>{payeeType === "corp" ? "เลขผู้เสียภาษี (13 หลัก)" : "เลขบัตรประชาชน"}</label><input className="input mono" value={payeeTaxId} onChange={e=>setPayeeTaxId(e.target.value)} placeholder="x-xxxx-xxxxx-xx-x"/></div>
              <div className="field"><label>อ้างอิง (RV/PV/JOB)</label><input className="input mono" value={ref} onChange={e=>setRef(e.target.value)} placeholder="—"/></div>
            </div>
            <div className="field mb"><label>ที่อยู่</label><textarea className="textarea" value={payeeAddress} onChange={e=>setPayeeAddress(e.target.value)} style={{minHeight: 48}} placeholder="ที่อยู่ผู้ถูกหัก"/></div>

            <div className="h2 mt-lg mb">เงินได้และภาษี</div>
            <div className="field mb"><label>ประเภทเงินได้ (ตามมาตรา 40)</label>
              <select className="input" value={incomeCode} onChange={e=>setIncomeCode(Number(e.target.value))}>
                {WHT_INCOME_ROWS.map(r => <option key={r.code} value={r.code}>{r.label}</option>)}
              </select>
            </div>
            <div className="field mb"><label>รายละเอียดเงินได้</label><input className="input" value={incomeLabel} onChange={e=>setIncomeLabel(e.target.value)} placeholder="เช่น ค่าเช่าโกดัง / ค่ารับเหมา / ค่าขนส่ง"/></div>
            <div className="field-row cols-3">
              <div className="field"><label>วันที่จ่าย</label><input className="input" value={payDate} onChange={e=>setPayDate(e.target.value)}/></div>
              <div className="field"><label>เงินที่จ่าย (ฐาน)</label><input className="input" type="number" value={base} onChange={e=>setBase(e.target.value)} style={{textAlign: "right"}}/></div>
              <div className="field"><label>อัตราหัก %</label>
                <select className="input" value={rate} onChange={e=>setRate(Number(e.target.value))}>
                  <option value={1}>1% (ค่าขนส่ง)</option>
                  <option value={2}>2% (โฆษณา)</option>
                  <option value={3}>3% (รับเหมา/บริการ)</option>
                  <option value={5}>5% (ค่าเช่า)</option>
                </select>
              </div>
            </div>
            <div style={{marginTop: 16, padding: "12px 14px", background: "var(--surface-2)", borderRadius: 8, display: "flex", justifyContent: "space-between", alignItems: "center"}}>
              <div style={{fontSize: 12.5, color: "var(--ink-3)"}}>ภาษีหัก ณ ที่จ่าย ({rate}% ของ ฿{window.UI.fmt0(Number(base)||0)}) · ยื่น <b style={{color: "var(--ink-1)"}}>{form}</b></div>
              <div className="amount" style={{fontSize: 20, fontWeight: 700, color: window.getDocColor("wht-cert")}}>฿{window.UI.fmtM(wht)}</div>
            </div>
          </div>

          <div style={{padding: 18, overflowY: "auto", background: "var(--surface-2)"}}>
            <div className="h2 mb muted" style={{display: "flex", alignItems: "center", gap: 6}}><I.doc size={14}/> ตัวอย่างเอกสาร (พิมพ์ได้)</div>
            <WHTCertPaper cert={cert}/>
          </div>
        </div>
        <div className="drawer-foot">
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn icon={I.print} onClick={() => setTimeout(() => window.printDocPaperWithOptions(), 250)}>บันทึก + พิมพ์</Btn>
          <Btn kind="primary" icon={I.check} onClick={save}>บันทึก + ออกหนังสือ</Btn>
        </div>
      </div>
    </>
  );
}

// =============== Host (open create/preview from anywhere) ===============
function WHTCertHost() {
  const [createInit, setCreateInit] = useStateW(null);
  const [viewCert, setViewCert] = useStateW(null);
  useEffectW(() => {
    window.openWHTCertCreate = (initial) => { setViewCert(null); setCreateInit(initial || {}); };
    window.openWHTCert = (cert) => { setCreateInit(null); setViewCert(cert); };
    // Build a 50-ทวิ draft straight from a Receipt Voucher that already has wht
    window.openWHTCertFromRV = (rv) => {
      const rate = rv.amount ? Math.round((rv.wht / rv.amount) * 100) : 5;
      window.openWHTCertCreate({
        no: "50ทวิ-2569-" + String(rv.no).slice(-4),
        issueDate: rv.date, payeeType: "individual",
        payee: rv.payee, payeeTaxId: rv.idcard || "", payeeAddress: rv.address || "",
        incomeCode: 5, incomeLabel: rv.purpose, payDate: rv.date,
        base: rv.amount, rate: rate || 5, ref: rv.no
      });
    };
  }, []);
  return (
    <>
      {createInit && <WHTCertCreate initial={createInit} onClose={() => setCreateInit(null)}/>}
      {viewCert && <WHTCertDrawer cert={viewCert} onClose={() => setViewCert(null)}/>}
    </>
  );
}

window.WHTCertificates = WHTCertificates;
window.WHTCertPaper = WHTCertPaper;
window.WHTCertHost = WHTCertHost;
