// SSPHONE print docs — ใบเสร็จรับเงิน + ใบรับซ่อม (A4 + สลิป 80mm)

function docBranch(st, id) { return st.branches.find((b) => b.id === id) || st.branches[0] || { name: "", addr: "", tel: "", short: "", taxId: "" }; }

function DocHeaderA4({ br, st, title, docId, ts, logoSize = 64, compact, noQr }) {
  const s = (st && st.settings) || {};
  const qrSize = compact ? 60 : 90;
  return (
    <div style={{ display: "flex", gap: compact ? 11 : 16, alignItems: "flex-start", borderBottom: "2.5px solid #101B33", paddingBottom: compact ? 9 : 14 }}>
      <img src={logoSrc(st)} alt="logo" style={{ width: logoSize, height: logoSize, objectFit: "contain", flex: "none" }} />
      <div style={{ lineHeight: 1.45, minWidth: 0, flex: 1 }}>
        <div style={{ fontFamily: T.headFont, fontSize: compact ? 17 : 22, fontWeight: 800, letterSpacing: 0.5 }}>{s.name || "SSPHONE"}</div>
        <div style={{ fontSize: compact ? 9.5 : 11.5 }}>{s.tagline || "ศูนย์ซื้อ–ขาย–ซ่อม มือถือครบวงจร"} · {br.name}</div>
        <div style={{ fontSize: compact ? 9 : 10.5, color: "#444" }}>{s.addr || br.addr} · โทร {s.tel || br.tel}</div>
        {(s.taxId || br.taxId) && <div style={{ fontSize: compact ? 9 : 10.5, color: "#444" }}>เลขประจำตัวผู้เสียภาษี {s.taxId || br.taxId}</div>}
        {s.lineId && <div style={{ fontSize: compact ? 8.5 : 10, color: "#444", marginTop: 4 }}>Line: {s.lineId}</div>}
      </div>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: compact ? 4 : 6, marginLeft: "auto" }}>
        {!noQr && s.lineQr && <img src={s.lineQr} alt="QR" style={{ width: qrSize, height: qrSize, border: `1px solid #ccc` }} />}
        <div style={{ textAlign: "right", lineHeight: 1.5, whiteSpace: "nowrap" }}>
          <div style={{ fontFamily: T.headFont, fontSize: compact ? 15 : 17, fontWeight: 800 }}>{title}</div>
          <div style={{ fontSize: compact ? 11 : 12, fontWeight: 700 }}>{docId}</div>
          <div style={{ fontSize: compact ? 9 : 10.5, color: "#444" }}>{fmtDT(ts)}</div>
        </div>
      </div>
    </div>
  );
}

