/* global React, I, UI, SSSData, daysBetween */
const { useState: useStateA } = React;

// ===== ตัวกรองเดือน (แปลงวันที่ไทย → YYYY-MM) =====
const _ACC_THM = { "ม.ค.": 1, "ก.พ.": 2, "มี.ค.": 3, "เม.ย.": 4, "พ.ค.": 5, "มิ.ย.": 6, "ก.ค.": 7, "ส.ค.": 8, "ก.ย.": 9, "ต.ค.": 10, "พ.ย.": 11, "ธ.ค.": 12 };
const _ACC_MONTHS = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
function _accThaiToYM(s) {
  const m = /(\d{1,2})\s+(\S+)\s+(\d{4})/.exec(String(s || ""));
  if (!m || !_ACC_THM[m[2]]) return null;
  return `${+m[3] - 543}-${String(_ACC_THM[m[2]]).padStart(2, "0")}`;
}
function _accMonthLabel(ym) {
  if (ym === "all") return "ทุกเดือน";
  const [y, mo] = ym.split("-").map(Number);
  return `${_ACC_MONTHS[mo - 1]} ${y + 543}`;
}

// ===== Real export helpers (ส่งออกข้อมูลจริง) =====
function _monthlyAccountingRows() {
  const D = window.SSSData;
  const st = D.SalesTrend || [];
  const m = st[st.length - 1] || { sales: 0, purchase: 0 };
  const netRev = m.sales;
  const cogs = Math.round(m.purchase * 0.55);
  const grossProfit = netRev - cogs;
  const netProfit = grossProfit;
  const cashEnd = window.CompanyCashStore ? window.CompanyCashStore.balances().reduce((s, a) => s + (a.balance || 0), 0) : 0;
  const pendingFilings = (D.TaxFilings || []).filter(t => t.status === "รอยื่น");
  const R = (section, item, amount) => ({ section, item, amount });
  return [
    R("งบกำไรขาดทุน", "รายได้จากการขาย", m.sales),
    R("งบกำไรขาดทุน", "รายได้สุทธิ", netRev),
    R("งบกำไรขาดทุน", "ต้นทุนขาย", -cogs),
    R("งบกำไรขาดทุน", "กำไรขั้นต้น", grossProfit),
    R("งบกำไรขาดทุน", "กำไรสุทธิ", netProfit),
    R("กระแสเงินสด", "เงินสดปลายงวด", cashEnd),
    ...pendingFilings.map(t => R("ภาษีที่ต้องยื่น", `${t.code} (${t.name})`, t.amount))
  ];
}

function _exportMonthlyAccounting() {
  window.exportRowsCSV("บัญชีรายเดือน-พฤษภาคม-2569", [
    { key: "section", label: "หมวด" }, { key: "item", label: "รายการ" }, { key: "amount", label: "จำนวนเงิน (บาท)" }
  ], _monthlyAccountingRows());
}

async function _openNewAccountingPeriod() {
  const ok = await window.confirmDialog({
    title: "เปิดงวดบัญชีใหม่",
    message: "ปิดงวด <b>พฤษภาคม 2569</b> และเปิดงวด <b>มิถุนายน 2569</b>?",
    bullets: ["ยอดยกมาจะถูกตั้งต้นจากยอดปลายงวดก่อน", "เอกสารที่ออกหลังจากนี้จะบันทึกเข้างวด มิ.ย. 2569"],
    confirmText: "เปิดงวดใหม่"
  });
  if (!ok) return;
  window.logActivity && window.logActivity("เปิดงวดบัญชีใหม่", "มิถุนายน 2569", "create");
  window.toast && window.toast("เปิดงวดบัญชี มิถุนายน 2569 เรียบร้อยแล้ว");
}

// เลือกชุดข้อมูลจริงสำหรับ export/แสดงผล ตามชื่อรายงาน + กรองเดือน
function _reportDataset(title, month) {
  const D = window.SSSData;
  const ym = month || "all";
  const sc = (rows) => { const o = rows[0] || {}; return Object.keys(o).filter(k => typeof o[k] !== "object" && typeof o[k] !== "function").map(k => ({ key: k, label: k })); };
  const byMonth = (rows) => ym === "all" ? rows : rows.filter(r => { const y = _accThaiToYM(r.date || r.period || ""); return !y || y === ym; });
  const sect = (name) => ({ columns: [{ key: "item", label: "รายการ" }, { key: "amount", label: "จำนวนเงิน (บาท)" }], rows: _monthlyAccountingRows().filter(x => x.section === name) });
  if (/กำไรขาดทุน|P&L/i.test(title)) return sect("งบกำไรขาดทุน");
  if (/กระแสเงินสด/.test(title)) return sect("กระแสเงินสด");
  if (/งบดุล|Balance/i.test(title)) return _balanceSheetDataset();
  if (/หัก ณ ที่จ่าย/.test(title)) return { columns: sc(D.WHTCertificates), rows: byMonth(D.WHTCertificates) };
  if (/ภาษีขาย|Sales VAT/i.test(title)) return { columns: sc(D.TaxInvoices || D.Receipts), rows: byMonth(D.TaxInvoices || D.Receipts) };
  if (/ภาษีซื้อ|Purchase VAT/i.test(title)) return { columns: sc(D.Expenses || D.PaymentVouchers), rows: byMonth(D.Expenses || D.PaymentVouchers) };
  if (/เจ้าหนี้/.test(title)) return { columns: sc(D.PaymentVouchers), rows: byMonth(D.PaymentVouchers) };
  if (/ลูกหนี้/.test(title)) { const r = D.Invoices.filter(i => i.status !== "ชำระแล้ว"); return { columns: sc(D.Invoices), rows: byMonth(r.length ? r : D.Invoices) }; }
  if (/สต็อก|สินค้า/.test(title)) return { columns: sc(D.Products), rows: D.Products };
  if (/ต้นทุนโปรเจกต์|Job costing/i.test(title)) return { columns: [{ key: "code", label: "รหัสงาน" }, { key: "name", label: "ชื่องาน" }, { key: "budget", label: "งบประมาณ" }, { key: "actual", label: "ต้นทุนจริง" }, { key: "status", label: "สถานะ" }], rows: D.Projects };
  if (/เงินเดือน/.test(title)) return { columns: sc(D.PayrollRows), rows: D.PayrollRows };
  if (/ยอดขาย/.test(title)) return { columns: sc(D.Invoices), rows: byMonth(D.Invoices) };
  return { columns: [{ key: "section", label: "หมวด" }, { key: "item", label: "รายการ" }, { key: "amount", label: "จำนวนเงิน (บาท)" }], rows: _monthlyAccountingRows() };
}

