// Receipt issuance flow — review → confirm → preview/print
// Used by PageJobDetail (ออกใบเสร็จ from a job) and PageBilling (issue or view)

const { useState: uRxS, useEffect: uRxE, useMemo: uRxM, useRef: uRxR } = React;

// ---- Default lines for a job (used when opening from a job) ----
function defaultLinesForJob(jobId) {
  // Different jobs get a believable mock breakdown
  const presets = {
    "J2604-000007": [
      { type: "svc",  code: "BRAKE-PAD",       name: "เปลี่ยนผ้าเบรกหน้า",        qty: 1, price: 800 },
      { type: "part", code: "BP-FRONT-SEDAN",  name: "ผ้าเบรกหน้า รถเก๋งทั่วไป",   qty: 1, price: 1100 },
      { type: "svc",  code: "BRAKE-OIL",       name: "เปลี่ยนน้ำมันเบรก",          qty: 1, price: 450 },
      { type: "part", code: "BRAKE-FLUID",     name: "น้ำมันเบรก DOT-4 500ml",     qty: 1, price: 180 },
    ],
    "J2604-000006": [
      { type: "svc",  code: "OIL-CHG",  name: "เปลี่ยนถ่ายน้ำมันเครื่อง",      qty: 1, price: 350 },
      { type: "part", code: "OIL-5W30", name: "น้ำมันเครื่อง 5W-30 (4L)",     qty: 1, price: 950 },
      { type: "part", code: "FILTER-O", name: "กรองน้ำมันเครื่อง",            qty: 1, price: 220 },
      { type: "svc",  code: "INSPECT",  name: "ตรวจเช็คทั่วไป 30 จุด",        qty: 1, price: 200 },
    ],
  };
  return presets[jobId] || [
    { type: "svc",  code: "GEN-SVC",  name: "ค่าบริการ",  qty: 1, price: 800 },
    { type: "part", code: "GEN-PART", name: "อะไหล่",     qty: 1, price: 700 },
  ];
}

function nextInvoiceId() {
  // Bump the highest INV2604-XXXXXX
  const max = (window.GS.INVOICES || []).reduce((m, inv) => {
    const n = parseInt((inv.id.split("-")[1] || "0"), 10);
    return n > m ? n : m;
  }, 0);
  return `INV2604-${String(max + 1).padStart(6, "0")}`;
}

