/* global React, I, UI, SSSData */
const { useState: useStateCA, useMemo: useMemoCA } = React;
const caUI = window.UI;

// ── Thai-date helpers สำหรับจัดกลุ่มรอบเบิก (ทุกวันพุธ/เสาร์) ──
const CA_TH_MON = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
const CA_TH_MON_FULL = ["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"];
function caParseDate(str) {
  const p = String(str || "").trim().split(/\s+/);
  const day = parseInt(p[0], 10) || 1;
  const mon = Math.max(0, CA_TH_MON.indexOf(p[1]));
  const yearBE = parseInt(p[2], 10) || 2569;
  return new Date(yearBE - 543, mon, day);
}
// รอบเบิก: 3 = พุธ, 6 = เสาร์ (ใช้ field round ถ้ามี ไม่งั้น derive จากวันในสัปดาห์)
function caRound(r) {
  if (r.round) return r.round;
  const d = caParseDate(r.date).getDay();
  return d === 3 ? "พุธ" : d === 6 ? "เสาร์" : "อื่นๆ";
}
const CA_ROUND_TONE = { "พุธ": "var(--info)", "เสาร์": "var(--c-violet)", "อื่นๆ": "var(--ink-3)" };
// จัดกลุ่ม rows → เดือน → ชุด(รอบ/วันที่)
function caGroup(rows) {
  const enriched = rows.map(r => ({ ...r, _d: caParseDate(r.date), _round: caRound(r) }));
  enriched.sort((a, b) => b._d - a._d || (a.no < b.no ? 1 : -1));
  const months = [];
  for (const r of enriched) {
    const mk = `${r._d.getFullYear()}-${r._d.getMonth()}`;
    let mo = months.find(m => m.key === mk);
    if (!mo) { mo = { key: mk, label: `${CA_TH_MON_FULL[r._d.getMonth()]} ${r._d.getFullYear() + 543}`, date: r._d, rows: [], batches: [] }; months.push(mo); }
    mo.rows.push(r);
  }
  months.forEach(mo => {
    for (const r of mo.rows) {
      let b = mo.batches.find(x => x.dateStr === r.date);
      if (!b) { b = { dateStr: r.date, round: r._round, date: r._d, rows: [] }; mo.batches.push(b); }
      b.rows.push(r);
    }
    mo.batches.sort((a, b) => b.date - a.date);
  });
  return months;
}