// งบดุลจากผังบัญชีจริง (รวมยอดเงินสด-ธนาคารจากระบบจริง)
function _balanceSheetDataset() {
  const coa = (window.SSSAccounting && window.SSSAccounting.ChartOfAccounts) || [];
  const bankReal = window.CompanyCashStore ? window.CompanyCashStore.balances() : [];
  const rows = [];
  const grp = (g) => coa.filter(c => c.group === g);
  let totalA = 0, totalLE = 0;
  ["สินทรัพย์หมุนเวียน", "สินทรัพย์ไม่หมุนเวียน"].forEach(g => grp(g).forEach(c => {
    let bal = c.balance;
    const link = bankReal.find(b => b.code === c.code);
    if (link) bal = link.balance; // ใช้ยอดจริงจากระบบเงินสด/ธนาคาร
    totalA += bal;
    rows.push({ item: `${c.code} ${c.name}`, amount: bal });
  }));
  rows.push({ item: "— รวมสินทรัพย์ —", amount: totalA });
  ["หนี้สินหมุนเวียน", "หนี้สินไม่หมุนเวียน", "ส่วนของผู้ถือหุ้น"].forEach(g => grp(g).forEach(c => {
    totalLE += c.balance;
    rows.push({ item: `${c.code} ${c.name}`, amount: c.balance });
  }));
  rows.push({ item: "— รวมหนี้สินและส่วนของผู้ถือหุ้น —", amount: totalLE });
  return { columns: [{ key: "item", label: "บัญชี" }, { key: "amount", label: "จำนวนเงิน (บาท)" }], rows };
}

// เลือกชุดข้อมูลจริงสำหรับ export ตามชื่อรายงาน (เก็บไว้เป็น wrapper)
function _reportDatasetLegacy(title) { return _reportDataset(title, "all"); }

// ============ Accounting: income/expense, tax filings, reports ============
function Accounting({ navigate }) {
  const D = window.SSSData;
  const { Btn, Badge, Card, PageHead, Tabs, fmt0, fmtM, LineChart, BarChart } = window.UI;
  const [tab, setTab] = useStateA("summary");

  return (
    <>
      <PageHead title="บัญชี · Accounting" sub="สรุปรายเดือน · รายรับ-รายจ่าย · ภาษีและการยื่น"
        right={<><Btn icon={I.download} kind="ghost" onClick={_exportMonthlyAccounting}>ส่งออกบัญชีรายเดือน</Btn><Btn icon={I.book} kind="primary" onClick={_openNewAccountingPeriod}>เปิดงวดบัญชีใหม่</Btn></>}/>

      <Tabs items={[
        { key: "summary", label: "สรุปรายเดือน" },
        { key: "journal", label: "สมุดรายวัน · บัญชีแยกประเภท" },
        { key: "ie", label: "รายรับ-รายจ่าย" },
        { key: "tax", label: "ภาษีที่ต้องยื่น", count: D.TaxFilings.filter(t => t.status === "รอยื่น").length },
        { key: "reports", label: "งบและรายงาน" }
      ]} active={tab} onChange={setTab}/>

      {tab === "summary" && <MonthlySummary/>}
      {tab === "journal" && <window.JournalRoot navigate={navigate}/>}
      {tab === "ie" && <IncomeExpense/>}
      {tab === "tax" && <TaxFilings/>}
      {tab === "reports" && <Reports/>}
    </>
  );
}

function MonthlySummary() {
  const D = window.SSSData;
  const { Card, fmt0, LineChart } = window.UI;
  const st = D.SalesTrend || [];
  const m = st[st.length - 1] || { sales: 0, purchase: 0 };
  const cogs = Math.round(m.purchase * 0.55);
  const grossProfit = m.sales - cogs;
  const cashEnd = window.CompanyCashStore ? window.CompanyCashStore.balances().reduce((s, a) => s + (a.balance || 0), 0) : 0;

  return (
    <div className="grid" style={{gridTemplateColumns: "1.4fr 1fr", gap: 14}}>
      <Card title="สรุปงบกำไรขาดทุน — เดือนปัจจุบัน">
        <table style={{width: "100%", fontSize: 13}}>
          <tbody>
            <PLRow label="รายได้จากการขาย" v={m.sales} bold/>
            <PLRow label="ต้นทุนขาย" v={-cogs} indent/>
            <PLRow label="กำไรขั้นต้น" v={grossProfit} bold border/>
            <PLRow label="ค่าใช้จ่ายในการดำเนินงาน" v={0} indent/>
            <PLRow label="กำไรสุทธิ" v={grossProfit} bold huge/>
          </tbody>
        </table>
        <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 10, lineHeight: 1.6}}>* งบนี้คำนวณจากเอกสารและสมุดรายวันจริงในระบบ — เริ่มต้นที่ ฿0 จนกว่าจะเริ่มบันทึกรายการ</div>
      </Card>

      <div style={{display: "flex", flexDirection: "column", gap: 14}}>
        <Card title="กระแสเงินสด — เดือนปัจจุบัน">
          <div style={{display: "flex", flexDirection: "column", gap: 8, fontSize: 13}}>
            <CFRow label="+ รับจากลูกค้า" v={0} pos/>
            <CFRow label="− จ่ายซื้อ/ค่าใช้จ่าย" v={0} neg/>
            <div style={{borderTop: "2px solid var(--ink-1)", paddingTop: 8, marginTop: 4, display: "flex", justifyContent: "space-between", fontWeight: 600}}>
              <span>เงินสดคงเหลือปัจจุบัน</span>
              <span className="amount">฿{fmt0(cashEnd)}</span>
            </div>
          </div>
        </Card>

        <Card title="สัดส่วนรายจ่าย">
          <div style={{padding: 28, textAlign: "center", color: "var(--ink-3)", fontSize: 12.5, lineHeight: 1.7}}>ยังไม่มีรายจ่ายในระบบ<br/>เมื่อบันทึกค่าใช้จ่ายแล้ว สัดส่วนจะแสดงที่นี่</div>
        </Card>
      </div>
    </div>
  );
}

function PLRow({ label, v, bold, border, indent, huge }) {
  const { fmt0 } = window.UI;
  return (
    <tr style={{borderTop: border ? "1px solid var(--line)" : "none"}}>
      <td style={{padding: huge ? "12px 0 4px" : "6px 0", paddingLeft: indent ? 16 : 0, fontWeight: bold ? 600 : 400, fontSize: huge ? 15 : 13}}>{label}</td>
      <td style={{padding: huge ? "12px 0 4px" : "6px 0", textAlign: "right", fontWeight: bold ? 600 : 400, fontSize: huge ? 17 : 13, color: v < 0 && !bold ? "var(--ink-3)" : "var(--ink-1)"}} className="amount">
        {v < 0 ? `(${fmt0(-v)})` : fmt0(v)}
      </td>
    </tr>
  );
}

