/* Kay Construction — printable PDF document views (kop + body + footer + signatures).
   Renders in the document's own language (id/en). Full-screen, no app chrome. */

function L(lang, id, en) { return lang === "en" ? en : id; }

/* normalize an Indonesian phone to wa.me format (digits, 0 → 62) */
function waNumber(phone) {
  if (!phone) return "";
  let d = String(phone).replace(/[^0-9]/g, "");
  if (d.indexOf("0") === 0) d = "62" + d.slice(1);
  else if (d.indexOf("62") !== 0 && d.length) d = "62" + d;
  return d;
}
function sendWhatsApp(doc, type, co, lang, client, project) {
  const tt = doc.amount != null ? { total: doc.amount } : S.docTotals(doc);
  const titleMap = {
    penawaran: L(lang, "Penawaran Harga", "Quotation"),
    invoice: L(lang, "Invoice", "Invoice"),
    spk: L(lang, "Surat Perintah Kerja", "Work Order"),
    kwitansi: L(lang, "Kwitansi", "Receipt"),
    rab: L(lang, "RAB", "Bill of Quantities"),
    "tambah-kurang": L(lang, "Pekerjaan Tambah-Kurang", "Variation Order")
  };
  const hi = L(lang, "Halo", "Hello");
  const who = client ? " " + (client.contactPerson || client.name) : "";
  const lines = [];
  lines.push(hi + who + ",");
  lines.push("");
  lines.push(L(lang, "Berikut kami sampaikan ", "Please find our ") + titleMap[type] + " *" + (doc.number || "") + "*" + (project ? (L(lang, " untuk proyek ", " for project ") + project.name) : "") + ".");
  if (type === "invoice" || type === "penawaran") {
    lines.push("");
    lines.push(L(lang, "Total", "Total") + ": *" + S.formatRupiah(tt.total) + "*");
    if (type === "invoice" && doc.dueDate) lines.push(L(lang, "Jatuh tempo", "Due") + ": " + S.formatDate(doc.dueDate, lang));
    if (type === "invoice" && co.bankName) lines.push(L(lang, "Pembayaran ke", "Pay to") + ": " + co.bankName + " " + (co.bankAccount || "") + " a.n. " + (co.bankHolder || ""));
  } else if (type === "kwitansi") {
    lines.push("");
    lines.push(L(lang, "Jumlah", "Amount") + ": *" + S.formatRupiah(doc.amount) + "*");
  }
  lines.push("");
  lines.push(L(lang, "Dokumen PDF kami lampirkan. Terima kasih.", "The PDF document is attached. Thank you."));
  lines.push((co.name || "Kay Construction") + (co.ownerName ? " — " + co.ownerName : ""));
  const num = waNumber(client && client.phone);
  const url = "https://wa.me/" + num + "?text=" + encodeURIComponent(lines.join("\n"));
  if (!num && !confirm(L(lang, "Nomor WhatsApp klien belum diisi. Buka WhatsApp tanpa nomor?", "Client WhatsApp number is empty. Open WhatsApp without a number?"))) return;
  window.open(url, "_blank");
}

function downloadDocPdf(doc, type, setBusy) {
  const el = document.querySelector(".paper");
  const fname = ((doc.number || type) + "").replace(/[\/\\:]/g, "-") + ".pdf";
  if (!window.html2pdf || !el) { window.print(); return; }
  setBusy && setBusy(true);
  el.classList.add("pdf-capturing");
  window.html2pdf().set({
    margin: 0,
    filename: fname,
    image: { type: "jpeg", quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true, backgroundColor: "#ffffff", logging: false },
    jsPDF: { unit: "mm", format: "a4", orientation: "portrait" }
  }).from(el).save().then(function () {
    el.classList.remove("pdf-capturing"); setBusy && setBusy(false);
  }).catch(function () {
    el.classList.remove("pdf-capturing"); setBusy && setBusy(false); window.print();
  });
}