// =============== Printable paper: ใบเบิกเงินสด ===============
function CashAdvancePaper({ ca }) {
  const C = window.SSSData.Company;
  const { fmtM, bahtText } = window.UI;
  const F = window.SSSData.PettyCashFund;
  const color = window.getDocColor("cash-advance");
  const colorSoft = window.hexA(color, 0.07);
  const colorLine = window.hexA(color, 0.22);
  const cleared = ca.status === "เคลียร์แล้ว" && ca.actual != null;
  const diff = cleared ? ca.actual - ca.amount : 0;

  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: "26px 36px 30px"}}>
        {/* Header */}
        <div style={{display: "grid", gridTemplateColumns: "1fr auto", gap: 24, marginBottom: 22, alignItems: "flex-start"}}>
          <div style={{display: "flex", gap: 20, alignItems: "flex-start"}}>
            <div style={{background: color, borderRadius: 6, alignSelf: "stretch", minHeight: 56, maxHeight: 80, display: "flex", alignItems: "center", justifyContent: "center", padding: "8px 16px", flexShrink: 0}}><img src="assets/logo-ink.png" alt={C.name} style={{width: 132, maxHeight: "100%", objectFit: "contain", display: "block"}}/></div>
            <div style={{paddingTop: 2}}>
              <div style={{fontWeight: 700, fontSize: 13.5, lineHeight: 1.25, color: "#0c0a09"}}>{C.name}</div>
              <div style={{fontSize: 10.5, color: "#78716c", marginTop: 1}}>{C.nameEn}</div>
              <div style={{fontSize: 10.5, color: "#57534e", marginTop: 6, lineHeight: 1.5, maxWidth: 360}}>{C.address}</div>
              <div style={{fontSize: 10.5, color: "#57534e", marginTop: 3}}>กองทุนเงินสดย่อย · ผู้รักษาเงิน <b style={{color: "#0c0a09"}}>{F.custodian}</b></div>
            </div>
          </div>
          <div style={{textAlign: "right", minWidth: 210}}>
            <h1 style={{margin: 0, fontSize: 26, fontWeight: 700, color, letterSpacing: "-0.02em", lineHeight: 1}}>ใบเบิกเงินสด</h1>
            <div style={{fontSize: 9.5, color: "#a8a29e", letterSpacing: "0.12em", marginTop: 4, fontWeight: 500}}>CASH ADVANCE VOUCHER</div>
            <div style={{marginTop: 14, display: "inline-block", textAlign: "left", background: colorSoft, padding: "10px 14px", borderRadius: 4, minWidth: 190}}>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 11}}><span style={{color: "#78716c"}}>เลขที่</span><b className="mono" style={{color: "#0c0a09"}}>{ca.no}</b></div>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 11, marginTop: 3}}><span style={{color: "#78716c"}}>วันที่เบิก</span><b style={{color: "#0c0a09"}}>{ca.date}</b></div>
              <div style={{display: "flex", justifyContent: "space-between", gap: 14, fontSize: 11, marginTop: 3}}><span style={{color: "#78716c"}}>กำหนดเคลียร์</span><b style={{color: "#0c0a09"}}>{ca.due}</b></div>
            </div>
          </div>
        </div>

        {/* Requester + purpose */}
        <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16}}>
          <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.06em"}}>ผู้ขอเบิก</div>
            <div style={{padding: "10px 12px", fontSize: 11.5}}>
              <div style={{fontWeight: 600, fontSize: 12.5, color: "#0c0a09"}}>{ca.requester}</div>
              <div style={{color: "#57534e", marginTop: 3, lineHeight: 1.6}}>
                <div>แผนก: {ca.dept}</div>
                <div>วิธีรับเงิน: {ca.method}</div>
                {ca.ref && ca.ref !== "—" && <div>อ้างอิงงาน: <span className="mono" style={{color: "#0c0a09"}}>{ca.ref}</span></div>}
              </div>
            </div>
          </div>
          <div style={{border: "1px solid #e7e5e4", borderRadius: 6, overflow: "hidden"}}>
            <div style={{background: "#f7f6f4", color: "#44403c", padding: "5px 12px", fontSize: 10, fontWeight: 600, letterSpacing: "0.06em"}}>วัตถุประสงค์การเบิก</div>
            <div style={{padding: "10px 12px", fontSize: 11.5, color: "#44403c", lineHeight: 1.6}}>{ca.purpose}</div>
          </div>
        </div>

        {/* Amount box */}
        <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 20px", background: color, color: "white", borderRadius: 6}}>
          <div>
            <div style={{fontSize: 11, opacity: 0.85}}>จำนวนเงินที่ขอเบิก</div>
            <div style={{fontSize: 10.5, opacity: 0.85, fontStyle: "italic", marginTop: 2}}>({bahtText(ca.amount)})</div>
          </div>
          <div style={{fontSize: 26, fontWeight: 700, fontVariantNumeric: "tabular-nums"}}>฿ {fmtM(ca.amount)}</div>
        </div>

        {/* Clearing summary (if cleared) */}
        {cleared && (
          <div style={{marginTop: 14, border: `1px solid ${colorLine}`, borderRadius: 6, overflow: "hidden"}}>
            <div style={{background: colorSoft, padding: "6px 14px", fontSize: 10.5, fontWeight: 700, color: "#0c0a09", letterSpacing: "0.04em"}}>สรุปการเคลียร์เงิน · เคลียร์เมื่อ {ca.clearedDate}</div>
            <div style={{padding: "10px 14px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, fontSize: 11.5}}>
              <div><div style={{color: "#78716c", fontSize: 10}}>เบิกไป</div><div style={{fontWeight: 600, color: "#0c0a09", marginTop: 2}}>฿ {fmtM(ca.amount)}</div></div>
              <div><div style={{color: "#78716c", fontSize: 10}}>ใช้จริง</div><div style={{fontWeight: 600, color: "#0c0a09", marginTop: 2}}>฿ {fmtM(ca.actual)}</div></div>
              <div><div style={{color: "#78716c", fontSize: 10}}>{diff >= 0 ? "เบิกเพิ่ม / จ่ายคืนพนักงาน" : "คืนเข้ากองทุน"}</div><div style={{fontWeight: 700, color: diff >= 0 ? "#b45309" : "#15803d", marginTop: 2}}>฿ {fmtM(Math.abs(diff))}</div></div>
            </div>
          </div>
        )}

        {/* Signatures */}
        <div style={{display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 30, marginTop: 40, fontSize: 10.5}}>
          {[
            { role: "ผู้ขอเบิก", name: ca.requester },
            { role: "ผู้อนุมัติ", name: ca.approver && ca.approver !== "—" ? ca.approver : C.currentUser.name },
            { role: "ผู้จ่ายเงิน (ผู้รักษาเงินสดย่อย)", name: F.custodian }
          ].map((s, i) => (
            <div key={i} style={{textAlign: "center"}}>
              <div style={{borderTop: "1px dashed #57534e", paddingTop: 6, marginTop: 38}}>
                <div style={{fontWeight: 600, color: "#0c0a09", fontSize: 10}}>{s.role}</div>
                <div style={{color: "#78716c", fontSize: 9.5, marginTop: 2}}>( {s.name} )</div>
                <div style={{color: "#a8a29e", fontSize: 9.5, marginTop: 2}}>วันที่ ____________</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{marginTop: 26, paddingTop: 10, borderTop: `2px solid ${color}`, fontSize: 9.5, color: "#78716c", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
          <span><b style={{color: "#44403c"}}>{C.name}</b> · กองทุนเงินสดย่อย</span>
          <span>{ca.no} · ออกโดยระบบ SSS</span>
        </div>
      </div>
    </div>
  );
}

// =============== Fund status hero ===============
// เก็บ/โหลดรายการเบิก (รวมที่ผู้ใช้สร้างใหม่ บันทึกถาวร)
window.caLoadAll = function() {
  try {
    const saved = JSON.parse(localStorage.getItem("sss-cash-advances") || "null");
    if (saved) { window.SSSData.CashAdvances = saved; return saved; }
  } catch {}
  return window.SSSData.CashAdvances;
};
window.caSaveAll = function(list) {
  try { localStorage.setItem("sss-cash-advances", JSON.stringify(list)); } catch {}
  window.SSSData.CashAdvances = list;
  window.dispatchEvent(new Event("sss-ca-changed"));
};

function FundStatus({ fund, onReplenish }) {
  const { fmt0 } = window.UI;
  const pct = Math.max(0, Math.min(100, Math.round((fund.onHand / fund.limit) * 100)));
  const low = fund.onHand < fund.replenishAt;
  return (
    <div className="card mb-lg" style={{overflow: "hidden"}}>
      <div style={{display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 0}}>
        {/* On-hand with gauge */}
        <div style={{padding: "18px 20px", borderRight: "1px solid var(--line)"}}>
          <div style={{display: "flex", alignItems: "center", gap: 8, color: "var(--ink-3)", fontSize: 12.5}}>
            <I.money size={15}/> เงินสดในมือ · {fund.name}
          </div>
          <div style={{display: "flex", alignItems: "baseline", gap: 10, marginTop: 8}}>
            <div className="value" style={{fontFamily: "var(--font-display)", fontSize: 30, fontWeight: 700, letterSpacing: "-0.01em"}}>฿{fmt0(fund.onHand)}</div>
            <div style={{fontSize: 12.5, color: "var(--ink-3)"}}>/ วงเงิน ฿{fmt0(fund.limit)}</div>
          </div>
          <div style={{height: 9, borderRadius: 999, background: "var(--surface-3)", marginTop: 12, overflow: "hidden"}}>
            <div style={{height: "100%", width: `${pct}%`, borderRadius: 999, background: low ? "var(--danger)" : "linear-gradient(90deg, var(--c-amber), var(--c-lime))"}}/>
          </div>
          <div style={{display: "flex", justifyContent: "space-between", marginTop: 7, fontSize: 11.5}}>
            <span className={low ? "" : "muted"} style={low ? {color: "var(--danger)", fontWeight: 600} : {}}>
              {low ? "⚠ ต่ำกว่าจุดเติมเงิน — ควรเติม" : `คงเหลือ ${pct}%`}
            </span>
            <button className="btn sm primary" style={{height: 24, fontSize: 11.5}} onClick={onReplenish}><I.plus size={11} className="icon"/>เติมเงินกองทุน</button>
          </div>
        </div>
        {/* Outstanding */}
        <div style={{padding: "18px 20px", borderRight: "1px solid var(--line)"}}>
          <div style={{color: "var(--ink-3)", fontSize: 12.5, display: "flex", alignItems: "center", gap: 6}}><I.clock size={14}/> เบิกค้างเคลียร์</div>
          <div className="value" style={{fontFamily: "var(--font-display)", fontSize: 25, fontWeight: 700, marginTop: 8}}>฿{fmt0(fund.advancesOut)}</div>
          <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 4}}>ยังไม่ส่งหลักฐาน</div>
        </div>
        {/* Spent this month */}
        <div style={{padding: "18px 20px", borderRight: "1px solid var(--line)"}}>
          <div style={{color: "var(--ink-3)", fontSize: 12.5, display: "flex", alignItems: "center", gap: 6}}><I.receipt size={14}/> ใช้จ่ายเดือนนี้</div>
          <div className="value" style={{fontFamily: "var(--font-display)", fontSize: 25, fontWeight: 700, marginTop: 8}}>฿{fmt0(fund.spentThisMonth)}</div>
          <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 4}}>เคลียร์แล้ว · เข้าค่าใช้จ่าย</div>
        </div>
        {/* Custodian */}
        <div style={{padding: "18px 20px"}}>
          <div style={{color: "var(--ink-3)", fontSize: 12.5, display: "flex", alignItems: "center", gap: 6}}><I.shield size={14}/> ผู้รักษาเงินสดย่อย</div>
          <div style={{fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, marginTop: 10}}>{fund.custodian}</div>
          <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 4}}>เติมเงินล่าสุด {fund.lastReplenish}</div>
        </div>
      </div>
    </div>
  );
}