// =============================================================
// ReceiptModal — multi-step (review → confirm → print)
// =============================================================
function ReceiptModal({ open, onClose, job, invoice, initialStep = "review" }) {
  const I = window.I;
  const GS = window.GS;
  const [step, setStep] = uRxS(initialStep);
  const [issuedId, setIssuedId] = uRxS(null);

  // Resolve customer / vehicle / lines from the source
  const ctx = uRxM(() => {
    if (invoice) {
      const c = GS.CUSTOMERS.find(c => c.id === invoice.custId);
      const j = GS.JOBS.find(j => j.id === invoice.jobId);
      const v = j && GS.VEHICLES.find(v => v.id === j.vehId);
      return {
        customer: c, vehicle: v, jobId: invoice.jobId,
        lines: defaultLinesForJob(invoice.jobId),
        existingInvoiceId: invoice.id,
      };
    }
    if (job) {
      const c = GS.CUSTOMERS.find(c => c.id === job.custId);
      const v = GS.VEHICLES.find(v => v.id === job.vehId);
      return {
        customer: c, vehicle: v, jobId: job.id,
        lines: defaultLinesForJob(job.id),
        existingInvoiceId: null,
      };
    }
    return null;
  }, [job, invoice]);

  const [lines, setLines] = uRxS(() => ctx ? ctx.lines : []);
  const [taxInvoice, setTaxInvoice] = uRxS(true);
  const [discount, setDiscount] = uRxS(0);
  const [paymentMethod, setPaymentMethod] = uRxS("transfer");
  const [paidNow, setPaidNow] = uRxS(true);
  const [note, setNote] = uRxS("");

  // Reset when reopened with different source
  uRxE(() => {
    if (open) {
      setStep(initialStep);
      setIssuedId(invoice ? invoice.id : null);
      setLines(ctx ? ctx.lines : []);
      setDiscount(0);
      setNote("");
    }
  }, [open, ctx, invoice, initialStep]);

  // Esc / lock scroll
  uRxE(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open || !ctx) return null;

  const sub = lines.reduce((s, l) => s + l.qty * l.price, 0);
  const afterDisc = Math.max(0, sub - (discount || 0));
  const vat = +(afterDisc * 0.07).toFixed(2);
  const total = +(afterDisc + vat).toFixed(2);

  const updateLine = (i, patch) => setLines(ls => ls.map((l, j) => j === i ? { ...l, ...patch } : l));
  const removeLine = (i) => setLines(ls => ls.filter((_, j) => j !== i));

  const handleIssue = () => {
    const id = ctx.existingInvoiceId || nextInvoiceId();
    setIssuedId(id);
    setStep("print");
  };

  return (
    <div className="scrim" onClick={onClose}>
      <div
        className="receipt-modal"
        onClick={e => e.stopPropagation()}
        data-step={step}
      >
        {step === "review"  && <ReviewStep   ctx={ctx} lines={lines} updateLine={updateLine} removeLine={removeLine}
                                              taxInvoice={taxInvoice} setTaxInvoice={setTaxInvoice}
                                              discount={discount} setDiscount={setDiscount}
                                              note={note} setNote={setNote}
                                              sub={sub} afterDisc={afterDisc} vat={vat} total={total}
                                              onClose={onClose} onNext={() => setStep("confirm")} />}
        {step === "confirm" && <ConfirmStep  ctx={ctx} taxInvoice={taxInvoice}
                                              paymentMethod={paymentMethod} setPaymentMethod={setPaymentMethod}
                                              paidNow={paidNow} setPaidNow={setPaidNow}
                                              total={total}
                                              onBack={() => setStep("review")} onIssue={handleIssue} onClose={onClose} />}
        {step === "print"   && <PrintStep    ctx={ctx} lines={lines}
                                              taxInvoice={taxInvoice} discount={discount}
                                              sub={sub} afterDisc={afterDisc} vat={vat} total={total}
                                              paymentMethod={paymentMethod} paidNow={paidNow}
                                              issuedId={issuedId} note={note}
                                              onClose={onClose} />}
      </div>
    </div>
  );
}