function Kop({ co }) {
  return (
    <div className="kop">
      <img src={co.logo || "assets/kay-logo.png"} alt="" />
      <div style={{ flex: 1 }}>
        <div className="co-name">{co.name || "KAY CONSTRUCTION"}</div>
        <div className="co-legal">{co.legalName || ""}{co.tagline ? " — " + co.tagline : ""}</div>
        <div className="co-meta">
          {co.address}{co.city ? ", " + co.city : ""}<br />
          {co.phone}{co.email ? " · " + co.email : ""}{co.website ? " · " + co.website : ""}
          {co.npwp ? <span><br />NPWP: {co.npwp}</span> : null}
        </div>
      </div>
    </div>
  );
}

function DocFoot({ co, lang }) {
  return (
    <div className="doc-foot">
      <div>{co.legalName || co.name}{co.npwp ? " · NPWP " + co.npwp : ""}</div>
      <div>{co.website || "app.kayconstruction.id"}</div>
    </div>
  );
}

function SignBlock({ lang, leftLabel, leftCompany, leftName, rightLabel, rightName, place, date, sign, stamp }) {
  return (
    <div>
      {place && <div style={{ textAlign: "right", marginTop: 24, fontSize: 11 }}>{place}, {date}</div>}
      <div className="sign-row">
        <div className="sign">
          <div>{leftLabel}</div>
          {leftCompany && <div style={{ fontWeight: 600, marginTop: 2 }}>{leftCompany}</div>}
          <div className="ttd">
            {stamp && <img className="stamp-img" src={stamp} alt="" />}
            {sign && <img className="sign-img" src={sign} alt="" />}
          </div>
          <div className="name">{leftName}</div>
        </div>
        {rightLabel && <div className="sign">
          <div>{rightLabel}</div>
          <div className="ttd"></div>
          <div className="name">{rightName}</div>
        </div>}
      </div>
    </div>
  );
}