// =============== Main petty-cash page ===============
function PettyCash({ navigate }) {
  const D = window.SSSData;
  const { Btn, Badge, Card, PageHead, Tabs, fmt0 } = window.UI;
  const [tab, setTab] = useStateCA("all");
  const [active, setActive] = useStateCA(null);   // row for detail/clear drawer
  const [creating, setCreating] = useStateCA(false);
  const [view, setView] = useStateCA("group");    // group | flat
  const [roundF, setRoundF] = useStateCA("all");  // all | พุธ | เสาร์
  const [q, setQ] = useStateCA("");
  const [dateF, setDateF] = useStateCA({ mode: "all" });
  const [rows, setRows] = useStateCA(() => window.caLoadAll());
  React.useEffect(() => {
    const h = () => setRows(window.caLoadAll());
    window.addEventListener("sss-ca-changed", h);
    return () => window.removeEventListener("sss-ca-changed", h);
  }, []);

  const tabs = [
    { key: "all", label: "ทั้งหมด", count: rows.length },
    { key: "รออนุมัติ", label: "รออนุมัติ", count: rows.filter(r => r.status === "รออนุมัติ").length },
    { key: "รอเคลียร์", label: "รอเคลียร์", count: rows.filter(r => r.status === "รอเคลียร์").length },
    { key: "เคลียร์แล้ว", label: "เคลียร์แล้ว", count: rows.filter(r => r.status === "เคลียร์แล้ว").length }
  ];
  const byStatus = tab === "all" ? rows : rows.filter(r => r.status === tab);
  const byRound = roundF === "all" ? byStatus : byStatus.filter(r => caRound(r) === roundF);
  const byQ = q.trim() ? byRound.filter(r => (r.no + " " + r.requester + " " + r.purpose + " " + r.dept).toLowerCase().includes(q.trim().toLowerCase())) : byRound;
  const list = byQ.filter(r => !window.DocDates || window.DocDates.match(dateF, r.date));
  const grouped = useMemoCA(() => caGroup(list), [list]);

  const pendingClear = rows.filter(r => r.status === "รอเคลียร์");
  const overdue = pendingClear.filter(r => r.overdue);

  const renderRow = (r) => {
    const cleared = r.status === "เคลียร์แล้ว" && r.actual != null;
    const diff = cleared ? r.actual - r.amount : null;
    return (
      <tr key={r.no} className="row-clickable" onClick={() => setActive(r)}>
        <td className="mono">{r.no}</td>
        <td>{r.date}</td>
        <td>{r.requester}<div style={{fontSize: 11, color: "var(--ink-3)"}}>{r.dept}</div></td>
        <td className="muted" style={{maxWidth: 280}}><span style={{display: "block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{r.purpose}</span></td>
        <td className="right amount">฿{fmt0(r.amount)}</td>
        <td className="right amount muted">{r.actual != null ? `฿${fmt0(r.actual)}` : "—"}</td>
        <td className="right amount" style={diff != null ? {color: diff >= 0 ? "var(--warning)" : "var(--success)", fontWeight: 600} : {color: "var(--ink-4)"}}>
          {diff != null ? `${diff >= 0 ? "+" : "−"}฿${fmt0(Math.abs(diff))}` : "—"}
        </td>
        <td>
          <span style={r.overdue ? {color: "var(--danger)", fontWeight: 600} : {}}>{r.due}</span>
          {r.overdue && <div style={{fontSize: 10.5, color: "var(--danger)"}}>เกินกำหนด</div>}
        </td>
        <td><Badge>{r.overdue && r.status === "รอเคลียร์" ? "เกินกำหนดเคลียร์" : r.status}</Badge></td>
        <td onClick={e => e.stopPropagation()}>
          {r.status === "รอเคลียร์"
            ? <Btn size="sm" kind="primary" onClick={() => setActive({ ...r, _clear: true })}>เคลียร์</Btn>
            : <Btn kind="ghost" size="sm" icon={I.chevronRight} onClick={() => setActive(r)}/>}
        </td>
      </tr>
    );
  };

  return (
    <>
      <PageHead
        title="เบิกเงินสด · Petty Cash"
        sub="เบิกเงินสดย่อยสำหรับค่าใช้จ่ายย่อย — ขออนุมัติ จ่ายเงิน แล้วเคลียร์พร้อมหลักฐาน"
        right={<>
          <Btn icon={I.download} kind="ghost" onClick={() => window.exportRowsCSV("เบิกเงินสด", [
            { key: "no", label: "เลขที่" }, { key: "date", label: "วันที่" }, { key: "requester", label: "ผู้ขอเบิก" },
            { key: "dept", label: "แผนก" }, { key: "purpose", label: "วัตถุประสงค์" }, { key: "amount", label: "จำนวนเบิก" },
            { key: "actual", label: "ใช้จริง" }, { key: "status", label: "สถานะ" }
          ], list)}>ส่งออก</Btn>
          <Btn icon={I.plus} kind="primary" onClick={() => setCreating(true)}>เบิกเงินสด</Btn>
        </>}
      />

      <FundStatus fund={D.PettyCashFund} onReplenish={() => window.toast && window.toast("บันทึกการเติมเงินกองทุนเงินสดย่อยแล้ว")}/>

      <div className="grid cols-4 mb-lg">
        <UI.Stat label="รอเคลียร์" value={pendingClear.length} sub={`฿${fmt0(pendingClear.reduce((s,r)=>s+r.amount,0))} ค้างอยู่`} icon={I.clock}/>
        <UI.Stat label="รออนุมัติ" value={rows.filter(r=>r.status==='รออนุมัติ').length} sub="ต้องอนุมัติจาก Admin" icon={I.shield}/>
        <UI.Stat label="เบิกเดือนนี้ (จำนวนใบ)" value={rows.length} sub={`รวม ฿${fmt0(rows.reduce((s,r)=>s+r.amount,0))}`} icon={I.money}/>
        <UI.Stat label="เกินกำหนดเคลียร์" value={overdue.length} sub={overdue.length ? "ติดตามด่วน" : "ไม่มีค้างเกินกำหนด"} deltaDir={overdue.length ? "down" : ""} icon={I.bell}/>
      </div>

      <Card flush padded={false}>
        <div style={{padding: 12, borderBottom: "1px solid var(--line)", display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap"}}>
          <Tabs items={tabs} active={tab} onChange={setTab}/>
          <span className="spacer"/>
          {/* รอบเบิก filter */}
          <div className="seg">
            {[{ k: "all", l: "ทุกรอบ" }, { k: "พุธ", l: "วันพุธ" }, { k: "เสาร์", l: "วันเสาร์" }].map(o => (
              <button key={o.k} className={`seg-btn ${roundF === o.k ? "on" : ""}`} onClick={() => setRoundF(o.k)}>
                {o.k !== "all" && <span style={{width: 7, height: 7, borderRadius: "50%", background: CA_ROUND_TONE[o.k], display: "inline-block", marginRight: 5}}/>}
                {o.l}
              </button>
            ))}
          </div>
          {/* view toggle */}
          <div className="seg">
            <button className={`seg-btn ${view === "group" ? "on" : ""}`} onClick={() => setView("group")} title="จัดกลุ่มตามเดือน + รอบ"><I.calc size={13} className="icon"/>จัดกลุ่ม</button>
            <button className={`seg-btn ${view === "flat" ? "on" : ""}`} onClick={() => setView("flat")} title="ตารางปกติ"><I.receipt size={13} className="icon"/>ตาราง</button>
          </div>
          <div className="search" style={{width: 220}}><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 ca-table">
            <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>
            {view === "flat" ? (
              <tbody>
                {list.length === 0 && <tr><td colSpan={10} style={{padding: 30, textAlign: "center", color: "var(--ink-3)"}}>ไม่มีรายการเบิกในเงื่อนไขที่เลือก</td></tr>}
                {list.map(renderRow)}
              </tbody>
            ) : (
              grouped.map(mo => {
                const moSum = mo.rows.reduce((s, r) => s + r.amount, 0);
                return (
                  <tbody key={mo.key}>
                    {/* month header */}
                    <tr className="ca-month">
                      <td colSpan={10}>
                        <div style={{display: "flex", alignItems: "center", gap: 10}}>
                          <I.calc size={14} style={{color: "var(--ink-3)"}}/>
                          <span style={{fontWeight: 700, fontSize: 13.5}}>{mo.label}</span>
                          <span style={{fontSize: 11.5, color: "var(--ink-3)"}}>{mo.rows.length} ใบ · {mo.batches.length} รอบเบิก</span>
                          <span className="spacer"/>
                          <span style={{fontSize: 12, color: "var(--ink-3)"}}>รวมเบิก</span>
                          <span className="amount" style={{fontWeight: 700, fontSize: 13.5}}>฿{fmt0(moSum)}</span>
                        </div>
                      </td>
                    </tr>
                    {mo.batches.map(b => {
                      const bSum = b.rows.reduce((s, r) => s + r.amount, 0);
                      const tone = CA_ROUND_TONE[b.round] || "var(--ink-3)";
                      return (
                        <React.Fragment key={b.dateStr}>
                          <tr className="ca-batch">
                            <td colSpan={10}>
                              <div style={{display: "flex", alignItems: "center", gap: 10}}>
                                <span style={{display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 10px", borderRadius: 999, background: `color-mix(in srgb, ${tone} 14%, transparent)`, color: tone, fontWeight: 600, fontSize: 11.5}}>
                                  <span style={{width: 7, height: 7, borderRadius: "50%", background: tone}}/>
                                  รอบวัน{b.round}
                                </span>
                                <span style={{fontWeight: 600, fontSize: 12.5}}>{b.dateStr}</span>
                                <span style={{fontSize: 11.5, color: "var(--ink-3)"}}>{b.rows.length} ใบ</span>
                                <span className="spacer"/>
                                <span className="amount" style={{fontWeight: 600, fontSize: 12.5, color: "var(--ink-2)"}}>฿{fmt0(bSum)}</span>
                              </div>
                            </td>
                          </tr>
                          {b.rows.map(renderRow)}
                        </React.Fragment>
                      );
                    })}
                  </tbody>
                );
              })
            )}
          </table>
          {view === "group" && grouped.length === 0 && <div style={{padding: 30, textAlign: "center", color: "var(--ink-3)"}}>ไม่มีรายการเบิกในเงื่อนไขที่เลือก</div>}
        </div>
      </Card>

      {active && <CashAdvanceDrawer ca={active} startClear={!!active._clear} onClose={() => setActive(null)}/>}
      {creating && <CashAdvanceCreate onClose={() => setCreating(false)}/>}
    </>
  );
}

// =============== Detail + clear drawer ===============
function CashAdvanceDrawer({ ca, startClear, onClose }) {
  const { Btn, Badge, Workflow, fmtM, fmt0 } = window.UI;
  const isPendingClear = ca.status === "รอเคลียร์";
  const [mode, setMode] = useStateCA(startClear && isPendingClear ? "clear" : "view");
  const [clines, setClines] = useStateCA([{ id: 1, desc: ca.purpose, amount: ca.amount }]);

  const actual = clines.reduce((s, l) => s + (Number(l.amount) || 0), 0);
  const diff = actual - ca.amount;
  const addLine = () => setClines(ls => [...ls, { id: Date.now(), desc: "", amount: 0 }]);
  const delLine = (id) => setClines(ls => ls.length > 1 ? ls.filter(l => l.id !== id) : ls);
  const updLine = (id, patch) => setClines(ls => ls.map(l => l.id === id ? { ...l, ...patch } : l));

  const step = ca.status === "เคลียร์แล้ว" ? 3 : ca.status === "รอเคลียร์" ? 2 : ca.status === "รออนุมัติ" ? 0 : 1;

  const confirmClear = () => {
    onClose && onClose();
    window.logActivity && window.logActivity("เคลียร์เงินเบิก", `${ca.no} — ใช้จริง ฿${fmt0(actual)}`, "expense");
    window.toast && window.toast(diff < 0
      ? `เคลียร์ ${ca.no} แล้ว · คืนเข้ากองทุน ฿${fmt0(-diff)}`
      : diff > 0 ? `เคลียร์ ${ca.no} แล้ว · จ่ายเพิ่มพนักงาน ฿${fmt0(diff)}`
      : `เคลียร์ ${ca.no} แล้ว · พอดี`);
  };

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer wide" style={{width: mode === "clear" ? 860 : 760}}>
        <div className="drawer-head">
          <I.money size={16}/>
          <h3>{mode === "clear" ? "เคลียร์เงินเบิก" : "ใบเบิกเงินสด"} {ca.no}</h3>
          <span className="spacer"/>
          <Badge>{ca.overdue && ca.status === "รอเคลียร์" ? "เกินกำหนดเคลียร์" : ca.status}</Badge>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>

        <div className="drawer-body">
          <div className="mb-lg"><Workflow steps={["ขอเบิก", "อนุมัติ", "จ่าย + รอเคลียร์", "เคลียร์เสร็จ"]} current={step}/></div>

          {mode === "view" && (
            <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14}}>
              <div className="field"><label>ผู้ขอเบิก</label><div className="input" style={{display: "flex", alignItems: "center"}}>{ca.requester} · {ca.dept}</div></div>
              <div className="field"><label>วันที่เบิก</label><div className="input" style={{display: "flex", alignItems: "center"}}>{ca.date}</div></div>
              <div className="field" style={{gridColumn: "1 / -1"}}><label>วัตถุประสงค์</label><div className="textarea" style={{minHeight: 44}}>{ca.purpose}</div></div>
              <div className="field"><label>จำนวนเงินเบิก</label><div className="input amount" style={{display: "flex", alignItems: "center", fontWeight: 600}}>฿{fmtM(ca.amount)}</div></div>
              <div className="field"><label>กำหนดเคลียร์</label><div className="input" style={{display: "flex", alignItems: "center", color: ca.overdue ? "var(--danger)" : undefined}}>{ca.due}</div></div>
              {ca.actual != null && (
                <>
                  <div className="field"><label>ใช้จริง</label><div className="input amount" style={{display: "flex", alignItems: "center"}}>฿{fmtM(ca.actual)}</div></div>
                  <div className="field"><label>{ca.actual - ca.amount >= 0 ? "เบิกเพิ่ม" : "คืนเข้ากองทุน"}</label><div className="input amount" style={{display: "flex", alignItems: "center", color: ca.actual - ca.amount >= 0 ? "var(--warning)" : "var(--success)", fontWeight: 600}}>฿{fmtM(Math.abs(ca.actual - ca.amount))}</div></div>
                </>
              )}
            </div>
          )}

          {mode === "clear" && (
            <div style={{display: "flex", flexDirection: "column", gap: 14}}>
              <div style={{padding: "10px 14px", background: "var(--surface-2)", borderRadius: 8, display: "flex", justifyContent: "space-between", alignItems: "center"}}>
                <div><div style={{fontSize: 12, color: "var(--ink-3)"}}>{ca.requester} เบิกไป</div><div className="amount" style={{fontSize: 18, fontWeight: 700}}>฿{fmtM(ca.amount)}</div></div>
                <div style={{fontSize: 12, color: "var(--ink-3)", textAlign: "right"}}>กรอกค่าใช้จ่ายจริงตามใบเสร็จ/ใบสำคัญรับเงิน<br/>ระบบจะคำนวณเงินคืน/เบิกเพิ่มให้</div>
              </div>

              <div>
                <div className="h2 mb" style={{display: "flex", alignItems: "center"}}>
                  <span>รายการค่าใช้จ่ายจริง</span><span className="spacer"/>
                  <Btn size="sm" icon={I.plus} onClick={addLine}>เพิ่มรายการ</Btn>
                </div>
                <div style={{display: "flex", flexDirection: "column", gap: 8}}>
                  {clines.map((l, i) => (
                    <div key={l.id} style={{display: "grid", gridTemplateColumns: "18px 1fr 120px 30px", gap: 8, alignItems: "center"}}>
                      <span style={{fontSize: 11, color: "var(--ink-3)"}}>#{i+1}</span>
                      <input className="input" placeholder="รายละเอียดค่าใช้จ่าย" value={l.desc} onChange={e=>updLine(l.id, { desc: e.target.value })}/>
                      <input className="input" type="number" placeholder="จำนวนเงิน" value={l.amount} onChange={e=>updLine(l.id, { amount: e.target.value })} style={{textAlign: "right"}}/>
                      <button className="icon-btn" onClick={() => delLine(l.id)}><I.trash size={12}/></button>
                    </div>
                  ))}
                </div>
              </div>

              <div className="attach-dropzone"><I.upload size={20}/><div style={{marginTop: 6}}>แนบใบเสร็จ / ใบสำคัญรับเงิน เป็นหลักฐาน</div></div>

              <div style={{padding: 14, background: "var(--surface-2)", borderRadius: 8, display: "flex", flexDirection: "column", gap: 7}}>
                <div style={{display: "flex", justifyContent: "space-between", fontSize: 13}}><span className="muted">เบิกไป</span><span className="amount">฿{fmtM(ca.amount)}</span></div>
                <div style={{display: "flex", justifyContent: "space-between", fontSize: 13}}><span className="muted">ใช้จริง</span><span className="amount">฿{fmtM(actual)}</span></div>
                <div style={{borderTop: "1px solid var(--line)", paddingTop: 7, display: "flex", justifyContent: "space-between", fontWeight: 700, fontSize: 15}}>
                  <span>{diff > 0 ? "จ่ายเพิ่มให้พนักงาน" : diff < 0 ? "พนักงานคืนเข้ากองทุน" : "พอดี ไม่มีส่วนต่าง"}</span>
                  <span className="amount" style={{color: diff > 0 ? "var(--warning)" : diff < 0 ? "var(--success)" : "var(--ink-1)"}}>฿{fmtM(Math.abs(diff))}</span>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="drawer-foot">
          <Btn kind="ghost" onClick={() => mode === "clear" && !startClear ? setMode("view") : onClose()}>{mode === "clear" && !startClear ? "ย้อนกลับ" : "ปิด"}</Btn>
          <Btn icon={I.print} kind="ghost" onClick={() => { setMode("view"); setTimeout(() => window.printDocPaperWithOptions(), 250); }}>พิมพ์ใบเบิก</Btn>
          {ca.status === "รออนุมัติ" && <Btn kind="primary" icon={I.check} onClick={() => { onClose(); window.toast && window.toast(`อนุมัติและจ่ายเงินเบิก ${ca.no} แล้ว`); }}>อนุมัติ + จ่ายเงิน</Btn>}
          {isPendingClear && mode === "view" && <Btn kind="primary" icon={I.check} onClick={() => setMode("clear")}>เคลียร์เงิน</Btn>}
          {mode === "clear" && <Btn kind="primary" icon={I.check} onClick={confirmClear}>ยืนยันการเคลียร์</Btn>}
        </div>

        {/* Hidden printable */}
        <div style={{position: "absolute", left: -99999, top: 0, width: 760}}><CashAdvancePaper ca={ca}/></div>
      </div>
    </>
  );
}

// =============== Create drawer (form + live preview) ===============
function CashAdvanceCreate({ onClose }) {
  const D = window.SSSData;
  const { Btn, fmt0 } = window.UI;
  // พนักงานทุกคนที่ทำงานอยู่ ณ ตอนนี้
  const emps = D.Employees.filter(e => e.status === "ทำงาน" || e.status === "ทดลองงาน");
  const [date, setDate] = useStateCA("22 พ.ค. 2569");
  const [due, setDue] = useStateCA("25 พ.ค. 2569");
  const [method, setMethod] = useStateCA("เงินสด");
  const [reason, setReason] = useStateCA("เบิกเงินวันพุธ");
  const [otherReason, setOtherReason] = useStateCA("");
  const [picks, setPicks] = useStateCA({});   // empId -> { on, amount }

  const toggle = (id) => setPicks(p => ({ ...p, [id]: { on: !(p[id] && p[id].on), amount: (p[id] && p[id].amount) || "" } }));
  const setAmt = (id, v) => setPicks(p => ({ ...p, [id]: { on: true, amount: v } }));
  const selected = emps.filter(e => picks[e.id] && picks[e.id].on);
  const total = selected.reduce((s, e) => s + (Number(picks[e.id].amount) || 0), 0);

  const purposeText = reason === "อื่นๆ" ? otherReason.trim() : reason;
  const round = reason === "เบิกเงินวันพุธ" ? "พุธ" : reason === "เบิกเงินวันเสาร์" ? "เสาร์" : "อื่นๆ";

  const save = () => {
    if (selected.length === 0) { window.toast && window.toast("ติ๊กเลือกพนักงานอย่างน้อย 1 คน"); return; }
    const noAmt = selected.filter(e => !(Number(picks[e.id].amount) > 0));
    if (noAmt.length) { window.toast && window.toast("กรอกจำนวนเงินของ: " + noAmt.map(e => e.name).join(", ")); return; }
    if (reason === "อื่นๆ" && !purposeText) { window.toast && window.toast("กรอกเหตุผลการเบิก (อื่นๆ)"); return; }

    const rows = window.caLoadAll();
    let maxNo = 42;
    rows.forEach(r => { const m = /^PC-2569-(\d+)$/.exec(r.no); if (m) maxNo = Math.max(maxNo, parseInt(m[1], 10)); });
    const created = selected.map((e, i) => ({
      no: "PC-2569-" + String(maxNo + 1 + i).padStart(4, "0"),
      date, round, requester: e.name, empId: e.id, dept: e.dept,
      purpose: purposeText, amount: Number(picks[e.id].amount), actual: null,
      method, approver: "—", due, status: "รออนุมัติ", ref: "—"
    }));
    window.caSaveAll([...created, ...rows]);
    window.logActivity && window.logActivity("ขอเบิกเงินสด", `${purposeText} · ${created.length} คน · ฿${fmt0(total)}`, "expense");
    window.toast && window.toast(`ส่งคำขอเบิก ${created.length} คน รวม ฿${fmt0(total)} ให้อนุมัติแล้ว`);
    onClose && onClose();
  };

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer wide" style={{width: 720}}>
        <div className="drawer-head">
          <I.money size={16}/>
          <h3>เบิกเงินสดย่อย — เลือกพนักงานรายคน</h3>
          <span className="spacer"/>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>
        <div className="drawer-body" style={{display: "flex", flexDirection: "column", gap: 14}}>
          <div className="field-row cols-2">
            <div className="field"><label>วันที่เบิก</label><input className="input" value={date} onChange={e => setDate(e.target.value)}></input></div>
            <div className="field"><label>กำหนดเคลียร์</label><input className="input" value={due} onChange={e => setDue(e.target.value)}></input></div>
          </div>
          <div className="field-row cols-2">
            <div className="field"><label>เหตุผลการเบิก</label>
              <select className="input" value={reason} onChange={e => setReason(e.target.value)}>
                <option>เบิกเงินวันพุธ</option>
                <option>เบิกเงินวันเสาร์</option>
                <option>อื่นๆ</option>
              </select>
            </div>
            <div className="field"><label>วิธีรับเงิน</label>
              <select className="input" value={method} onChange={e => setMethod(e.target.value)}>
                <option>เงินสด</option><option>โอน · KBank</option>
              </select>
            </div>
          </div>
          {reason === "อื่นๆ" && (
            <div className="field"><label>ระบุเหตุผล (จำเป็นเมื่อเลือก "อื่นๆ")</label>
              <input className="input" value={otherReason} onChange={e => setOtherReason(e.target.value)} placeholder="เช่น ซื้ออะไหล่ด่วนร้านไม่มีบิล, ค่าน้ำมันส่งของต่างจังหวัด"></input>
            </div>
          )}

          <div>
            <div className="label mb" style={{display: "flex", justifyContent: "space-between", alignItems: "center"}}>
              <span>พนักงานที่ทำงานอยู่ ({emps.length} คน) — ติ๊กเลือกแล้วใส่จำนวนเงิน</span>
              <span style={{display: "flex", gap: 6}}>
                <button className="btn sm" onClick={() => setPicks(Object.fromEntries(emps.map(e => [e.id, { on: true, amount: (picks[e.id] && picks[e.id].amount) || "" }])))}>เลือกทุกคน</button>
                <button className="btn sm" onClick={() => setPicks({})}>ล้าง</button>
              </span>
            </div>
            <div style={{display: "flex", flexDirection: "column", gap: 6, maxHeight: 340, overflow: "auto", border: "1px solid var(--line)", borderRadius: 8, padding: 6}}>
              {emps.map(e => {
                const on = picks[e.id] && picks[e.id].on;
                return (
                  <div key={e.id} style={{display: "grid", gridTemplateColumns: "auto 1fr 150px", gap: 10, alignItems: "center", padding: "7px 10px", borderRadius: 6, background: on ? "var(--info-bg)" : "transparent", border: `1px solid ${on ? "var(--info)" : "transparent"}`}}>
                    <label style={{display: "flex", alignItems: "center", gap: 10, cursor: "pointer", minWidth: 0}}>
                      <input type="checkbox" checked={!!on} onChange={() => toggle(e.id)} style={{width: 16, height: 16, flexShrink: 0}}></input>
                      <span className="avatar" style={{width: 26, height: 26, fontSize: 10, flexShrink: 0}}>{e.name.slice(0, 2)}</span>
                    </label>
                    <div style={{minWidth: 0}}>
                      <div style={{fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{e.name}</div>
                      <div style={{fontSize: 11, color: "var(--ink-3)"}}>{e.role} · {e.dept}{e.status === "ทดลองงาน" ? " · ทดลองงาน" : ""}</div>
                    </div>
                    <input className="input" type="number" min="0" placeholder="จำนวนเงิน" disabled={!on}
                      value={(picks[e.id] && picks[e.id].amount) || ""}
                      onChange={ev => setAmt(e.id, ev.target.value)}
                      style={{textAlign: "right", height: 32, opacity: on ? 1 : 0.45}}></input>
                  </div>
                );
              })}
            </div>
          </div>

          <div style={{padding: "10px 14px", background: "var(--surface-2)", borderRadius: 8, display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13}}>
            <span>เลือก <b>{selected.length}</b> คน · เหตุผล: <b>{purposeText || "—"}</b></span>
            <span style={{fontSize: 16, fontWeight: 700}}>รวม ฿{fmt0(total)}</span>
          </div>
          <div style={{fontSize: 11.5, color: "var(--ink-3)"}}>เงินสดในมือกองทุน ฿{fmt0(D.PettyCashFund.onHand)} · ระบบจะออกใบเบิก 1 ใบต่อ 1 คน (เลขที่ต่อเนื่อง) สถานะ "รออนุมัติ"</div>
        </div>
        <div className="drawer-foot">
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="primary" icon={I.check} onClick={save}>ส่งขออนุมัติ ({selected.length} คน · ฿{fmt0(total)})</Btn>
        </div>
      </div>
    </>
  );
}

window.PettyCash = PettyCash;
window.CashAdvancePaper = CashAdvancePaper;