// ---- Step 1: Review lines ----
function ReviewStep({ ctx, lines, updateLine, removeLine, taxInvoice, setTaxInvoice,
                     discount, setDiscount, note, setNote,
                     sub, afterDisc, vat, total, onClose, onNext }) {
  const I = window.I;
  const GS = window.GS;
  return (
    <>
      <div className="rm-head">
        <div>
          <div className="rm-eyebrow">ออกใบเสร็จ · Issue receipt · 1/3</div>
          <div className="rm-title">ตรวจสอบรายการ</div>
        </div>
        <button className="tb-iconbtn" onClick={onClose} aria-label="close"><I.X size={16}/></button>
      </div>

      <div className="rm-body">
        {/* Source summary */}
        <div className="rm-source">
          <div>
            <div className="t-xs mono muted" style={{textTransform:"uppercase",letterSpacing:".08em"}}>อ้างอิง Job</div>
            <div className="code t-strong" style={{fontSize:14}}>{ctx.jobId}</div>
          </div>
          <div>
            <div className="t-xs mono muted" style={{textTransform:"uppercase",letterSpacing:".08em"}}>ลูกค้า</div>
            <div className="thai t-strong" style={{fontSize:14}}>{ctx.customer?.name || "—"}</div>
            <div className="mono t-xs muted">{ctx.customer?.phone}</div>
          </div>
          <div>
            <div className="t-xs mono muted" style={{textTransform:"uppercase",letterSpacing:".08em"}}>รถ</div>
            <div className="row-flex" style={{gap:6}}>
              <span className="mono t-strong">{ctx.vehicle?.plate || "—"}</span>
            </div>
            <div className="thai t-xs muted">{ctx.vehicle?.make} {ctx.vehicle?.model}</div>
          </div>
        </div>

        <table className="tbl rm-tbl">
          <thead><tr>
            <th style={{width:60}}>ประเภท</th>
            <th>รายการ</th>
            <th className="num" style={{width:70}}>จำนวน</th>
            <th className="num" style={{width:110}}>ราคา/หน่วย</th>
            <th className="num" style={{width:110}}>รวม</th>
            <th style={{width:30}}></th>
          </tr></thead>
          <tbody>
            {lines.map((l, i) => (
              <tr key={i}>
                <td><span className="badge badge-outline" style={{padding:"1px 6px",fontSize:9.5}}>{l.type === "svc" ? "งาน" : "อะไหล่"}</span></td>
                <td>
                  <div className="thai t-strong" style={{fontSize:13}}>{l.name}</div>
                  <div className="code t-xs muted">{l.code}</div>
                </td>
                <td className="num">
                  <input className="rm-num" type="number" min={1} value={l.qty}
                         onChange={e => updateLine(i, { qty: Math.max(1, parseInt(e.target.value || "1", 10)) })}/>
                </td>
                <td className="num">
                  <input className="rm-num" type="number" min={0} value={l.price}
                         onChange={e => updateLine(i, { price: Math.max(0, parseFloat(e.target.value || "0")) })}/>
                </td>
                <td className="num mono t-strong">{GS.fmtMoney(l.qty * l.price, true)}</td>
                <td>
                  <button className="tb-iconbtn" onClick={() => removeLine(i)} aria-label="remove">
                    <I.X size={13}/>
                  </button>
                </td>
              </tr>
            ))}
            {lines.length === 0 && (
              <tr><td colSpan={6} style={{textAlign:"center",padding:24,color:"var(--ink-4)",fontFamily:"var(--font-thai)"}}>
                ไม่มีรายการ — เพิ่มจาก Job ก่อนออกใบเสร็จ
              </td></tr>
            )}
          </tbody>
        </table>

        <div className="rm-grid2">
          <div>
            <label className="label">หมายเหตุบนใบเสร็จ</label>
            <textarea rows={3} value={note} onChange={e => setNote(e.target.value)}
                      placeholder="เช่น รับประกันอะไหล่ 6 เดือน / 10,000 กม."
                      style={{width:"100%",resize:"vertical"}}/>
            <label className="rm-check" style={{marginTop:10}}>
              <input type="checkbox" checked={taxInvoice} onChange={e => setTaxInvoice(e.target.checked)}/>
              <span>ออกเป็น <b>ใบกำกับภาษี</b> (เต็มรูป VAT 7%)</span>
            </label>
          </div>
          <div className="rm-totals">
            <div className="row-flex between"><span className="muted">ยอดก่อนหักส่วนลด</span><span className="mono">{GS.fmtMoney(sub)}</span></div>
            <div className="row-flex between" style={{alignItems:"center"}}>
              <span className="muted">ส่วนลด</span>
              <input className="rm-num" type="number" min={0} value={discount}
                     onChange={e => setDiscount(Math.max(0, parseFloat(e.target.value || "0")))}
                     style={{width:120,textAlign:"right"}}/>
            </div>
            <div className="row-flex between"><span className="muted">ยอดสุทธิ</span><span className="mono">{GS.fmtMoney(afterDisc)}</span></div>
            <div className="row-flex between"><span className="muted">VAT 7%</span><span className="mono">{taxInvoice ? GS.fmtMoney(vat) : "—"}</span></div>
            <div className="row-flex between rm-grand">
              <span className="thai t-strong" style={{fontSize:14}}>รวมทั้งสิ้น</span>
              <span className="mono t-strong" style={{fontSize:20}}>{GS.fmtMoney(taxInvoice ? total : afterDisc)}</span>
            </div>
          </div>
        </div>
      </div>

      <div className="rm-foot">
        <div className="rm-steps"><span className="rm-dot active"/><span className="rm-dot"/><span className="rm-dot"/></div>
        <div className="row-flex" style={{gap:8}}>
          <button className="btn btn-default" onClick={onClose}>ยกเลิก</button>
          <button className="btn btn-accent" onClick={onNext} disabled={lines.length === 0}>
            ถัดไป · ยืนยัน <I.Arrow size={14}/>
          </button>
        </div>
      </div>
    </>
  );
}