function ItemsTable({ items, lang, grouped }) {
  // optionally group rows by category
  let rows = [];
  if (grouped) {
    const cats = [];
    items.forEach((it) => { const c = it.category || "—"; if (!cats.includes(c)) cats.push(c); });
    cats.forEach((c) => {
      rows.push({ cat: c });
      items.filter((it) => (it.category || "—") === c).forEach((it) => rows.push({ it }));
    });
  } else { rows = items.map((it) => ({ it })); }
  let n = 0;
  return (
    <table className="doc-tbl">
      <thead><tr>
        <th style={{ width: 28 }}>No</th>
        <th>{L(lang, "Uraian Pekerjaan", "Description")}</th>
        <th className="r" style={{ width: 55 }}>{L(lang, "Vol", "Qty")}</th>
        <th style={{ width: 50 }}>{L(lang, "Sat", "Unit")}</th>
        <th className="r" style={{ width: 110 }}>{L(lang, "Harga Satuan", "Unit Price")}</th>
        <th className="r" style={{ width: 120 }}>{L(lang, "Jumlah", "Amount")}</th>
      </tr></thead>
      <tbody>
        {rows.map((r, i) => r.cat !== undefined ? (
          <tr className="cat-row" key={"c" + i}><td></td><td colSpan="5">{r.cat}</td></tr>
        ) : (
          <tr key={r.it.id}>
            <td>{++n}</td>
            <td>{r.it.description}</td>
            <td className="r tnum">{S.formatNumber(r.it.volume)}</td>
            <td>{r.it.unit}</td>
            <td className="r tnum">{S.formatNumber(r.it.unitPrice)}</td>
            <td className="r tnum">{S.formatNumber((Number(r.it.volume) || 0) * (Number(r.it.unitPrice) || 0))}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function Totals({ doc, lang }) {
  const tt = S.docTotals(doc);
  return (
    <div className="totals">
      <div className="line"><span>{L(lang, "Subtotal", "Subtotal")}</span><span className="tnum">{S.formatRupiah(tt.subtotal)}</span></div>
      {tt.discount > 0 && <div className="line"><span>{L(lang, "Diskon", "Discount")}</span><span className="tnum">−{S.formatRupiah(tt.discount)}</span></div>}
      <div className="line"><span>{L(lang, "PPN", "VAT")} {tt.ppnPercent}%</span><span className="tnum">{S.formatRupiah(tt.ppnAmount)}</span></div>
      <div className="line grand"><span>{L(lang, "Total", "Total")}</span><span className="tnum">{S.formatRupiah(tt.total)}</span></div>
    </div>
  );
}

function Parties({ blocks }) {
  return (
    <div className="parties">
      {blocks.map((b, i) => (
        <div key={i} style={{ flex: 1 }}>
          <div className="lbl">{b.label}</div>
          <div className="v">{b.value}</div>
          {b.sub && <div style={{ fontSize: 10.5, color: "#555" }}>{b.sub}</div>}
        </div>
      ))}
    </div>
  );
}

/* ---------------- main print router ---------------- */
function PrintDoc({ type, id }) {
  useStore();
  const [busy, setBusy] = useState(false);
  const co = S.getDB().company || {};
  const collMap = { rab: "rab", penawaran: "quotations", "tambah-kurang": "addenda", spk: "workOrders", invoice: "invoices", kwitansi: "payments" };
  const backMap = { rab: "#/dokumen/rab/", penawaran: "#/dokumen/penawaran/", "tambah-kurang": "#/dokumen/tambah-kurang/", spk: "#/dokumen/spk/", invoice: "#/dokumen/invoice/", kwitansi: "#/dokumen/kwitansi/" };
  const doc = S.find(collMap[type], id);
  if (!doc) return <div className="print-screen"><div className="paper">Document not found. <a href="#/dashboard">Dashboard</a></div></div>;
  const lang = doc.language || "id";
  const project = doc.projectId ? S.find("projects", doc.projectId) : null;
  const client = project ? S.find("clients", project.clientId) : null;
  const place = co.city ? co.city.split(",")[0] : "Bali";

  return (
    <div className="print-screen">
      <div className="print-toolbar no-print">
        <Button variant="ghost" icon="back" onClick={() => go(backMap[type] + id)}>{t("common.back")}</Button>
        <div className="row" style={{ gap: 12 }}>
          <Badge tone="neutral">{lang.toUpperCase()}</Badge>
          {(type === "penawaran" || type === "invoice" || type === "spk" || type === "kwitansi" || type === "tambah-kurang") &&
            <Button icon="arrow" onClick={() => sendWhatsApp(doc, type, co, lang, client, project)} title={t("wa.hint")}>{t("wa.send")}</Button>}
          <Button icon="print" onClick={() => window.print()}>{L(lang, "Cetak", "Print")}</Button>
          <Button variant="primary" icon="download" disabled={busy} onClick={() => downloadDocPdf(doc, type, setBusy)}>
            {busy ? L(lang, "Menyiapkan…", "Preparing…") : L(lang, "Unduh PDF", "Download PDF")}
          </Button>
        </div>
      </div>
      <div className="paper print-doc">
        <Kop co={co} />
        {co.headerImage && <img className="header-band" src={co.headerImage} alt="" />}
        {type === "rab" && <RabPaper doc={doc} co={co} lang={lang} project={project} place={place} />}
        {type === "penawaran" && <QuoPaper doc={doc} co={co} lang={lang} project={project} client={client} place={place} />}
        {type === "tambah-kurang" && <AddendumPaper doc={doc} co={co} lang={lang} project={project} client={client} place={place} />}
        {type === "spk" && <SpkPaper doc={doc} co={co} lang={lang} project={project} place={place} />}
        {type === "invoice" && <InvPaper doc={doc} co={co} lang={lang} project={project} client={client} place={place} />}
        {type === "kwitansi" && <KwitPaper doc={doc} co={co} lang={lang} project={project} place={place} />}
        <DocFoot co={co} lang={lang} />
      </div>
    </div>
  );
}

function RabPaper({ doc, co, lang, project, place }) {
  return (
    <div>
      <div className="doc-title">{L(lang, "Rencana Anggaran Biaya", "Bill of Quantities")}</div>
      <div className="doc-no">{doc.number} · {doc.version || ""}</div>
      <Parties blocks={[
        { label: L(lang, "Proyek", "Project"), value: project ? project.name : "—", sub: project ? project.code : "" },
        { label: L(lang, "Tanggal", "Date"), value: S.formatDate(doc.date, lang) },
        { label: L(lang, "Status", "Status"), value: tStatus(doc.status) }
      ]} />
      {doc.title && <div style={{ fontWeight: 600, marginBottom: 6 }}>{doc.title}</div>}
      <ItemsTable items={doc.items || []} lang={lang} grouped />
      <Totals doc={doc} lang={lang} />
      {doc.note && <div className="note-block"><strong>{L(lang, "Catatan", "Notes")}:</strong> {doc.note}</div>}
      <SignBlock lang={lang} place={place} date={S.formatDate(doc.date, lang)}
        leftLabel={L(lang, "Disusun oleh,", "Prepared by,")} leftCompany={co.name || "Kay Construction"} leftName={co.ownerName || co.name || "Ketut Adi Yoga"} sign={co.signature} stamp={co.stamp} />
    </div>
  );
}

function QuoPaper({ doc, co, lang, project, client, place }) {
  const terms = lang === "en" ? co.paymentTermsEn : co.paymentTermsId;
  return (
    <div>
      <div className="doc-title">{L(lang, "Surat Penawaran Harga", "Quotation")}</div>
      <div className="doc-no">{doc.number}</div>
      <Parties blocks={[
        { label: L(lang, "Kepada Yth.", "To"), value: client ? client.name : "—", sub: client ? (client.address || "") : "" },
        { label: L(lang, "Proyek", "Project"), value: project ? project.name : "—", sub: project ? project.code : "" },
        { label: L(lang, "Berlaku s/d", "Valid until"), value: S.formatDate(doc.validUntil, lang) }
      ]} />
      <p style={{ fontSize: 11 }}>{L(lang, "Dengan hormat, bersama ini kami sampaikan penawaran harga untuk pekerjaan berikut:", "We are pleased to submit our quotation for the following works:")}</p>
      <ItemsTable items={doc.items || []} lang={lang} grouped />
      <Totals doc={doc} lang={lang} />
      <div className="terbilang-box">{L(lang, "Terbilang", "In words")}: {S.terbilang(S.docTotals(doc).total, lang)}</div>
      {(doc.paymentTerms || terms) && <div className="note-block"><strong>{L(lang, "Syarat Pembayaran", "Payment Terms")}:</strong> {doc.paymentTerms || terms}</div>}
      {doc.note && <div className="note-block">{doc.note}</div>}
      <SignBlock lang={lang} place={place} date={S.formatDate(doc.date, lang)}
        leftLabel={L(lang, "Hormat kami,", "Sincerely,")} leftCompany={co.name || "Kay Construction"} leftName={co.ownerName || co.name || "Ketut Adi Yoga"} sign={co.signature} stamp={co.stamp} />
    </div>
  );
}

function SpkPaper({ doc, co, lang, project, place }) {
  return (
    <div>
      <div className="doc-title">{L(lang, "Surat Perintah Kerja", "Work Order")}</div>
      <div className="doc-no">{doc.number}</div>
      <Parties blocks={[
        { label: L(lang, "Proyek", "Project"), value: project ? project.name : "—", sub: project ? project.code : "" },
        { label: L(lang, "Tanggal", "Date"), value: S.formatDate(doc.date, lang) },
        { label: L(lang, "Nilai Pekerjaan", "Work Value"), value: S.formatRupiah(doc.value) }
      ]} />
      <div style={{ fontWeight: 600, margin: "10px 0 4px" }}>{doc.title}</div>
      <div className="note-block"><strong>{L(lang, "Lingkup Pekerjaan", "Scope of Work")}:</strong><br />{doc.scope}</div>
      <div className="parties" style={{ marginTop: 10 }}>
        <div><div className="lbl">{L(lang, "Mulai", "Start")}</div><div className="v">{S.formatDate(doc.startDate, lang)}</div></div>
        <div><div className="lbl">{L(lang, "Selesai", "End")}</div><div className="v">{S.formatDate(doc.endDate, lang)}</div></div>
        <div><div className="lbl">{L(lang, "Status", "Status")}</div><div className="v">{tStatus(doc.status)}</div></div>
      </div>
      {doc.note && <div className="note-block">{doc.note}</div>}
      <SignBlock lang={lang} place={place} date={S.formatDate(doc.date, lang)}
        leftLabel={L(lang, "Yang Memerintahkan,", "Issued by,")} leftCompany={co.name || "Kay Construction"} leftName={co.ownerName || co.name || "Ketut Adi Yoga"} sign={co.signature} stamp={co.stamp}
        rightLabel={L(lang, "Yang Menerima,", "Acknowledged by,")} rightName={"(........................)"} />
    </div>
  );
}

function InvPaper({ doc, co, lang, project, client, place }) {
  const tt = S.docTotals(doc);
  const overdue = doc.dueDate && S.daysBetween(doc.dueDate, S.todayISO()) > 0;
  return (
    <div>
      <div className="doc-title">{L(lang, "Invoice", "Invoice")}</div>
      <div className="doc-no">{doc.number}</div>
      <Parties blocks={[
        { label: L(lang, "Ditagihkan kepada", "Bill to"), value: client ? client.name : "—", sub: client ? (client.address || "") : "" },
        { label: L(lang, "Proyek", "Project"), value: project ? project.name : "—", sub: project ? project.code : "" },
        { label: L(lang, "Terbit / Jatuh Tempo", "Issued / Due"), value: S.formatDate(doc.issueDate, lang), sub: L(lang, "J.T. ", "Due ") + S.formatDate(doc.dueDate, lang) }
      ]} />
      <table className="doc-tbl">
        <thead><tr><th>{L(lang, "Deskripsi", "Description")}</th><th className="r" style={{ width: 140 }}>{L(lang, "Jumlah", "Amount")}</th></tr></thead>
        <tbody>
          <tr><td><strong>{L(lang, "Termin", "Term")} {doc.terminNo} — {doc.terminDesc}</strong><br /><span style={{ fontSize: 10, color: "#666" }}>{project ? project.name : ""}</span></td>
          <td className="r tnum">{S.formatRupiah(tt.subtotal)}</td></tr>
        </tbody>
      </table>
      <Totals doc={doc} lang={lang} />
      <div className="terbilang-box">{L(lang, "Terbilang", "In words")}: {S.terbilang(tt.total, lang)}</div>
      <div className="bank-box">
        <strong>{L(lang, "Pembayaran ditransfer ke", "Please remit payment to")}:</strong><br />
        {co.bankName} — {co.bankAccount}<br />a.n. {co.bankHolder}
      </div>
      {doc.note && <div className="note-block">{doc.note}</div>}
      <div className="note-block" style={{ fontSize: 9.5, color: "#777" }}>{L(lang, "Catatan: nomor invoice ini adalah penomoran internal, bukan Nomor Seri Faktur Pajak.", "Note: this invoice number is an internal reference, not an official tax invoice serial number.")}</div>
      <SignBlock lang={lang} place={place} date={S.formatDate(doc.issueDate, lang)}
        leftLabel={L(lang, "Hormat kami,", "Sincerely,")} leftCompany={co.name || "Kay Construction"} leftName={co.ownerName || co.name || "Ketut Adi Yoga"} sign={co.signature} stamp={co.stamp} />
    </div>
  );
}

function KwitPaper({ doc, co, lang, project, place }) {
  return (
    <div>
      <div className="doc-title">{L(lang, "Kwitansi", "Receipt")}</div>
      <div className="doc-no">{doc.number}</div>
      <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 14, fontSize: 12.5 }}>
        <div style={{ display: "flex", gap: 12 }}>
          <div style={{ width: 150, color: "#666" }}>{L(lang, "Telah terima dari", "Received from")}</div>
          <div style={{ flex: 1, fontWeight: 600, borderBottom: "1px dotted #999" }}>{doc.receivedFrom}</div>
        </div>
        <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
          <div style={{ width: 150, color: "#666" }}>{L(lang, "Uang sejumlah", "The sum of")}</div>
          <div style={{ flex: 1 }}><div className="terbilang-box" style={{ margin: 0 }}>{S.terbilang(doc.amount, lang)}</div></div>
        </div>
        <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
          <div style={{ width: 150, color: "#666" }}>{L(lang, "Untuk pembayaran", "For payment of")}</div>
          <div style={{ flex: 1, borderBottom: "1px dotted #999", paddingBottom: 4 }}>{doc.forPayment}</div>
        </div>
        <div style={{ display: "flex", gap: 12 }}>
          <div style={{ width: 150, color: "#666" }}>{L(lang, "Metode", "Method")}</div>
          <div style={{ flex: 1 }}>{t("method." + doc.method)}{doc.bank ? " · " + doc.bank : ""}</div>
        </div>
      </div>
      <div className="sign-row" style={{ alignItems: "flex-end" }}>
        <div className="kwit-amount">{S.formatRupiah(doc.amount)}</div>
        <div className="sign">
          <div style={{ marginBottom: 2 }}>{place}, {S.formatDate(doc.date, lang)}</div>
          <div style={{ fontWeight: 600 }}>{co.name || "Kay Construction"}</div>
          <div className="ttd">
            {co.stamp && <img className="stamp-img" src={co.stamp} alt="" />}
            {co.signature && <img className="sign-img" src={co.signature} alt="" />}
          </div>
          <div className="name">{co.ownerName || co.name || "Ketut Adi Yoga"}</div>
        </div>
      </div>
    </div>
  );
}

function AddendumPaper({ doc, co, lang, project, client, place }) {
  const signed = Number(doc.amount) || 0;
  const approved = doc.status === "disetujui";
  const currentEff = project ? S.effectiveContract(project.id) : 0;
  const initial = approved ? currentEff - signed : currentEff;
  const finalVal = approved ? currentEff : currentEff + signed;
  const isKurang = doc.type === "kurang";
  const items = doc.useItems ? (doc.items || []) : [];
  return (
    <div>
      <div className="doc-title">{L(lang, "Pekerjaan Tambah / Kurang", "Variation Order")}</div>
      <div className="doc-no">{doc.number}</div>
      <Parties blocks={[
        { label: L(lang, "Kepada Yth.", "To"), value: client ? client.name : "—", sub: client ? (client.address || "") : "" },
        { label: L(lang, "Proyek", "Project"), value: project ? project.name : "—", sub: project ? project.code : "" },
        { label: L(lang, "Tanggal", "Date"), value: S.formatDate(doc.date, lang), sub: isKurang ? L(lang, "Pekerjaan Kurang", "Deduction") : L(lang, "Pekerjaan Tambah", "Addition") }
      ]} />
      {doc.title && <div style={{ fontWeight: 600, margin: "10px 0 4px" }}>{doc.title}</div>}
      {doc.reason && <div className="note-block"><strong>{L(lang, "Alasan / Permintaan", "Reason / Request")}:</strong> {doc.reason}</div>}
      {items.length > 0 && <ItemsTable items={items} lang={lang} grouped />}
      <div className="totals" style={{ width: "72%", marginTop: 14 }}>
        <div className="line"><span style={{ whiteSpace: "nowrap", paddingRight: 20 }}>{L(lang, "Nilai Kontrak Awal", "Original Contract")}</span><span className="tnum">{S.formatRupiah(initial)}</span></div>
        <div className="line"><span style={{ whiteSpace: "nowrap", paddingRight: 20 }}>{isKurang ? L(lang, "Pekerjaan Kurang", "Deduction") : L(lang, "Pekerjaan Tambah", "Addition")}</span><span className="tnum">{signed < 0 ? "−" : "+"}{S.formatRupiah(Math.abs(signed))}</span></div>
        <div className="line grand"><span style={{ whiteSpace: "nowrap", paddingRight: 20 }}>{L(lang, "Nilai Kontrak Akhir", "Revised Contract")}</span><span className="tnum" style={{ whiteSpace: "nowrap" }}>{S.formatRupiah(finalVal)}</span></div>
      </div>
      <div className="terbilang-box">{L(lang, "Terbilang nilai perubahan", "Change amount in words")}: {S.terbilang(Math.abs(signed), lang)}</div>
      {doc.note && <div className="note-block">{doc.note}</div>}
      <SignBlock lang={lang} place={place} date={S.formatDate(doc.date, lang)}
        leftLabel={L(lang, "Disetujui oleh Kontraktor,", "Approved by Contractor,")} leftCompany={co.name || "Kay Construction"} leftName={co.ownerName || co.name || "Ketut Adi Yoga"} sign={co.signature} stamp={co.stamp}
        rightLabel={L(lang, "Disetujui oleh Klien,", "Approved by Client,")} rightName={client ? client.name : "(........................)"} />
    </div>
  );
}

Object.assign(window, { PrintDoc });