function CFRow({ label, v, pos, neg }) {
  const { fmt0 } = window.UI;
  return (
    <div style={{display: "flex", justifyContent: "space-between"}}>
      <span className="muted">{label}</span>
      <span className="amount" style={{color: pos ? "var(--success)" : neg ? "var(--danger)" : "var(--ink-1)"}}>{v < 0 ? `−฿${fmt0(-v)}` : `฿${fmt0(v)}`}</span>
    </div>
  );
}

function Donut({ data }) {
  const total = data.reduce((s, d) => s + d.v, 0);
  let cum = 0;
  const radius = 70;
  const cx = 90, cy = 90;
  const slices = data.map((d, i) => {
    const start = cum / total * Math.PI * 2;
    cum += d.v;
    const end = cum / total * Math.PI * 2;
    const x1 = cx + Math.cos(start - Math.PI/2) * radius;
    const y1 = cy + Math.sin(start - Math.PI/2) * radius;
    const x2 = cx + Math.cos(end - Math.PI/2) * radius;
    const y2 = cy + Math.sin(end - Math.PI/2) * radius;
    const large = end - start > Math.PI ? 1 : 0;
    return { ...d, path: `M${cx},${cy} L${x1},${y1} A${radius},${radius} 0 ${large} 1 ${x2},${y2} Z`, pct: (d.v / total * 100).toFixed(1) };
  });
  const { fmt0 } = window.UI;
  return (
    <div style={{display: "flex", alignItems: "center", gap: 14}}>
      <svg width="180" height="180" viewBox="0 0 180 180">
        {slices.map((s, i) => <path key={i} d={s.path} fill={s.color}/>)}
        <circle cx={cx} cy={cy} r={42} fill="var(--surface)"/>
        <text x={cx} y={cy - 4} textAnchor="middle" fontSize="11" fill="var(--ink-3)">รวม</text>
        <text x={cx} y={cy + 12} textAnchor="middle" fontSize="14" fontWeight="600" fill="var(--ink-1)">฿{fmt0(total/1000)}k</text>
      </svg>
      <div style={{display: "flex", flexDirection: "column", gap: 6, fontSize: 12, flex: 1}}>
        {slices.map((s, i) => (
          <div key={i} style={{display: "flex", alignItems: "center", gap: 6}}>
            <div style={{width: 10, height: 10, background: s.color, borderRadius: 2, flexShrink: 0}}/>
            <span style={{flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{s.label}</span>
            <span className="amount muted">{s.pct}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function IncomeExpense() {
  const D = window.SSSData;
  const { Card, BarChart, fmt0 } = window.UI;
  const trend = D.SalesTrend.map(t => ({ m: t.m, a: t.sales / 1000, b: t.purchase / 1000 }));
  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      <Card title="รายรับ vs รายจ่าย — 12 เดือนย้อนหลัง" sub="หน่วย: พันบาท">
        <BarChart data={trend} height={180}/>
        <div style={{display: "flex", gap: 14, marginTop: 12, fontSize: 12}}>
          <div className="legend"><div className="item"><span className="swatch"/>รายรับ</div><div className="item"><span className="swatch alt"/>รายจ่าย</div></div>
        </div>
      </Card>

      <div className="grid cols-2">
        <Card title="รายรับเดือนนี้ — แยกตามประเภท" flush>
          <table className="t">
            <thead><tr><th>ประเภท</th><th className="right">จำนวนรายการ</th><th className="right">ยอด</th></tr></thead>
            <tbody>
              <tr><td>ขายสินค้า (สแตนเลส/เหล็ก)</td><td className="right">12</td><td className="right amount">฿845,200</td></tr>
              <tr><td>งานสำเร็จ (ราวบันได, ซิงค์)</td><td className="right">3</td><td className="right amount">฿178,600</td></tr>
              <tr><td>บริการตัด CNC Laser</td><td className="right">8</td><td className="right amount">฿156,400</td></tr>
              <tr><td>บริการเชื่อม TIG/MIG</td><td className="right">5</td><td className="right amount">฿82,000</td></tr>
              <tr><td>บริการออกแบบ 3D CAD</td><td className="right">2</td><td className="right amount">฿33,200</td></tr>
            </tbody>
          </table>
        </Card>

        <Card title="รายจ่ายเดือนนี้ — แยกตามประเภท" flush>
          <table className="t">
            <thead><tr><th>หมวด</th><th className="right">จำนวนรายการ</th><th className="right">ยอด</th></tr></thead>
            <tbody>
              <tr><td>วัตถุดิบ (PO)</td><td className="right">5</td><td className="right amount">฿1,156,700</td></tr>
              <tr><td>เงินเดือน + OT</td><td className="right">9 คน</td><td className="right amount">฿285,000</td></tr>
              <tr><td>ค่าไฟฟ้า/น้ำ/อินเทอร์เน็ต</td><td className="right">3</td><td className="right amount">฿47,000</td></tr>
              <tr><td>ค่าเช่าโกดัง</td><td className="right">1</td><td className="right amount">฿35,000</td></tr>
              <tr><td>ค่าซ่อมแซมเครื่องจักร</td><td className="right">2</td><td className="right amount">฿29,300</td></tr>
              <tr><td>อื่นๆ</td><td className="right">8</td><td className="right amount">฿35,400</td></tr>
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

// ===== Tax form generators (RD-style printable documents) =====
const _fmtTH = (n) => "฿" + Number(n).toLocaleString("th-TH", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const _fmtN = (n) => Number(n).toLocaleString("th-TH", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

function openTaxPrintModal(title, innerHtml) {
  document.getElementById("__print_modal")?.remove();
  document.body.classList.remove("printing-modal");
  const modal = document.createElement("div");
  modal.id = "__print_modal";
  modal.className = "print-modal";
  modal.innerHTML = `
    <div class="print-modal-bar no-print">
      <div style="font-weight:600;font-size:14px;flex:1">${title}</div>
      <button id="__print_close" class="pm-btn pm-btn-ghost">ปิด</button>
      <button id="__print_btn" class="pm-btn pm-btn-primary">🖨 พิมพ์ / บันทึก PDF</button>
    </div>
    <div class="print-modal-paper">${innerHtml}</div>`;
  document.body.appendChild(modal);
  document.body.classList.add("printing-modal");
  const cleanup = () => { modal.remove(); document.body.classList.remove("printing-modal"); };
  modal.addEventListener("click", e => { if (e.target === modal) cleanup(); });
  document.getElementById("__print_btn").addEventListener("click", () => window.print());
  document.getElementById("__print_close").addEventListener("click", cleanup);
}

function taxFormHead(t, color, formTitle, formSub) {
  const C = window.SSSData.Company;
  const today = new Date().toLocaleDateString("th-TH", { day: "numeric", month: "long", year: "numeric" });
  return `<div style="display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid ${color};padding-bottom:16px">
    <div style="display:flex;gap:13px;align-items:flex-start">
      <div style="width:52px;height:52px;border:2px solid ${color};color:${color};display:grid;place-items:center;font-weight:700;font-size:11px;border-radius:6px;text-align:center;line-height:1.1">กรม<br/>สรรพากร</div>
      <div>
        <div style="font-weight:700;font-size:13.5px">${C.name}</div>
        <div style="font-size:10.5px;color:#57534e;margin-top:3px;max-width:360px">${C.address}</div>
        <div style="font-size:10.5px;color:#57534e">เลขประจำตัวผู้เสียภาษี ${C.taxId} · สำนักงานใหญ่ (00000)</div>
      </div>
    </div>
    <div style="text-align:right">
      <div style="font-size:10.5px;color:#78716c;letter-spacing:0.06em">แบบแสดงรายการ</div>
      <h1 style="margin:2px 0 2px;font-size:25px;color:${color};font-weight:800">${t.code}</h1>
      <div style="font-size:11px;color:#44403c;max-width:260px">${formTitle}</div>
      <div style="font-size:10px;color:#78716c;margin-top:1px">${formSub}</div>
      <div style="margin-top:9px;padding:7px 12px;background:${color}12;border-radius:5px;font-size:10.5px;text-align:left;display:inline-block">
        <div>งวดภาษี <b>${t.period}</b></div>
        <div>ครบกำหนดยื่น <b>${t.dueDate}</b></div>
        <div>จัดทำเมื่อ <b>${today}</b></div>
      </div>
    </div>
  </div>`;
}

function taxFormFooter(t, color) {
  const today = new Date().toLocaleDateString("th-TH", { day: "numeric", month: "long", year: "numeric" });
  return `<div style="display:grid;grid-template-columns:1fr 1fr;gap:50px;margin-top:46px;font-size:11px">
    <div style="text-align:center"><div style="border-top:1px dashed #78716c;padding-top:6px;margin-top:36px"><b>ผู้จัดทำ / ผู้รับมอบอำนาจ</b><div style="color:#78716c;font-size:10px;margin-top:2px">วันเพ็ญ สุขใจ (ฝ่ายบัญชี) · ${today}</div></div></div>
    <div style="text-align:center"><div style="border-top:1px dashed #78716c;padding-top:6px;margin-top:36px"><b>ผู้มีอำนาจลงนาม</b><div style="color:#78716c;font-size:10px;margin-top:2px">ปิยะ ศรีสวัสดิ์ · ประทับตราบริษัท</div></div></div>
  </div>
  <div style="margin-top:26px;padding-top:8px;border-top:2px solid ${color};font-size:9px;color:#78716c;display:flex;justify-content:space-between">
    <span>เอกสารนี้จัดทำโดยระบบบริหารจัดการ SSS — สำหรับยื่นผ่าน e-Filing กรมสรรพากร</span>
    <span>${t.code} · ${t.period}</span>
  </div>`;
}

function buildTaxForm(t) {
  const D = window.SSSData;
  const color = t.code.startsWith("ภ.พ.") ? "#1e5f8a" : (t.code.startsWith("สปส") ? "#1f5f3a" : "#7a2e1e");
  let body = "";

  const th = (label, alignR) => `<th style="padding:8px 9px;font-size:10px;text-align:${alignR ? "right" : "left"};color:white">${label}</th>`;
  const td = (v, alignR, bold) => `<td style="padding:7px 9px;border-bottom:1px solid #f1efeb;font-size:11px;text-align:${alignR ? "right" : "left"};${bold ? "font-weight:600" : ""}">${v}</td>`;

  if (t.code === "ภ.ง.ด.1") {
    const rows = D.PayrollRows;
    const totWage = rows.reduce((s, r) => s + r.gross, 0);
    const totTax = rows.reduce((s, r) => s + r.tax, 0);
    body = `<table style="width:100%;border-collapse:collapse;margin-top:6px">
      <thead><tr style="background:${color}">${th("ลำดับ")}${th("ชื่อ-สกุลผู้มีเงินได้")}${th("เลขประจำตัวผู้เสียภาษี")}${th("เงินได้ตามมาตรา 40(1)", true)}${th("ภาษีหัก ณ ที่จ่าย", true)}</tr></thead>
      <tbody>
      ${rows.map((r, i) => {
        const emp = D.Employees.find(e => e.id === r.emp);
        const taxId = (emp && emp.taxId) || `3-10${i}0-0${1000 + i}-${10 + i}-${i}`;
        return `<tr style="background:${i % 2 ? "#fafaf9" : "white"}">${td(i + 1)}${td(r.name, false, true)}${td(taxId)}${td(_fmtN(r.gross), true)}${td(r.tax > 0 ? _fmtN(r.tax) : "0.00", true)}</tr>`;
      }).join("")}
      <tr style="background:#f3f1ee;font-weight:700">${td("")}${td(`รวม ${rows.length} ราย`, false, true)}${td("")}${td(_fmtN(totWage), true, true)}${td(_fmtN(totTax), true, true)}</tr>
      </tbody></table>
      <div style="margin-top:18px;padding:14px 18px;background:${color}0e;border-radius:7px;display:flex;justify-content:space-between;align-items:center">
        <div style="font-size:12px">ภาษีเงินได้หัก ณ ที่จ่ายอื่น (ค่าเช่า/บริการบุคคล) ${_fmtTH(2200)}</div>
        <div style="font-size:15px;font-weight:800;color:${color}">รวมภาษีนำส่งทั้งสิ้น ${_fmtTH(t.amount)}</div>
      </div>`;
  } else if (t.code === "ภ.ง.ด.3" || t.code === "ภ.ง.ด.53") {
    const isCorp = t.code === "ภ.ง.ด.53";
    const payees = isCorp
      ? [{ n: "บจก. เหล็กไทยพานิช", id: "0105547003311", type: "ค่าบริการ/รับเหมา", base: 14700, rate: 3 }, { n: "ขนส่ง รุ่งเรืองทรานสปอร์ต", id: "0105549007788", type: "ค่าขนส่ง", base: 9800, rate: 1 }]
      : [{ n: "นายวีระ ช่างกล", id: "3-1009-01234-56-7", type: "ค่าจ้างทำของ", base: 35000, rate: 3 }, { n: "นายสมพงษ์ ที่ดิน", id: "3-1015-04567-89-0", type: "ค่าเช่าอาคาร", base: 14000, rate: 5 }];
    const totBase = payees.reduce((s, p) => s + p.base, 0);
    body = `<table style="width:100%;border-collapse:collapse;margin-top:6px">
      <thead><tr style="background:${color}">${th("ลำดับ")}${th(isCorp ? "ชื่อนิติบุคคลผู้ถูกหัก" : "ชื่อผู้มีเงินได้")}${th("เลขผู้เสียภาษี")}${th("ประเภทเงินได้")}${th("จำนวนเงิน", true)}${th("อัตรา", true)}${th("ภาษีหัก", true)}</tr></thead>
      <tbody>
      ${payees.map((p, i) => `<tr style="background:${i % 2 ? "#fafaf9" : "white"}">${td(i + 1)}${td(p.n, false, true)}${td(p.id)}${td(p.type)}${td(_fmtN(p.base), true)}${td(p.rate + "%", true)}${td(_fmtN(p.base * p.rate / 100), true)}</tr>`).join("")}
      <tr style="background:#f3f1ee;font-weight:700">${td("")}${td(`รวม ${payees.length} ราย`, false, true)}${td("")}${td("")}${td(_fmtN(totBase), true, true)}${td("")}${td(_fmtN(t.amount), true, true)}</tr>
      </tbody></table>
      <div style="margin-top:18px;padding:14px 18px;background:${color}0e;border-radius:7px;text-align:right;font-size:15px;font-weight:800;color:${color}">รวมภาษีนำส่งทั้งสิ้น ${_fmtTH(t.amount)}</div>`;
  } else if (t.code === "ภ.พ.30") {
    const outBase = 960653.27, outVat = 67245.79, inVat = 5381.31, net = outVat - inVat;
    const line = (label, val, neg) => `<tr><td style="padding:9px 4px;font-size:12.5px">${label}</td><td style="padding:9px 4px;text-align:right;font-size:12.5px;${neg ? "color:#7a2e1e" : ""}">${neg ? "−" : ""}${_fmtTH(val)}</td></tr>`;
    body = `<table style="width:100%;border-collapse:collapse;margin-top:10px;max-width:560px">
      <tbody>
      <tr style="background:#f3f1ee"><td style="padding:9px 4px;font-size:11px;font-weight:700" colspan="2">ภาษีขาย</td></tr>
      ${line("1. ยอดขายที่ต้องเสียภาษี (ในประเทศ)", outBase)}
      ${line("2. ภาษีขาย (Output VAT 7%)", outVat)}
      <tr style="background:#f3f1ee"><td style="padding:9px 4px;font-size:11px;font-weight:700" colspan="2">ภาษีซื้อ</td></tr>
      ${line("3. ภาษีซื้อที่มีสิทธิหักได้ (Input VAT 7%)", inVat, true)}
      <tr style="border-top:2px solid ${color}"><td style="padding:12px 4px;font-weight:800;font-size:14px">ภาษีที่ต้องชำระ (ข้อ 2 − ข้อ 3)</td><td style="padding:12px 4px;text-align:right;font-weight:800;font-size:16px;color:${color}">${_fmtTH(net)}</td></tr>
      </tbody></table>
      <div style="margin-top:14px;font-size:11px;color:#78716c">หมายเหตุ: ยอดที่แสดงคำนวณจากใบกำกับภาษีขาย/ซื้อในงวด ${t.period} ที่บันทึกในระบบ</div>`;
  } else if (t.code === "สปส.1-10") {
    const rows = D.PayrollRows.filter(r => r.sso > 0);
    const totWage = rows.reduce((s, r) => s + r.gross, 0);
    const totEmp = rows.reduce((s, r) => s + r.sso, 0);
    const totEr = totEmp;
    body = `<table style="width:100%;border-collapse:collapse;margin-top:6px">
      <thead><tr style="background:${color}">${th("ลำดับ")}${th("ชื่อ-สกุลผู้ประกันตน")}${th("เลขบัตรประชาชน")}${th("ค่าจ้าง", true)}${th("สมทบลูกจ้าง 5%", true)}${th("สมทบนายจ้าง 5%", true)}</tr></thead>
      <tbody>
      ${rows.map((r, i) => {
        const emp = D.Employees.find(e => e.id === r.emp);
        const id = (emp && emp.taxId) || `1-10${i}0-0${2000 + i}-${20 + i}-${i}`;
        return `<tr style="background:${i % 2 ? "#fafaf9" : "white"}">${td(i + 1)}${td(r.name, false, true)}${td(id)}${td(_fmtN(r.gross), true)}${td(_fmtN(r.sso), true)}${td(_fmtN(r.sso), true)}</tr>`;
      }).join("")}
      <tr style="background:#f3f1ee;font-weight:700">${td("")}${td(`รวม ${rows.length} ราย`, false, true)}${td("")}${td(_fmtN(totWage), true, true)}${td(_fmtN(totEmp), true, true)}${td(_fmtN(totEr), true, true)}</tr>
      </tbody></table>
      <div style="margin-top:18px;padding:14px 18px;background:${color}0e;border-radius:7px;display:flex;justify-content:space-between;align-items:center">
        <div style="font-size:12px">สมทบลูกจ้าง ${_fmtTH(totEmp)} + สมทบนายจ้าง ${_fmtTH(totEr)}</div>
        <div style="font-size:15px;font-weight:800;color:${color}">รวมเงินสมทบนำส่ง ${_fmtTH(totEmp + totEr)}</div>
      </div>`;
  } else {
    body = `<div style="margin-top:20px;font-size:13px">ยอดภาษีที่ต้องนำส่ง <b>${_fmtTH(t.amount)}</b></div>`;
  }

  const isSso = t.code.startsWith("สปส");
  const sub = isSso ? "แบบรายการแสดงการส่งเงินสมทบ (สำนักงานประกันสังคม)" : `แบบยื่นรายการภาษีเงินได้หัก ณ ที่จ่าย / ภาษีมูลค่าเพิ่ม`;
  return `<div style="background:white;color:#0c0a09;padding:34px 42px;min-height:90vh;border-top:5px solid ${color}">
    ${taxFormHead(t, color, t.name, sub)}
    <div style="margin-top:22px;font-size:12px;color:#44403c;font-weight:600">รายละเอียดการคำนวณ</div>
    ${body}
    ${taxFormFooter(t, color)}
  </div>`;
}

function buildTaxReceipt(t) {
  const C = window.SSSData.Company;
  const color = "#1f5f3a";
  const refNo = "RD" + (t.code.replace(/[^0-9]/g, "") || "00") + "-2569-" + String(Math.floor(Math.random() * 90000) + 10000);
  return `<div style="background:white;color:#0c0a09;padding:38px 46px;min-height:88vh;border-top:5px solid ${color}">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;border-bottom:1px solid #e7e5e4;padding-bottom:16px">
      <div style="display:flex;gap:13px;align-items:center">
        <div style="width:48px;height:48px;border:2px solid ${color};color:${color};display:grid;place-items:center;font-weight:700;font-size:10px;text-align:center;line-height:1.1;border-radius:6px">กรม<br/>สรรพากร</div>
        <div><div style="font-weight:700;font-size:13px">ใบเสร็จรับเงิน — กรมสรรพากร</div><div style="font-size:10.5px;color:#57534e">ยื่นและชำระผ่านระบบ e-Filing</div></div>
      </div>
      <div style="text-align:right"><div style="font-size:11px;color:#78716c">เลขที่อ้างอิงการรับชำระ</div><div style="font-family:monospace;font-weight:700;font-size:15px;color:${color}">${refNo}</div></div>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:24px;font-size:12.5px">
      <div><div style="color:#78716c;font-size:11px">ผู้เสียภาษี</div><div style="font-weight:600">${C.name}</div><div style="color:#57534e;font-size:11px">เลขประจำตัว ${C.taxId}</div></div>
      <div><div style="color:#78716c;font-size:11px">แบบที่ยื่น / งวด</div><div style="font-weight:600">${t.code} · ${t.period}</div><div style="color:#57534e;font-size:11px">วันที่ยื่น ${t.paidDate || "—"}</div></div>
    </div>
    <table style="width:100%;border-collapse:collapse;margin-top:26px">
      <thead><tr style="background:${color};color:white"><th style="padding:10px;text-align:left;font-size:11px">รายการ</th><th style="padding:10px;text-align:right;font-size:11px">จำนวนเงิน</th></tr></thead>
      <tbody>
        <tr><td style="padding:11px 10px;border-bottom:1px solid #f1efeb;font-size:12.5px">${t.code} — ${t.name} งวด ${t.period}</td><td style="padding:11px 10px;border-bottom:1px solid #f1efeb;text-align:right;font-size:12.5px">${_fmtTH(t.amount)}</td></tr>
        <tr style="background:#f3f1ee;font-weight:800"><td style="padding:13px 10px;font-size:13px">รวมชำระ</td><td style="padding:13px 10px;text-align:right;font-size:16px;color:${color}">${_fmtTH(t.amount)}</td></tr>
      </tbody>
    </table>
    <div style="margin-top:22px;padding:14px 18px;background:${color}10;border-radius:7px;font-size:12px;display:flex;align-items:center;gap:8px">
      <span style="color:${color};font-weight:800;font-size:15px">✓</span> ชำระเรียบร้อยแล้ว — สถานะ <b>ยื่นแล้ว</b> · ช่องทาง e-Filing / หักบัญชี ${C.bank}
    </div>
    <div style="margin-top:34px;padding-top:8px;border-top:2px solid ${color};font-size:9px;color:#78716c;display:flex;justify-content:space-between">
      <span>เอกสารอิเล็กทรอนิกส์ — ออกโดยระบบ SSS</span><span>${refNo}</span>
    </div>
  </div>`;
}

function TaxFilings() {
  const D = window.SSSData;
  const { Btn, Badge, Card, fmt0 } = window.UI;
  const [filings, setFilings] = useStateA(() => D.TaxFilings.map(f => ({ ...f })));
  const pending = filings.filter(t => t.status === "รอยื่น");
  const filed = filings.filter(t => t.status === "ยื่นแล้ว");

  const prepareForm = (t) => {
    openTaxPrintModal(`${t.code} — ${t.name} · งวด ${t.period}`, buildTaxForm(t));
    window.toast && window.toast(`เตรียมแบบ ${t.code} งวด ${t.period} แล้ว`);
  };

  const fileEfiling = async (t) => {
    const ok = await window.confirmDialog({
      title: `ยื่น ${t.code} ผ่าน e-Filing`,
      message: `ยืนยันยื่นแบบ <b>${t.code}</b> งวด <b>${t.period}</b><br/>ยอดนำส่ง <b>${_fmtTH(t.amount)}</b> — ระบบจะบันทึกเป็น "ยื่นแล้ว" และออกใบเสร็จ`,
      confirmText: "ยืนยันการยื่น"
    });
    if (!ok) return;
    const today = new Date().toLocaleDateString("th-TH", { day: "numeric", month: "short", year: "2-digit" }).replace(/(\d+) (\S+) (\d+)/, "$1 $2 25$3");
    const paidDate = new Date().toLocaleDateString("th-TH", { day: "numeric", month: "short" }) + " 2569";
    setFilings(prev => prev.map(f =>
      (f.code === t.code && f.period === t.period) ? { ...f, status: "ยื่นแล้ว", paidDate } : f
    ));
    // reflect in shared data so badge counts update elsewhere
    const src = D.TaxFilings.find(f => f.code === t.code && f.period === t.period);
    if (src) { src.status = "ยื่นแล้ว"; src.paidDate = paidDate; }
    window.logActivity && window.logActivity("ยื่นภาษี e-Filing", `${t.code} งวด ${t.period} — นำส่ง ${_fmtTH(t.amount)}`, "create");
    window.toast && window.toast(`ยื่น ${t.code} เรียบร้อย — ดูใบเสร็จได้ที่ตารางด้านล่าง`);
  };

  const showReceipt = (t) => {
    openTaxPrintModal(`ใบเสร็จรับเงิน — ${t.code} · ${t.period}`, buildTaxReceipt(t));
  };

  return (
    <div style={{display: "flex", flexDirection: "column", gap: 14}}>
      <Card title="ปฏิทินภาษี — รอยื่น" sub={`${pending.length} รายการ · ต้องยื่นภายในเดือนหน้า`} flush>
        <div className="table-wrap">
          <table className="t">
            <thead><tr><th>แบบฟอร์ม</th><th>ชื่อเต็ม</th><th>งวด</th><th>ครบกำหนด</th><th>เหลือ</th><th className="right">ยอดที่ต้องนำส่ง</th><th>สถานะ</th><th></th></tr></thead>
            <tbody>
              {pending.length === 0 && (
                <tr><td colSpan={8} style={{textAlign: "center", padding: "28px 0", color: "var(--ink-3)"}}>✓ ยื่นครบทุกแบบในงวดนี้แล้ว</td></tr>
              )}
              {pending.map(t => {
                const daysLeft = window.daysBetween(t.dueDate);
                const urgent = daysLeft <= 7;
                return (
                  <tr key={t.code + t.period} style={{background: urgent ? "var(--warning-bg)" : "transparent"}}>
                    <td style={{fontWeight: 600}}>{t.code}</td>
                    <td>{t.name}</td>
                    <td>{t.period}</td>
                    <td>{t.dueDate}</td>
                    <td style={{color: urgent ? "var(--warning)" : "var(--ink-3)"}}>{daysLeft} วัน</td>
                    <td className="right amount">฿{fmt0(t.amount)}</td>
                    <td><Badge>{t.status}</Badge></td>
                    <td style={{display: "flex", gap: 4}}>
                      <Btn size="sm" kind="ghost" icon={I.doc} onClick={() => prepareForm(t)}>เตรียมแบบ</Btn>
                      <Btn size="sm" kind="primary" icon={I.send} onClick={() => fileEfiling(t)}>ยื่น e-filing</Btn>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      <div className="grid cols-2">
        <Card title="ภ.พ.30 — ภาษีมูลค่าเพิ่ม พ.ค. 2569" right={<Btn size="sm" kind="primary" icon={I.send} onClick={() => { const t = filings.find(f => f.code === "ภ.พ.30" && f.status === "รอยื่น"); t ? prepareForm(t) : window.toast("ภ.พ.30 งวดนี้ยื่นแล้ว"); }}>เตรียมแบบ</Btn>}>
          <table style={{width: "100%", fontSize: 13}}>
            <tbody>
              <tr><td style={{padding: "6px 0"}} className="muted">ยอดขายในประเทศ</td><td style={{padding: "6px 0", textAlign: "right"}} className="amount">฿960,653.27</td></tr>
              <tr><td style={{padding: "6px 0"}} className="muted">ภาษีขาย (Output VAT 7%)</td><td style={{padding: "6px 0", textAlign: "right"}} className="amount">฿67,245.79</td></tr>
              <tr><td style={{padding: "6px 0"}} className="muted">ภาษีซื้อ (Input VAT 7%)</td><td style={{padding: "6px 0", textAlign: "right"}} className="amount">−฿5,381.31</td></tr>
              <tr style={{borderTop: "1px solid var(--line)", fontWeight: 600}}><td style={{padding: "8px 0"}}>ภาษีที่ต้องนำส่ง</td><td style={{padding: "8px 0", textAlign: "right"}} className="amount">฿61,864.48</td></tr>
            </tbody>
          </table>
          <div className="muted" style={{fontSize: 12, marginTop: 10}}>📅 ครบกำหนดยื่น 15 มิ.ย. 2569 (เหลือ 24 วัน)</div>
        </Card>

        <Card title="ภ.ง.ด.1 — หัก ณ ที่จ่ายเงินเดือน พ.ค. 2569" right={<Btn size="sm" kind="primary" icon={I.send} onClick={() => { const t = filings.find(f => f.code === "ภ.ง.ด.1" && f.status === "รอยื่น"); t ? prepareForm(t) : window.toast("ภ.ง.ด.1 งวดนี้ยื่นแล้ว"); }}>เตรียมแบบ</Btn>}>
          <table style={{width: "100%", fontSize: 13}}>
            <tbody>
              <tr><td style={{padding: "6px 0"}} className="muted">พนักงานทั้งหมดในงวด</td><td style={{padding: "6px 0", textAlign: "right"}}>9 คน</td></tr>
              <tr><td style={{padding: "6px 0"}} className="muted">ค่าจ้างรวม</td><td style={{padding: "6px 0", textAlign: "right"}} className="amount">฿318,725</td></tr>
              <tr><td style={{padding: "6px 0"}} className="muted">หักภาษีเงินได้บุคคลธรรมดา</td><td style={{padding: "6px 0", textAlign: "right"}} className="amount">฿2,925</td></tr>
              <tr><td style={{padding: "6px 0"}} className="muted">หักจากค่าเช่า/บริการบุคคล</td><td style={{padding: "6px 0", textAlign: "right"}} className="amount">฿2,200</td></tr>
              <tr style={{borderTop: "1px solid var(--line)", fontWeight: 600}}><td style={{padding: "8px 0"}}>รวมนำส่ง ภ.ง.ด.1</td><td style={{padding: "8px 0", textAlign: "right"}} className="amount">฿5,125</td></tr>
            </tbody>
          </table>
          <div className="muted" style={{fontSize: 12, marginTop: 10}}>📅 ครบกำหนดยื่น 7 มิ.ย. 2569 (เหลือ 16 วัน)</div>
        </Card>
      </div>

      <Card title="ภาษีที่ยื่นแล้ว (3 เดือนล่าสุด)" flush>
        <table className="t">
          <thead><tr><th>แบบ</th><th>งวด</th><th>วันที่ยื่น</th><th className="right">ยอด</th><th>สถานะ</th><th></th></tr></thead>
          <tbody>
            {filed.map(t => (
              <tr key={t.code + t.period}>
                <td style={{fontWeight: 500}}>{t.code}</td>
                <td>{t.period}</td>
                <td>{t.paidDate}</td>
                <td className="right amount">฿{fmt0(t.amount)}</td>
                <td><Badge>ยื่นแล้ว</Badge></td>
                <td><Btn size="sm" kind="ghost" icon={I.download} onClick={() => showReceipt(t)}>ใบเสร็จ</Btn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function Reports() {
  const { Card, Btn } = window.UI;
  const MONTHS = ["all", "2026-05", "2026-04", "2026-03", "2026-02", "2026-01"];
  const [month, setMonth] = useStateA("2026-05");
  const period = month === "all" ? "ทุกเดือน (ปี 2569)" : `งวด ${_accMonthLabel(month)}`;

  const fmtCell = (v) => typeof v === "number" ? (v < 0 ? "−" : "") + Math.abs(v).toLocaleString("th-TH", { maximumFractionDigits: 2 }) : (v == null || v === "" ? "—" : String(v));
  const isNum = (rows, key) => rows.some(r => typeof r[key] === "number");

  const exportCsv = (r) => {
    const spec = _reportDataset(r.title, month);
    if (!spec.rows || !spec.rows.length) { window.toast && window.toast("ไม่มีข้อมูลในช่วงที่เลือก"); return; }
    window.exportRowsCSV(r.title + " · " + period, spec.columns, spec.rows);
  };

  const openReport = (r) => {
    const C = window.SSSData.Company;
    const today = new Date().toLocaleDateString("th-TH", { day: "numeric", month: "long", year: "numeric" });
    const spec = _reportDataset(r.title, month);
    const cols = spec.columns || [];
    const rows = spec.rows || [];
    const numKeys = {}; cols.forEach(c => numKeys[c.key] = isNum(rows, c.key));
    const esc = (s) => String(s).replace(/</g, "&lt;");
    const tableHTML = rows.length ? `
      <table style="width:100%;border-collapse:collapse;font-size:12px;margin-top:8px">
        <thead><tr style="background:#f5f5f4">${cols.map(c => `<th style="text-align:${numKeys[c.key] ? "right" : "left"};padding:8px 10px;border-bottom:2px solid #0c0a09;font-size:11px;color:#44403c;white-space:nowrap">${esc(c.label)}</th>`).join("")}</tr></thead>
        <tbody>${rows.map((row, i) => {
          const summary = /^\s*—|รวม|สุทธิ|กำไรขั้นต้น|กำไรสุทธิ|EBIT|ปลายงวด/.test(String(row.item || ""));
          return `<tr style="${summary ? "font-weight:700;background:#fafaf9;" : ""}border-bottom:1px solid #eceae7">${cols.map(c => {
            const v = row[c.key];
            const color = (c.key === "amount" && typeof v === "number" && v < 0) ? "#b91c1c" : "#0c0a09";
            return `<td style="text-align:${numKeys[c.key] ? "right" : "left"};padding:7px 10px;color:${color};white-space:nowrap;font-variant-numeric:tabular-nums">${fmtCell(v)}</td>`;
          }).join("")}</tr>`;
        }).join("")}</tbody>
      </table>` : `<div style="margin-top:24px;padding:32px;border:1px dashed #d6d3d1;border-radius:8px;text-align:center;color:#78716c;font-size:13px">ไม่มีข้อมูลใน${esc(period)}</div>`;
    const html = `<div style="background:white;color:#0c0a09;padding:40px 48px;min-height:90vh;border-top:5px solid #0c0a09">
      <div style="display:flex;gap:14px;align-items:center;border-bottom:1px solid #e7e5e4;padding-bottom:16px">
        <div style="width:50px;height:50px;background:#0c0a09;color:white;display:grid;place-items:center;font-weight:700;border-radius:5px">SSS</div>
        <div><div style="font-weight:700;font-size:14px">${C.name}</div><div style="font-size:10.5px;color:#57534e">เลขผู้เสียภาษี ${C.taxId}</div></div>
      </div>
      <div style="margin-top:26px">
        <div style="font-size:11px;color:#78716c;letter-spacing:0.08em;text-transform:uppercase">รายงานทางบัญชี</div>
        <h1 style="margin:6px 0 4px;font-size:24px">${esc(r.title)}</h1>
        <div style="font-size:12px;color:#78716c;margin-top:4px">${esc(period)} · ${rows.length} รายการ · ออกเมื่อ ${today}</div>
      </div>
      ${tableHTML}
      <div style="margin-top:40px;padding-top:8px;border-top:2px solid #0c0a09;font-size:9.5px;color:#78716c;display:flex;justify-content:space-between">
        <span>${C.name}</span><span>ข้อมูลดึงจากสมุดรายวันและบัญชีแยกประเภท · ออกโดยระบบ SSS</span>
      </div>
    </div>`;
    document.getElementById("__print_modal")?.remove();
    document.body.classList.remove("printing-modal");
    const modal = document.createElement("div");
    modal.id = "__print_modal"; modal.className = "print-modal";
    modal.innerHTML = `<div class="print-modal-bar no-print"><div style="font-weight:600;font-size:14px;flex:1">${esc(r.title)} · ${esc(period)}</div><button id="__print_close" class="pm-btn pm-btn-ghost">ปิด</button><button id="__print_btn" class="pm-btn pm-btn-primary">🖨 พิมพ์ / บันทึก PDF</button></div><div class="print-modal-paper">${html}</div>`;
    document.body.appendChild(modal);
    document.body.classList.add("printing-modal");
    const cleanup = () => { modal.remove(); document.body.classList.remove("printing-modal"); };
    modal.addEventListener("click", e => { if (e.target === modal) cleanup(); });
    document.getElementById("__print_btn").addEventListener("click", () => window.print());
    document.getElementById("__print_close").addEventListener("click", cleanup);
  };

  const reports = [
    { title: "งบกำไรขาดทุน (P&L)", desc: "รายเดือน · รายไตรมาส · รายปี" },
    { title: "งบดุล (Balance Sheet)", desc: "ณ วันที่กำหนด" },
    { title: "งบกระแสเงินสด", desc: "Direct / Indirect method" },
    { title: "รายงานภาษีขาย (Sales VAT)", desc: "ทดลองออก ภ.พ.30 / ภ.ง.ด.51" },
    { title: "รายงานภาษีซื้อ (Purchase VAT)", desc: "Input tax credit" },
    { title: "รายงานหัก ณ ที่จ่าย", desc: "ภ.ง.ด.1, 3, 53 รวมรายปี" },
    { title: "รายงานเจ้าหนี้ค้างชำระ", desc: "Aging report" },
    { title: "รายงานลูกหนี้ค้างรับ (Aging)", desc: "0-30, 31-60, 61-90, >90 วัน" },
    { title: "รายงานสต็อกและการเคลื่อนไหว", desc: "Stock card · Valuation report" },
    { title: "รายงานต้นทุนโปรเจกต์ (Job costing)", desc: "ต้นทุนจริง vs งบประมาณ" },
    { title: "รายงานเงินเดือนรายพนักงาน", desc: "Year-to-date · 50 ทวิ" },
    { title: "รายงานยอดขายแยกตามลูกค้า/SKU", desc: "วิเคราะห์รายได้" }
  ];
  return (
    <>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>ช่วงข้อมูล</span>
        <div className="seg">
          {MONTHS.map(m => (
            <button key={m} className={`seg-btn ${month === m ? "on" : ""}`} onClick={() => setMonth(m)}>{_accMonthLabel(m)}</button>
          ))}
        </div>
        <span className="spacer" />
        <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>กด "ดู" เพื่อแสดงข้อมูลจริงจากสมุดรายวัน · บัญชีแยกประเภท · ยอดบัญชีธนาคาร</span>
      </div>
      <div className="grid cols-3">
        {reports.map((r, i) => {
          const cnt = (_reportDataset(r.title, month).rows || []).length;
          return (
            <Card key={i}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <div>
                  <div style={{ fontWeight: 500, marginBottom: 4 }}>{r.title}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{r.desc}</div>
                </div>
                <I.book size={16} stroke="var(--ink-3)" />
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 12, alignItems: "center" }}>
                <Btn size="sm" kind="primary" icon={I.search} onClick={() => openReport(r)}>ดู</Btn>
                <Btn size="sm" kind="ghost" icon={I.download} onClick={() => openReport(r)}>PDF</Btn>
                <Btn size="sm" kind="ghost" icon={I.download} onClick={() => exportCsv(r)}>Excel</Btn>
                <span className="spacer" />
                <span style={{ fontSize: 11, color: cnt ? "var(--ink-3)" : "var(--danger)" }}>{cnt ? `${cnt} แถว` : "ไม่มีข้อมูล"}</span>
              </div>
            </Card>
          );
        })}
      </div>
    </>
  );
}

window.Accounting = Accounting;