// ---- Step 2: Confirm payment / before issue ----
function ConfirmStep({ ctx, taxInvoice, paymentMethod, setPaymentMethod, paidNow, setPaidNow,
                      total, onBack, onIssue, onClose }) {
  const I = window.I;
  const GS = window.GS;
  const methods = [
    { id: "cash",     label: "เงินสด",       icon: "Money" },
    { id: "transfer", label: "โอน / QR",     icon: "Receipt" },
    { id: "card",     label: "บัตรเครดิต",   icon: "Receipt" },
    { id: "credit",   label: "ลงเครดิต (วางบิล)", icon: "Calendar" },
  ];

  return (
    <>
      <div className="rm-head">
        <div>
          <div className="rm-eyebrow">ออกใบเสร็จ · Issue receipt · 2/3</div>
          <div className="rm-title">ยืนยันการออกใบเสร็จ</div>
        </div>
        <button className="tb-iconbtn" onClick={onClose} aria-label="close"><I.X size={16}/></button>
      </div>

      <div className="rm-body">
        <div className="rm-confirm-summary">
          <div>
            <div className="t-xs mono muted" style={{textTransform:"uppercase",letterSpacing:".08em",marginBottom:4}}>ลูกค้า</div>
            <div className="thai t-strong" style={{fontSize:15}}>{ctx.customer?.name}</div>
            <div className="mono t-xs muted">{ctx.customer?.phone}</div>
          </div>
          <div>
            <div className="t-xs mono muted" style={{textTransform:"uppercase",letterSpacing:".08em",marginBottom:4}}>ประเภท</div>
            <div className="thai t-strong" style={{fontSize:15}}>{taxInvoice ? "ใบกำกับภาษี (เต็มรูป)" : "ใบเสร็จรับเงิน"}</div>
            <div className="thai t-xs muted">{taxInvoice ? "VAT 7% รวมในยอด" : "ไม่มี VAT"}</div>
          </div>
          <div>
            <div className="t-xs mono muted" style={{textTransform:"uppercase",letterSpacing:".08em",marginBottom:4}}>ยอดที่ต้องชำระ</div>
            <div className="mono t-strong" style={{fontSize:24,color:"var(--accent)"}}>{GS.fmtMoney(total)}</div>
          </div>
        </div>

        <div className="rm-section">
          <div className="rm-section-title">วิธีชำระเงิน</div>
          <div className="rm-method-grid">
            {methods.map(m => {
              const Ic = I[m.icon] || I.Receipt;
              const active = paymentMethod === m.id;
              return (
                <button key={m.id}
                  className={"rm-method" + (active ? " active" : "")}
                  onClick={() => setPaymentMethod(m.id)}>
                  <Ic size={18}/>
                  <span className="thai">{m.label}</span>
                </button>
              );
            })}
          </div>
        </div>

        <div className="rm-section">
          <div className="rm-section-title">สถานะการชำระ</div>
          <div className="rm-radio-row">
            <label className={"rm-radio" + (paidNow ? " active" : "")}>
              <input type="radio" name="paid" checked={paidNow} onChange={() => setPaidNow(true)}/>
              <div>
                <div className="thai t-strong">รับชำระทันที</div>
                <div className="thai t-xs muted">ใบเสร็จออกในสถานะ <b>ชำระแล้ว</b></div>
              </div>
            </label>
            <label className={"rm-radio" + (!paidNow ? " active" : "")}>
              <input type="radio" name="paid" checked={!paidNow} onChange={() => setPaidNow(false)}/>
              <div>
                <div className="thai t-strong">ยังไม่ชำระ (วางบิล)</div>
                <div className="thai t-xs muted">กำหนดชำระภายใน 30 วัน</div>
              </div>
            </label>
          </div>
        </div>

        <div className="rm-warn">
          <I.Info size={14} stroke="var(--warn)"/>
          <span className="thai">เมื่อกดออกใบเสร็จแล้วจะไม่สามารถแก้ไขรายการได้ — ต้องออกใบลด/ใบยกเลิกแทน</span>
        </div>
      </div>

      <div className="rm-foot">
        <div className="rm-steps"><span className="rm-dot done"/><span className="rm-dot active"/><span className="rm-dot"/></div>
        <div className="row-flex" style={{gap:8}}>
          <button className="btn btn-default" onClick={onBack}><I.ChevronL size={14}/> ย้อนกลับ</button>
          <button className="btn btn-accent" onClick={onIssue}>
            <I.Check size={14}/> ออกใบเสร็จ {GS.fmtMoney(total, true)}
          </button>
        </div>
      </div>
    </>
  );
}