/* ── ใบเสร็จ A4 ── */
function ReceiptA4({ st, sale }) {
  const br = docBranch(st, sale.branch);
  const { lineQr } = st.settings || {};
  const sub = sale.items.reduce((a, i) => a + i.qty * i.price, 0);
  return (
    <div className="ss-doc-a4" style={{ width: 794, minHeight: 1050, background: "#fff", padding: "46px 52px", boxSizing: "border-box", fontFamily: T.bodyFont, color: "#101B33", display: "flex", flexDirection: "column" }}>
      <DocHeaderA4 st={st} br={br} title="ใบเสร็จรับเงิน" docId={sale.id} ts={sale.ts} noQr />
      <div style={{ display: "flex", gap: 30, margin: "14px 0", fontSize: 12, flexWrap: "wrap" }}>
        <div><span style={{ color: "#666" }}>ลูกค้า:</span> <b>{sale.customer || "ลูกค้าหน้าร้าน"}</b></div>
        <div><span style={{ color: "#666" }}>พนักงาน:</span> {userOf(st, sale.by).name}</div>
        <div><span style={{ color: "#666" }}>ชำระโดย:</span> {sale.pay}</div>
        {sale.refRepair && <div><span style={{ color: "#666" }}>อ้างอิงใบรับซ่อม:</span> <b style={{ fontFamily: "monospace" }}>{sale.refRepair}</b></div>}
      </div>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
        <thead>
          <tr style={{ background: "#F1F4FA" }}>
            {["#", "รายการ", "จำนวน", "ราคา/หน่วย", "รวม"].map((h, i) => (
              <th key={h} style={{ textAlign: i >= 2 ? "right" : "left", padding: "8px 10px", borderBottom: "1.5px solid #101B33", fontWeight: 700 }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {sale.items.map((it, i) => {
            const p = prodOf(st, it.productId) || { name: it.name || "—", sku: "" };
            return (
              <tr key={i}>
                <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0" }}>{i + 1}</td>
                <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0" }}>{p.name}{(() => { const sp = specOf(st, p); return sp ? <span style={{ color: "#555" }}> · {sp}</span> : null; })()}<div style={{ fontSize: 10, color: "#777" }}>{p.sku}</div></td>
                <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0", textAlign: "right" }}>{it.qty}</td>
                <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0", textAlign: "right" }}>{fmtMoney(it.price)}</td>
                <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0", textAlign: "right", fontWeight: 700 }}>{fmtMoney(it.qty * it.price)}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 12 }}>
        <div style={{ width: 260, fontSize: 12.5, display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}><span>รวม</span><span>{fmtMoney(sub)}</span></div>
          <div style={{ display: "flex", justifyContent: "space-between" }}><span>ส่วนลด</span><span>− {fmtMoney(sale.discount || 0)}</span></div>
          <div style={{ display: "flex", justifyContent: "space-between", fontFamily: T.headFont, fontSize: 17, fontWeight: 800, borderTop: "2px solid #101B33", paddingTop: 8 }}>
            <span>ยอดสุทธิ</span><span>{fmtMoney(sub - (sale.discount || 0))}</span>
          </div>
        </div>
      </div>
      <div style={{ marginTop: "auto", display: "flex", alignItems: "flex-end", justifyContent: "space-between", paddingTop: 36 }}>
        <div style={{ fontSize: 10.5, color: "#666", lineHeight: 1.7, maxWidth: 380 }}>
          {sale.refRepair ? (() => {
            const rt = (st.settings && st.settings.repairTerms) || {};
            return (
              <React.Fragment>
                <div style={{ fontWeight: 800, color: "#101B33", marginBottom: 2 }}>เงื่อนไขการรับซ่อม</div>
                {rt.responsibility && <div>1. {rt.responsibility}</div>}
                {rt.warranty && <div>2. {rt.warranty}</div>}
                {rt.pickup && <div>3. {rt.pickup}</div>}
                <div>4. รับประกันอาการเดิมและอะไหล่ที่เปลี่ยน เป็นเวลา {rt.warrantyTime || "3 เดือน"}</div>
              </React.Fragment>
            );
          })() : (() => {
            const stt = (st.settings && st.settings.saleTerms) || {};
            return (
              <React.Fragment>
                {stt.device && <div>เครื่อง: {stt.device}</div>}
                {stt.accessory && <div>อุปกรณ์: {stt.accessory}</div>}
              </React.Fragment>
            );
          })()}
        </div>
        <div style={{ textAlign: "center" }}>
          <BarcodeArt value={sale.id} />
        </div>
        <div style={{ textAlign: "center", fontSize: 11 }}>
          <div style={{ borderBottom: "1px dotted #888", width: 160, height: 36 }}></div>
          ผู้รับเงิน
        </div>
      </div>
    </div>
  );
}

/* ── สลิป 80mm ── */
function SlipShell({ children }) {
  return (
    <div className="ss-doc-slip" style={{ width: 302, background: "#fff", padding: "18px 14px", boxSizing: "border-box", fontFamily: T.bodyFont, color: "#000", fontSize: 11.5, lineHeight: 1.55 }}>
      {children}
    </div>
  );
}
function SlipHead({ br, title, st }) {
  return (
    <div style={{ textAlign: "center", borderBottom: "1px dashed #000", paddingBottom: 8, marginBottom: 8 }}>
      <img src="assets/ssphone-logo.png" alt="" style={{ width: 44, height: 44, objectFit: "contain" }} />
      <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 15 }}>SSPHONE · {br.short}</div>
      <div style={{ fontSize: 9.5 }}>{(st && st.settings && st.settings.addr) || br.addr}</div>
      <div style={{ fontSize: 9.5 }}>โทร {(st && st.settings && st.settings.tel) || br.tel}{((st && st.settings && st.settings.taxId) || br.taxId) ? ` · เลขภาษี ${(st && st.settings && st.settings.taxId) || br.taxId}` : ""}</div>
      <div style={{ fontWeight: 800, marginTop: 5, fontSize: 12.5 }}>— {title} —</div>
    </div>
  );
}
function SlipRow({ l, r, bold, big }) {
  return <div style={{ display: "flex", justifyContent: "space-between", fontWeight: bold ? 800 : 400, fontSize: big ? 14 : "inherit" }}><span>{l}</span><span>{r}</span></div>;
}

function ReceiptSlip({ st, sale }) {
  const br = docBranch(st, sale.branch);
  const sub = sale.items.reduce((a, i) => a + i.qty * i.price, 0);
  return (
    <SlipShell>
      <SlipHead br={br} title="ใบเสร็จรับเงิน" st={st} />
      <SlipRow l={sale.id} r={fmtDT(sale.ts)} />
      {sale.refRepair && <SlipRow l="อ้างอิงใบรับซ่อม" r={sale.refRepair} />}
      <SlipRow l={`พนักงาน: ${userOf(st, sale.by).name.split(" ")[0]}`} r={sale.pay} />
      <div style={{ borderTop: "1px dashed #000", margin: "7px 0" }}></div>
      {sale.items.map((it, i) => {
        const p = prodOf(st, it.productId) || { name: it.name || "—" };
        return (
          <div key={i} style={{ marginBottom: 4 }}>
            <div>{p.name}{(() => { const sp = specOf(st, p); return sp ? " · " + sp : ""; })()}</div>
            <SlipRow l={`  ${it.qty} x ${fmtMoney(it.price)}`} r={fmtMoney(it.qty * it.price)} />
          </div>
        );
      })}
      <div style={{ borderTop: "1px dashed #000", margin: "7px 0" }}></div>
      <SlipRow l="รวม" r={fmtMoney(sub)} />
      {sale.discount > 0 && <SlipRow l="ส่วนลด" r={`-${fmtMoney(sale.discount)}`} />}
      <SlipRow l="ยอดสุทธิ" r={fmtMoney(sub - (sale.discount || 0))} bold big />
      <div style={{ textAlign: "center", marginTop: 10 }}>
        <BarcodeArt value={sale.id} height={30} />
        <div style={{ marginTop: 6 }}>ขอบคุณที่ใช้บริการ ♥</div>
        <div style={{ fontSize: 9.5 }}>เครื่องมือสองรับประกันร้าน 30 วัน</div>
      </div>
    </SlipShell>
  );
}

/* ── ใบรับซ่อม A4 (compact=true สำหรับ 2 ใบ/แผ่น) ── */
function RepairDocA4({ st, rp, compact }) {
  const br = docBranch(st, rp.branch);
  const s = st.settings || {};
  const terms = s.repairTerms || {};
  const pdpa = s.pdpa || {};
  const fs = compact ? 0.86 : 1; // scale factor for fonts
  const px = (n) => Math.round(n * fs);
  return (
    <div className="ss-doc-a4" style={{ width: 794, minHeight: compact ? 0 : 1050, height: compact ? "100%" : undefined, background: "#fff", padding: compact ? "14px 28px" : "32px 42px", boxSizing: "border-box", fontFamily: T.bodyFont, color: "#101B33", display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ display: "flex", gap: compact ? 11 : 16, alignItems: "flex-start", borderBottom: "2.5px solid #101B33", paddingBottom: compact ? 9 : 14 }}>
        <img src={logoSrc(st)} alt="logo" style={{ width: compact ? 58 : 84, height: compact ? 58 : 84, objectFit: "contain", flex: "none" }} />
        <div style={{ lineHeight: 1.45, minWidth: 0, flex: 1 }}>
          <div style={{ fontFamily: T.headFont, fontSize: compact ? 17 : 22, fontWeight: 800, letterSpacing: 0.5 }}>{s.name || "SSPHONE"}</div>
          <div style={{ fontSize: compact ? 9.5 : 11.5 }}>{s.tagline || "ศูนย์ซื้อ–ขาย–ซ่อม มือถือครบวงจร"} · {br.name}</div>
          <div style={{ fontSize: compact ? 9 : 10.5, color: "#444" }}>{s.addr || br.addr} · โทร {s.tel || br.tel}</div>
          {(s.taxId || br.taxId) && <div style={{ fontSize: compact ? 9 : 10.5, color: "#444" }}>เลขประจำตัวผู้เสียภาษี {s.taxId || br.taxId}</div>}
          {s.lineId && <div style={{ fontSize: compact ? 8.5 : 10, color: "#444", marginTop: 4 }}>Line: {s.lineId}</div>}
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: compact ? 4 : 6, marginLeft: "auto", textAlign: "center" }}>
          <div style={{ textAlign: "right", lineHeight: 1.5, whiteSpace: "nowrap" }}>
            <div style={{ fontFamily: T.headFont, fontSize: compact ? 15 : 17, fontWeight: 800 }}>ใบรับซ่อม</div>
            <div style={{ fontSize: compact ? 11 : 12, fontWeight: 700 }}>{rp.id}</div>
            <div style={{ fontSize: compact ? 9 : 10.5, color: "#444" }}>{fmtDT(rp.ts)}</div>
          </div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: compact ? "5px 24px" : "10px 28px", margin: compact ? "10px 0" : "16px 0", fontSize: px(12.5) }}>
        <div><span style={{ color: "#666" }}>ลูกค้า:</span> <b>{rp.customer}</b></div>
        <div><span style={{ color: "#666" }}>โทร:</span> <b>{rp.phone}</b></div>
        <div><span style={{ color: "#666" }}>เครื่อง:</span> <b>{rp.brand ? rp.brand + " " : ""}{rp.device}</b>{rp.color ? <span> · สี{rp.color}</span> : null}</div>
        <div><span style={{ color: "#666" }}>IMEI/SN:</span> <span style={{ fontFamily: "monospace" }}>{rp.imei || "—"}</span></div>
        <div><span style={{ color: "#666" }}>รหัสเครื่อง:</span> <span style={{ fontFamily: "monospace" }}>{rp.code || "—"}</span></div>
        <div><span style={{ color: "#666" }}>สิ่งที่รับมาด้วย:</span> {(rp.accessories && rp.accessories.length) ? rp.accessories.join(" · ") : "ไม่มี"}</div>
        <div><span style={{ color: "#666" }}>นัดรับ:</span> {rp.due ? fmtDate(rp.due) : "รอแจ้ง"}</div>
        <div><span style={{ color: "#666" }}>ช่างผู้รับผิดชอบ:</span> {userOf(st, rp.tech).name}</div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: compact ? "10px 16px" : "14px 20px", marginBottom: compact ? 10 : 16 }}>        <div style={{ border: "1.5px solid #101B33", borderRadius: 8, padding: compact ? "7px 12px" : "10px 14px", fontSize: px(12), lineHeight: 1.4, maxHeight: compact ? 56 : 72, overflow: "hidden" }}>
          <div style={{ fontWeight: 800, marginBottom: 2, fontSize: px(12.5) }}>อาการที่แจ้ง / งานที่ตกลง</div>
          <div style={{ fontSize: px(11.5) }}>{rp.issue}</div>
          {rp.symptom && <div style={{ color: "#444", marginTop: 2, fontSize: px(10.5) }}>{rp.symptom}</div>}
        </div>
        {s.lineQr && <img src={s.lineQr} alt="QR" style={{ width: compact ? 65 : 85, height: compact ? 65 : 85, border: `1px solid #ccc`, borderRadius: 4, alignSelf: "start" }} />}
      </div>
      <div style={{ display: "flex", gap: compact ? 9 : 14, fontSize: px(13) }}>
        <div style={{ flex: 1, background: "#F1F4FA", borderRadius: 8, padding: compact ? "7px 12px" : "10px 16px" }}>ค่าซ่อมประเมิน<div style={{ fontFamily: T.headFont, fontSize: px(20), fontWeight: 800 }}>{fmtMoney(rp.est)}</div></div>
        <div style={{ flex: 1, background: "#F1F4FA", borderRadius: 8, padding: compact ? "7px 12px" : "10px 16px" }}>มัดจำแล้ว<div style={{ fontFamily: T.headFont, fontSize: px(20), fontWeight: 800 }}>{fmtMoney(rp.deposit)}</div></div>
        <div style={{ flex: 1, background: "#101B33", color: "#fff", borderRadius: 8, padding: compact ? "7px 12px" : "10px 16px" }}>คงเหลือชำระ<div style={{ fontFamily: T.headFont, fontSize: px(20), fontWeight: 800 }}>{fmtMoney((rp.est || 0) - (rp.deposit || 0))}</div></div>
      </div>
      <div style={{ fontSize: px(9.3), color: "#555", lineHeight: 1.65, marginTop: compact ? 9 : 16, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "2px 18px" }}>
        <div style={{ gridColumn: "1/-1", fontWeight: 800, color: "#101B33", fontSize: px(10.5), marginBottom: 1 }}>เงื่อนไขการรับซ่อม</div>
        <div>1. {terms.responsibility}</div>
        <div>2. {terms.warranty}</div>
        <div>3. {terms.pickup}</div>
        <div>4. รับประกันอาการเดิมและอะไหล่ที่เปลี่ยน เป็นเวลา {terms.warrantyTime || "3 เดือน"}</div>
      </div>
      {compact ? (
        <div style={{ fontSize: px(8.6), color: "#666", lineHeight: 1.5, marginTop: 7, borderTop: "1px solid #E2E7F0", paddingTop: 6 }}>
          <b style={{ color: "#101B33" }}>PDPA:</b> {pdpa.collect || "ร้านเก็บข้อมูลเพื่อการซ่อมและติดต่อเท่านั้น"} · ลูกค้ายินยอมให้ร้านดำเนินการซ่อมตามที่ตกลง
        </div>
      ) : (
        <div style={{ fontSize: px(8.8), color: "#666", lineHeight: 1.6, marginTop: 12, borderTop: "1px solid #E2E7F0", paddingTop: 9 }}>
          <div style={{ fontWeight: 800, color: "#101B33", fontSize: px(9.8), marginBottom: 2 }}>การคุ้มครองข้อมูลส่วนบุคคล (PDPA)</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1px 18px" }}>
            <div><b>การเก็บข้อมูล:</b> {pdpa.collect}</div>
            <div><b>สิทธิเจ้าของข้อมูล:</b> {pdpa.rights}</div>
            <div><b>ระยะเวลาเก็บ:</b> {pdpa.retention}</div>
            <div><b>การให้ความยินยอม:</b> {pdpa.consent}</div>
          </div>
        </div>
      )}
      <div style={{ marginTop: compact ? "auto" : 12, display: "flex", alignItems: "flex-end", justifyContent: "flex-start", gap: compact ? 10 : 14, paddingTop: compact ? 4 : 16 }}>
        <div style={{ textAlign: "center", fontSize: px(10.5), flex: 1 }}>
          <div style={{ borderBottom: "1px dotted #888", height: compact ? 26 : 34 }}></div>ลูกค้า (ลงชื่อยินยอม + ส่งซ่อม)
        </div>
        <div style={{ textAlign: "center", fontSize: px(10.5), flex: 1 }}>
          <div style={{ borderBottom: "1px dotted #888", height: compact ? 26 : 34 }}></div>เจ้าหน้าที่ผู้รับเครื่อง
        </div>
      </div>
      <div style={{ textAlign: "center", marginTop: compact ? 6 : 10 }}>
        <BarcodeArt value={rp.id} height={compact ? 26 : 34} />
      </div>
    </div>
  );
}

/* 2 ใบใน 1 แผ่น A4 — แนวนอน 2 ใบเรียงบน-ล่างในกระดาษแนวตั้ง (ตัดแบ่งครึ่ง) */
function RepairDoc2Up({ st, rp }) {
  return (
    <div style={{ width: 794, height: 1040, background: "#fff", display: "flex", flexDirection: "column", boxSizing: "border-box" }}>
      <div style={{ flex: 1, minHeight: 0, overflow: "hidden" }}><RepairDocA4 st={st} rp={rp} compact /></div>
      <div style={{ borderTop: "1.5px dashed #B6C2DA", textAlign: "center", fontSize: 9, color: "#9AA6BE", padding: "1px 0" }}>✂ ตัดตามรอยประ — ส่วนบนสำหรับลูกค้า · ส่วนล่างสำหรับร้าน</div>
      <div style={{ flex: 1, minHeight: 0, overflow: "hidden" }}><RepairDocA4 st={st} rp={rp} compact /></div>
    </div>
  );
}

function RepairSlip({ st, rp }) {
  const br = docBranch(st, rp.branch);
  return (
    <SlipShell>
      <SlipHead br={br} title="ใบรับซ่อม" st={st} />
      <SlipRow l={rp.id} r={fmtDT(rp.ts)} bold />
      <div style={{ borderTop: "1px dashed #000", margin: "7px 0" }}></div>
      <SlipRow l="ลูกค้า" r={rp.customer} />
      <SlipRow l="โทร" r={rp.phone} />
      <SlipRow l="เครื่อง" r={`${rp.brand ? rp.brand + " " : ""}${rp.device}`} />
      {rp.color && <SlipRow l="สี" r={rp.color} />}
      {rp.code && <SlipRow l="รหัสเครื่อง" r={rp.code} />}
      <div style={{ fontSize: 10, fontFamily: "monospace" }}>IMEI: {rp.imei || "—"}</div>
      {rp.accessories && rp.accessories.length > 0 && <div style={{ fontSize: 10 }}>รับมาด้วย: {rp.accessories.join(", ")}</div>}
      <div style={{ borderTop: "1px dashed #000", margin: "7px 0" }}></div>
      <div><b>อาการ:</b> {rp.issue}</div>
      <div style={{ fontSize: 10.5, color: "#333" }}>{rp.symptom}</div>
      <div style={{ borderTop: "1px dashed #000", margin: "7px 0" }}></div>
      <SlipRow l="ประเมิน" r={fmtMoney(rp.est)} />
      <SlipRow l="มัดจำ" r={fmtMoney(rp.deposit)} />
      <SlipRow l="คงเหลือ" r={fmtMoney((rp.est || 0) - (rp.deposit || 0))} bold big />
      <SlipRow l="นัดรับ" r={rp.due ? fmtDate(rp.due) : "รอแจ้ง"} />
      <div style={{ textAlign: "center", marginTop: 10 }}>
        <BarcodeArt value={rp.id} height={30} />
        <div style={{ fontSize: 9, marginTop: 5, lineHeight: 1.6 }}>กรุณานำสลิปนี้มารับเครื่อง · ประกันงานซ่อม {(st.settings && st.settings.repairTerms && st.settings.repairTerms.warrantyTime) || "3 เดือน"}<br />ร้านไม่รับผิดชอบข้อมูลในเครื่อง</div>
        {st.settings && st.settings.lineQr && <img src={st.settings.lineQr} alt="QR" style={{ width: 60, height: 60, marginTop: 8, border: "1px solid #000" }} />}
      </div>
    </SlipShell>
  );
}

/* ── ใบรับจำนำ A4 ── */
function PawnDocA4({ st, pw }) {
  const br = docBranch(st, pw.branch);
  const row = (label, val, bold) => (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px dashed #ccc", fontSize: 13 }}>
      <span style={{ color: "#555" }}>{label}</span><span style={{ fontWeight: bold ? 800 : 600 }}>{val}</span>
    </div>
  );
  return (
    <div style={{ width: 794, minHeight: 1050, background: "#fff", padding: "40px 46px", fontFamily: T.bodyFont, color: "#101B33", boxSizing: "border-box" }}>
      <DocHeaderA4 br={br} st={st} title="ใบรับจำนำ / สัญญาขายฝากขายคืน" docId={pw.id} ts={pw.start} logoSize={70} noQr />
      <div style={{ textAlign: "center", fontFamily: T.headFont, fontWeight: 800, fontSize: 19, margin: "18px 0 14px", letterSpacing: 1 }}>ใบรับจำนำเครื่อง</div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 14 }}>
        <div>เลขที่: <b>{pw.id}</b></div>
        <div>วันที่: <b>{fmtDate(pw.start)}</b></div>
      </div>
      <div style={{ marginBottom: 16 }}>
        {row("ชื่อผู้จำนำ", pw.customer, true)}
        {row("เบอร์โทรติดต่อ", pw.phone)}
        {row("ยี่ห้อ / รุ่น", `${pw.brand} ${pw.model}`, true)}
        {pw.storage || pw.color ? row("ความจุ / สี", `${pw.storage || "—"}${pw.color ? " · " + pw.color : ""}`) : null}
        {pw.imei ? row("IMEI / SN", pw.imei) : null}
        {pw.code ? row("รหัสเครื่อง", pw.code) : null}
        {pw.battery ? row("แบตเตอรี่", pw.battery + "%") : null}
        {row("ยอดรับจำนำ", fmtMoney(pw.amount), true)}
        {row("ยอดชำระ/ดอกเบี้ย", fmtMoney(pw.paid))}
        {row("วันเริ่มจำนำ", fmtDate(pw.start))}
        {row("วันครบกำหนดไถ่คืน", fmtDate(pw.due), true)}
        {pw.note ? row("หมายเหตุ", pw.note) : null}
      </div>
      <div style={{ background: "#FFF3E6", border: "1px solid #F2C99A", borderRadius: 8, padding: "12px 16px", fontSize: 11.5, color: "#7A4A12", lineHeight: 1.7, marginBottom: 26 }}>
        เงื่อนไข: ผู้จำนำต้องมาไถ่ถอนภายในวันครบกำหนด หากเกินกำหนดทางร้านถือว่าเครื่องหลุดจำนำ และร้านมีสิทธิ์จำหน่ายต่อได้· โปรดเก็บใบรับนี้ไว้เป็นหลักฐาน
      </div>
      <div style={{ display: "flex", justifyContent: "space-around", marginTop: 48, fontSize: 12 }}>
        <div style={{ textAlign: "center" }}><div style={{ borderTop: "1px solid #333", width: 180, paddingTop: 6 }}>ลงชื่อผู้จำนำ</div></div>
        <div style={{ textAlign: "center" }}><div style={{ borderTop: "1px solid #333", width: 180, paddingTop: 6 }}>ลงชื่อผู้รับจำนำ</div></div>
      </div>
      {st.settings && st.settings.lineQr && (
        <div style={{ display: "flex", justifyContent: "center", marginTop: 36 }}>
          <img src={st.settings.lineQr} alt="QR" style={{ width: 110, height: 110, border: "1px solid #ccc", borderRadius: 4 }} />
        </div>
      )}
    </div>
  );
}