// ---- Step 3: Print preview ----
function PrintStep({ ctx, lines, taxInvoice, discount, sub, afterDisc, vat, total,
                    paymentMethod, paidNow, issuedId, note, onClose }) {
  const I = window.I;
  const GS = window.GS;
  const printRef = uRxR(null);
  const [copied, setCopied] = uRxS(false);

  const methodLabel = ({
    cash: "เงินสด", transfer: "โอน / QR", card: "บัตรเครดิต", credit: "ลงเครดิต (วางบิล)"
  })[paymentMethod] || paymentMethod;

  const handlePrint = () => {
    document.body.classList.add("printing-receipt");
    requestAnimationFrame(() => {
      window.print();
      setTimeout(() => document.body.classList.remove("printing-receipt"), 600);
    });
  };

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(`${issuedId} · ${ctx.customer?.name} · ${GS.fmtMoney(total)}`);
      setCopied(true); setTimeout(() => setCopied(false), 1500);
    } catch {}
  };

  return (
    <>
      <div className="rm-head">
        <div>
          <div className="rm-eyebrow" style={{color:"var(--ok)"}}>
            <I.Check size={11} stroke="var(--ok)"/> ออกใบเสร็จเรียบร้อย · 3/3
          </div>
          <div className="rm-title row-flex" style={{gap:10}}>
            <span>{issuedId}</span>
            <span className={"badge " + (paidNow ? "badge-ok" : "badge-warn")}>
              <span className="badge-dot"/>{paidNow ? "ชำระแล้ว" : "คงค้าง"}
            </span>
          </div>
        </div>
        <button className="tb-iconbtn" onClick={onClose} aria-label="close"><I.X size={16}/></button>
      </div>

      <div className="rm-body rm-print-body">
        <div className="rm-print-actions">
          <button className="btn btn-default btn-sm" onClick={handlePrint}><I.Print size={13}/> พิมพ์</button>
          <button className="btn btn-default btn-sm"><I.Download size={13}/> PDF</button>
          <button className="btn btn-default btn-sm"><I.Send size={13}/> ส่ง LINE</button>
          <button className="btn btn-default btn-sm"><I.Mail size={13}/> ส่งอีเมล</button>
          <button className="btn btn-default btn-sm" onClick={handleCopy}>
            <I.Copy size={13}/> {copied ? "คัดลอกแล้ว" : "คัดลอกเลขที่"}
          </button>
        </div>

        <div className="rm-receipt" ref={printRef} id="printable-receipt">
          <ReceiptPaper
            issuedId={issuedId}
            ctx={ctx}
            lines={lines}
            taxInvoice={taxInvoice}
            discount={discount}
            sub={sub} afterDisc={afterDisc} vat={vat} total={total}
            methodLabel={methodLabel}
            paidNow={paidNow}
            note={note}
          />
        </div>
      </div>

      <div className="rm-foot">
        <div className="rm-steps"><span className="rm-dot done"/><span className="rm-dot done"/><span className="rm-dot active"/></div>
        <div className="row-flex" style={{gap:8}}>
          <button className="btn btn-default" onClick={onClose}>ปิด</button>
          <button className="btn btn-accent" onClick={handlePrint}><I.Print size={14}/> พิมพ์ใบเสร็จ</button>
        </div>
      </div>
    </>
  );
}

// ---- The actual receipt paper (also styled for @print) ----
function ReceiptPaper({ issuedId, ctx, lines, taxInvoice, discount, sub, afterDisc, vat, total, methodLabel, paidNow, note }) {
  const GS = window.GS;
  const today = "26 เม.ย. 2569";
  const due   = "26 พ.ค. 2569";
  return (
    <div className="paper">
      <div className="paper-head">
        <div>
          <div className="paper-brand">นายอะไหล่ยนต์</div>
          <div className="paper-sub">อู่ซ่อมรถ · ขายอะไหล่ยนต์</div>
          <div className="paper-addr">
            123/45 ถนนพระราม 9 แขวงห้วยขวาง เขตห้วยขวาง กรุงเทพฯ 10310<br/>
            โทร 02-123-4567 · เลขประจำตัวผู้เสียภาษี 0-1055-12345-67-8 · สำนักงานใหญ่
          </div>
        </div>
        <div className="paper-meta">
          <div className="paper-doctype">{taxInvoice ? "ใบกำกับภาษี / ใบเสร็จรับเงิน" : "ใบเสร็จรับเงิน"}</div>
          <div className="paper-doctype-en">{taxInvoice ? "TAX INVOICE / RECEIPT" : "RECEIPT"}</div>
          <table className="paper-meta-tbl">
            <tbody>
              <tr><td>เลขที่</td><td className="mono t-strong">{issuedId}</td></tr>
              <tr><td>วันที่</td><td className="mono">{today}</td></tr>
              <tr><td>อ้างอิง Job</td><td className="mono muted">{ctx.jobId}</td></tr>
              <tr><td>ครบกำหนด</td><td className="mono muted">{paidNow ? "—" : due}</td></tr>
            </tbody>
          </table>
        </div>
      </div>

      <div className="paper-parties">
        <div>
          <div className="paper-label">ลูกค้า / Bill to</div>
          <div className="paper-name">{ctx.customer?.name}</div>
          <div className="paper-line">{ctx.customer?.phone} · {ctx.customer?.email || "—"}</div>
          <div className="paper-line muted">{ctx.customer?.taxId ? `เลขผู้เสียภาษี ${ctx.customer.taxId}` : "ลูกค้าทั่วไป"}</div>
        </div>
        <div>
          <div className="paper-label">รถ / Vehicle</div>
          <div className="paper-name mono">{ctx.vehicle?.plate}</div>
          <div className="paper-line">{ctx.vehicle?.make} {ctx.vehicle?.model} · {ctx.vehicle?.year}</div>
          <div className="paper-line muted">เลขไมล์ {GS.fmtInt(ctx.vehicle?.mileage || 0)} กม.</div>
        </div>
      </div>

      <table className="paper-tbl">
        <thead><tr>
          <th style={{width:30}}>#</th>
          <th>รายการ / Description</th>
          <th className="num" style={{width:50}}>จำนวน</th>
          <th className="num" style={{width:90}}>หน่วยละ</th>
          <th className="num" style={{width:100}}>รวม</th>
        </tr></thead>
        <tbody>
          {lines.map((l, i) => (
            <tr key={i}>
              <td className="mono muted">{i + 1}</td>
              <td>
                <div className="thai t-strong">{l.name}</div>
                <div className="paper-code">[{l.type === "svc" ? "งาน" : "อะไหล่"}] {l.code}</div>
              </td>
              <td className="num mono">{l.qty}</td>
              <td className="num mono">{GS.fmtMoney(l.price, true)}</td>
              <td className="num mono t-strong">{GS.fmtMoney(l.qty * l.price, true)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div className="paper-totals-row">
        <div className="paper-words">
          <div className="paper-label">จำนวนเงินตัวอักษร</div>
          <div className="thai t-strong" style={{fontSize:13}}>
            ({thaiBaht(taxInvoice ? total : afterDisc)})
          </div>
          {note && (
            <>
              <div className="paper-label" style={{marginTop:10}}>หมายเหตุ</div>
              <div className="thai" style={{fontSize:11,whiteSpace:"pre-wrap"}}>{note}</div>
            </>
          )}
        </div>
        <table className="paper-totals">
          <tbody>
            <tr><td>ยอดรวม</td><td className="num mono">{GS.fmtMoney(sub)}</td></tr>
            {discount > 0 && <tr><td>ส่วนลด</td><td className="num mono">-{GS.fmtMoney(discount)}</td></tr>}
            <tr><td>ยอดสุทธิก่อนภาษี</td><td className="num mono">{GS.fmtMoney(afterDisc)}</td></tr>
            <tr><td>VAT 7%</td><td className="num mono">{taxInvoice ? GS.fmtMoney(vat) : "—"}</td></tr>
            <tr className="grand"><td>รวมทั้งสิ้น</td><td className="num mono">{GS.fmtMoney(taxInvoice ? total : afterDisc)}</td></tr>
          </tbody>
        </table>
      </div>

      <div className="paper-pay">
        <div>
          <div className="paper-label">วิธีชำระเงิน</div>
          <div className="thai t-strong">{methodLabel}</div>
          <div className="paper-line muted">{paidNow ? `รับเงินแล้ว ${today}` : `กำหนดชำระภายใน ${due}`}</div>
        </div>
        <div className={"paper-stamp " + (paidNow ? "stamp-paid" : "stamp-pending")}>
          {paidNow ? "PAID" : "UNPAID"}
        </div>
      </div>

      <div className="paper-sigs">
        <div className="paper-sig">
          <div className="sig-line"></div>
          <div className="thai">ผู้รับเงิน · Cashier</div>
          <div className="paper-line muted">ลุงวุ้น</div>
        </div>
        <div className="paper-sig">
          <div className="sig-line"></div>
          <div className="thai">ผู้รับใบเสร็จ · Customer</div>
          <div className="paper-line muted">{ctx.customer?.name}</div>
        </div>
      </div>

      <div className="paper-foot">
        ขอบคุณที่ใช้บริการ — ใบเสร็จนี้ออกโดยระบบ นายอะไหล่ยนต์ {issuedId} · พิมพ์ {today}
      </div>
    </div>
  );
}

// ---- Tiny Thai-baht-words helper (good enough for receipts) ----
function thaiBaht(amount) {
  const num = Math.round((amount || 0) * 100) / 100;
  const baht = Math.floor(num);
  const satang = Math.round((num - baht) * 100);
  const digits = ["ศูนย์","หนึ่ง","สอง","สาม","สี่","ห้า","หก","เจ็ด","แปด","เก้า"];
  const positions = ["","สิบ","ร้อย","พัน","หมื่น","แสน","ล้าน"];
  function read(n) {
    if (n === 0) return "";
    const s = String(n);
    let out = "";
    for (let i = 0; i < s.length; i++) {
      const d = parseInt(s[i], 10);
      const pos = s.length - 1 - i;
      if (d === 0) continue;
      if (pos === 0 && d === 1 && s.length > 1) out += "เอ็ด";
      else if (pos === 1 && d === 2) out += "ยี่";
      else if (pos === 1 && d === 1) out += "";
      else out += digits[d];
      out += positions[pos] || "";
    }
    return out;
  }
  let result = "";
  if (baht === 0 && satang === 0) result = "ศูนย์บาทถ้วน";
  else {
    if (baht > 0) result += read(baht) + "บาท";
    if (satang > 0) result += read(satang) + "สตางค์";
    else result += "ถ้วน";
  }
  return result;
}

window.ReceiptFlow = { ReceiptModal, defaultLinesForJob };