/* ── ใบกำกับภาษี A4 ── */
function TaxInvoiceA4({ st, inv }) {
  const s = (st && st.settings) || {};
  const subtotal = (inv.items || []).reduce((a, i) => a + (Number(i.amount) || (Number(i.qty) || 0) * (Number(i.unitPrice) || 0)), 0);
  const afterDisc = subtotal - (Number(inv.discount) || 0);
  const vat = Math.round(afterDisc / 1.07 * 0.07);
  const beforeVat = afterDisc - vat;
  return (
    <div className="ss-doc-a4" style={{ width: 794, minHeight: 1050, background: "#fff", padding: "46px 52px", boxSizing: "border-box", fontFamily: T.bodyFont, color: "#101B33", display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", gap: 16, alignItems: "flex-start", borderBottom: "2.5px solid #101B33", paddingBottom: 14 }}>
        <img src={logoSrc(st)} alt="logo" style={{ width: 64, height: 64, objectFit: "contain", flex: "none" }} />
        <div style={{ lineHeight: 1.45, minWidth: 0 }}>
          <div style={{ fontFamily: T.headFont, fontSize: 22, fontWeight: 800, letterSpacing: 0.5 }}>{s.name || "SSPHONE"}</div>
          <div style={{ fontSize: 10.5, color: "#444" }}>{s.addr}</div>
          <div style={{ fontSize: 10.5, color: "#444" }}>โทร {s.tel}{s.taxId ? ` · เลขประจำตัวผู้เสียภาษี ${s.taxId}` : ""}</div>
        </div>
        <div style={{ marginLeft: "auto", textAlign: "right", lineHeight: 1.5, whiteSpace: "nowrap" }}>
          <div style={{ fontFamily: T.headFont, fontSize: 18, fontWeight: 800 }}>ใบกำกับภาษี / ใบเสร็จรับเงิน</div>
          <div style={{ fontSize: 12, fontWeight: 700 }}>{inv.id}</div>
          <div style={{ fontSize: 10.5, color: "#444" }}>{fmtDT(inv.ts)}</div>
          {inv.refInv && <div style={{ fontSize: 10, color: "#777" }}>อ้างอิงใบเสร็จ {inv.refInv}</div>}
        </div>
      </div>

      <div style={{ border: "1px solid #C9D2E3", borderRadius: 8, padding: "12px 16px", margin: "16px 0", fontSize: 12, lineHeight: 1.6 }}>
        <div style={{ fontWeight: 700, marginBottom: 3, color: "#666", fontSize: 10.5 }}>ลูกค้า / ผู้ซื้อ</div>
        <div style={{ fontWeight: 800, fontSize: 14 }}>{inv.customerName || "—"}</div>
        {inv.customerTaxId && <div>เลขประจำตัวผู้เสียภาษี: <b>{inv.customerTaxId}</b></div>}
        {inv.customerAddress && <div style={{ whiteSpace: "pre-wrap", color: "#444" }}>{inv.customerAddress}</div>}
      </div>

      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
        <thead>
          <tr style={{ background: "#F1F4FA" }}>
            {["#", "รายการ", "จำนวน", "ราคา/หน่วย", "จำนวนเงิน"].map((h, i) => (
              <th key={h} style={{ textAlign: i >= 2 ? "right" : "left", padding: "8px 10px", borderBottom: "1.5px solid #101B33", fontWeight: 700 }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {(inv.items || []).filter((it) => it.description).map((it, i) => (
            <tr key={i}>
              <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0" }}>{i + 1}</td>
              <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0" }}>{it.description}</td>
              <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0", textAlign: "right" }}>{it.qty}</td>
              <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0", textAlign: "right" }}>{fmtMoney(it.unitPrice)}</td>
              <td style={{ padding: "8px 10px", borderBottom: "1px solid #E2E7F0", textAlign: "right", fontWeight: 700 }}>{fmtMoney(it.amount || it.qty * it.unitPrice)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 12 }}>
        <div style={{ width: 280, fontSize: 12.5, display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}><span>ยอดรวม</span><span>{fmtMoney(subtotal)}</span></div>
          {(Number(inv.discount) || 0) > 0 && <div style={{ display: "flex", justifyContent: "space-between" }}><span>ส่วนลด</span><span>− {fmtMoney(Number(inv.discount) || 0)}</span></div>}
          <div style={{ display: "flex", justifyContent: "space-between" }}><span>มูลค่าก่อนภาษี</span><span>{fmtMoney(beforeVat)}</span></div>
          <div style={{ display: "flex", justifyContent: "space-between" }}><span>ภาษีมูลค่าเพิ่ม 7%</span><span>{fmtMoney(vat)}</span></div>
          <div style={{ display: "flex", justifyContent: "space-between", fontFamily: T.headFont, fontSize: 17, fontWeight: 800, borderTop: "2px solid #101B33", paddingTop: 8 }}>
            <span>รวมทั้งสิ้น</span><span>{fmtMoney(afterDisc)}</span>
          </div>
        </div>
      </div>

      {inv.notes && <div style={{ marginTop: 16, fontSize: 11, color: "#555", lineHeight: 1.6 }}><b>หมายเหตุ:</b> {inv.notes}</div>}

      <div style={{ marginTop: "auto", display: "flex", alignItems: "flex-end", justifyContent: "space-between", paddingTop: 44 }}>
        <div style={{ textAlign: "center", fontSize: 11 }}>
          <div style={{ borderBottom: "1px dotted #888", width: 170, height: 36 }}></div>
          ผู้รับเงิน / ผู้มีอำนาจลงนาม
        </div>
        <div style={{ textAlign: "center", fontSize: 11 }}>
          <div style={{ borderBottom: "1px dotted #888", width: 170, height: 36 }}></div>
          ผู้ซื้อ / ผู้รับสินค้า
        </div>
      </div>
    </div>
  );
}

/* ── Print modal: preview + เลือก A4/สลิป + พิมพ์ ── */
function PrintModal({ open, onClose, kind, data }) {
  const { st } = useStore();
  const [fmt, setFmt] = React.useState("a4");
  React.useEffect(() => { if (open) setFmt("a4"); }, [open]);
  if (!open || !data) return null;

  const Doc = kind === "sale" ? (fmt === "slip" ? ReceiptSlip : ReceiptA4)
    : kind === "tax" ? TaxInvoiceA4
    : kind === "pawn" ? PawnDocA4
    : (fmt === "slip" ? RepairSlip : fmt === "a4x2" ? RepairDoc2Up : RepairDocA4);
  const prop = kind === "sale" ? { sale: data } : kind === "tax" ? { inv: data } : kind === "pawn" ? { pw: data } : { rp: data };
  const isSlip = fmt === "slip" && kind !== "pawn" && kind !== "tax";
  const scale = isSlip ? 1.05 : 0.72;
  const w = isSlip ? 302 : 794;
  const h = isSlip ? null : (fmt === "a4x2" ? 1123 : 1050);
  const fmtOptions = kind === "sale"
    ? [["a4", "🗎 A4"], ["slip", "▯ สลิป 80mm"]]
    : kind === "pawn" || kind === "tax" ? [["a4", "🗎 A4"]]
    : [["a4", "🗎 A4 (1 ใบ)"], ["a4x2", "🗇 A4 (2 ใบ/แผ่น)"], ["slip", "▯ สลิป 80mm"]];

  const doPrint = () => {
    const styleEl = document.createElement("style");
    styleEl.textContent = isSlip
      ? "@page { size: 80mm auto; margin: 4mm; }"
      : "@page { size: A4; margin: 0; }";
    document.head.appendChild(styleEl);
    document.body.classList.add("ss-printing");
    let done = false;
    const cleanup = () => {
      if (done) return;
      done = true;
      styleEl.remove();
      document.body.classList.remove("ss-printing");
      window.removeEventListener("afterprint", cleanup);
      window.removeEventListener("focus", onFocus);
    };
    // คืนค่าหลังพิมพ์เสร็จจริง (รองรับมือถือ/แท็บเล็ตที่เปิดแผ่นพิมพ์แบบ async)
    const onFocus = () => setTimeout(cleanup, 200);
    window.addEventListener("afterprint", cleanup);
    window.addEventListener("focus", onFocus);
    // ให้ DOM อัปเดต class ก่อนเรียก print หนึ่งเฟรม
    requestAnimationFrame(() => requestAnimationFrame(() => window.print()));
    // กันค้างกรณี event ไม่ยิง (เผื่อไว้นานพอให้ผู้ใช้เลือกขนาดกระดาษ)
    setTimeout(cleanup, 60000);
  };

  return (
    <Modal open={open} onClose={onClose} width={isSlip ? 440 : 860} noPad
      title={kind === "sale" ? `ใบเสร็จ ${data.id}` : kind === "tax" ? `ใบกำกับภาษี ${data.id}` : kind === "pawn" ? `ใบรับจำนำ ${data.id}` : `ใบรับซ่อม ${data.id}`}
      footer={<React.Fragment>
        <div style={{ marginRight: "auto", display: "flex", gap: 6, flexWrap: "wrap" }}>
          {fmtOptions.map(([v, l]) => (
            <Btn key={v} sm kind={fmt === v ? "primary" : "ghost"} onClick={() => setFmt(v)}>{l}</Btn>
          ))}
        </div>
        <Btn kind="ghost" onClick={onClose}>ปิด</Btn>
        <Btn onClick={doPrint}>⎙ พิมพ์ / บันทึก PDF</Btn>
      </React.Fragment>}>
      <div style={{ background: "#DDE3EE", padding: 22, display: "flex", justifyContent: "center", maxHeight: "74vh", overflowY: "auto" }}>
        <div style={{ width: w * scale, height: h ? h * scale : "auto", flex: "none" }}>
          <div style={{ transform: `scale(${scale})`, transformOrigin: "top left", boxShadow: "0 8px 30px rgba(10,18,42,.25)", width: w }}>
            <Doc st={st} {...prop} />
          </div>
        </div>
      </div>
      {/* hidden full-size copy for actual printing */}
      {ReactDOM.createPortal(
        <div className="ss-print-area"><Doc st={st} {...prop} /></div>,
        document.getElementById("print-mount")
      )}
    </Modal>
  );
}

Object.assign(window, { PrintModal, ReceiptA4, ReceiptSlip, RepairDocA4, RepairDoc2Up, RepairSlip, PawnDocA4, TaxInvoiceA4 });
