/* NGIPL PLM Print & export view (A4 price list in brand style) */
const { useState, useEffect, useMemo } = React;

/* ---- direct PDF export (no browser print dialog) ---- */
const PDF_LIBS = [
  { global: "html2canvas", src: "https://unpkg.com/html2canvas@1.4.1/dist/html2canvas.min.js" },
  { global: "jspdf", src: "https://unpkg.com/jspdf@2.5.1/dist/jspdf.umd.min.js" },
];
let pdfLibsPromise = null;
function loadPdfLibs() {
  if (pdfLibsPromise) return pdfLibsPromise;
  pdfLibsPromise = Promise.all(PDF_LIBS.map((lib) => new Promise((resolve, reject) => {
    if (window[lib.global]) return resolve();
    const s = document.createElement("script");
    s.src = lib.src;
    s.onload = () => resolve();
    s.onerror = () => reject(new Error("Could not load " + lib.src));
    document.head.appendChild(s);
  })));
  pdfLibsPromise.catch(() => { pdfLibsPromise = null; }); /* let a failed load be retried */
  return pdfLibsPromise;
}

/* Renders the sheet to a paginated A4 PDF: rows never cut, fixed 9mm/8mm margins, zero bleed. */
async function sheetToPdf(sheetEl, filename, stopsSelector) {
  await loadPdfLibs();
  const wrap = document.createElement("div");
  wrap.style.cssText = "position:fixed;left:-10000px;top:0;width:794px;background:#ffffff;";
  const clone = sheetEl.cloneNode(true);
  clone.style.transform = "none";
  wrap.appendChild(clone);
  document.body.appendChild(wrap);
  try {
    if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} }
    const canvas = await window.html2canvas(clone, { scale: 2, useCORS: true, backgroundColor: "#ffffff", logging: false });
    const sheetRect = clone.getBoundingClientRect();
    const sheetTop = sheetRect.top;
    const totalH = clone.offsetHeight;
    /* invisible text layer, makes the PDF searchable/selectable */
    const texts = [];
    clone.querySelectorAll("th, td, .sheet-title, .sheet-wef, .sheet-for, .co-block > div, .fnote, .fmark").forEach((el) => {
      const t = (el.innerText || "").trim().replace(/\s+/g, " ");
      if (!t) return;
      const r = el.getBoundingClientRect();
      texts.push({ t, x: r.left - sheetRect.left, y: r.top - sheetTop, h: r.height, fs: parseFloat(getComputedStyle(el).fontSize) || 10 });
    });
    /* also index the catalogue card text for searchability */
    if (stopsSelector) clone.querySelectorAll(".vc-nm, .vc-rate, .vc-band-nm").forEach((el) => {
      const t = (el.innerText || "").trim().replace(/\s+/g, " ");
      if (!t) return;
      const r = el.getBoundingClientRect();
      texts.push({ t, x: r.left - sheetRect.left, y: r.top - sheetTop, h: r.height, fs: parseFloat(getComputedStyle(el).fontSize) || 10 });
    });
    const stops = [];
    clone.querySelectorAll(stopsSelector || "tbody tr, .sheet-foot").forEach((el) => {
      stops.push(el.getBoundingClientRect().top - sheetTop);
    });
    stops.push(totalH);
    const sorted = Array.from(new Set(stops.map((v) => Math.max(0, Math.round(v))))).sort((a, b) => a - b);
    const pageWmm = 210, pageHmm = 297, mSide = 9, mTop = 8, mBot = 10;
    const contentWmm = pageWmm - 2 * mSide;
    const pxPerMm = 794 / contentWmm;
    const usablePx = (pageHmm - mTop - mBot) * pxPerMm;
    const pdf = new window.jspdf.jsPDF({ unit: "mm", format: "a4", compress: true });
    let start = 0, page = 0;
    while (start < totalH - 1) {
      let end = Math.min(start + usablePx, totalH);
      if (end < totalH) {
        const cands = sorted.filter((v) => v > start + usablePx * 0.4 && v <= end);
        if (cands.length) end = cands[cands.length - 1];
      }
      const slice = end - start;
      const c2 = document.createElement("canvas");
      c2.width = canvas.width;
      c2.height = Math.max(1, Math.round(slice * 2));
      const ctx = c2.getContext("2d");
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, c2.width, c2.height);
      ctx.drawImage(canvas, 0, Math.round(start * 2), canvas.width, c2.height, 0, 0, canvas.width, c2.height);
      if (page > 0) pdf.addPage();
      pdf.addImage(c2.toDataURL("image/jpeg", 0.95), "JPEG", mSide, mTop, contentWmm, slice / pxPerMm);
      const s = start, e = end;
      pdf.setTextColor(0, 0, 0);
      texts.forEach((o) => {
        if (o.y < s - 0.5 || o.y + o.h > e + 1) return;
        pdf.setFontSize((o.fs / pxPerMm) * 2.8346);
        pdf.text(o.t, mSide + o.x / pxPerMm, mTop + (o.y - s + o.h * 0.78) / pxPerMm, { renderingMode: "invisible" });
      });
      page++;
      start = end;
    }
    await deliverFile(pdf.output("blob"), filename, { title: filename });
    return page;
  } finally {
    wrap.remove();
  }
}

/* Canvas to Blob. A data: URL cannot be saved on iOS Safari, which ignores the
   download attribute for data: URLs and simply opens the image instead. */
function canvasToBlob(canvas, type, quality) {
  return new Promise((resolve, reject) => {
    if (canvas.toBlob) {
      canvas.toBlob((b) => b ? resolve(b) : reject(new Error("Could not encode the image")), type, quality);
      return;
    }
    try {
      const parts = canvas.toDataURL(type, quality).split(",");
      const bin = atob(parts[1]);
      const arr = new Uint8Array(bin.length);
      for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
      resolve(new Blob([arr], { type: type }));
    } catch (e) { reject(e); }
  });
}

/* Hand a finished file to the person. On a phone this opens the native share sheet,
   so a quote goes straight into WhatsApp instead of a download the user then has to
   find and attach. Falls back to a blob download, which iOS does honour. */
async function deliverFile(blob, filename, opts) {
  opts = opts || {};
  if (opts.share !== false && navigator.canShare && typeof File === "function") {
    try {
      const file = new File([blob], filename, { type: blob.type });
      if (navigator.canShare({ files: [file] })) {
        await navigator.share({ files: [file], title: opts.title || filename });
        return "shared";
      }
    } catch (err) {
      /* the person dismissed the sheet: do not then also download behind their back */
      if (err && (err.name === "AbortError" || err.name === "NotAllowedError")) return "cancelled";
    }
  }
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.rel = "noopener";
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 20000);
  return "downloaded";
}

/* Detected once: can this device hand a real file to another app (WhatsApp, Mail)?
   True on iPhone and Android, on Safari for Mac, and on Chrome/Edge for Windows.
   False on most desktop Chrome, where the honest word is still Download. */
const CAN_SHARE_FILES = (function () {
  try {
    if (!navigator.canShare || typeof File !== "function") return false;
    const probe = new File([new Blob(["x"], { type: "text/plain" })], "probe.txt", { type: "text/plain" });
    return !!navigator.canShare({ files: [probe] });
  } catch (e) { return false; }
})();

/* House filing convention (same as NEMPL letters, CC statements, insurance):
   the name starts YYYY-MM-DD, so sorting by Name sorts by date and reversing the
   column keeps the newest document on top. Local date, not toISOString, which is
   UTC and would roll the date backwards in the early hours in India. */
function isoDate(d) {
  d = d || new Date();
  const p = (n) => String(n).padStart(2, "0");
  return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate());
}
/* "10 April 2026" as it is stored, into 2026-04-10 for a filename */
function isoWef(wef) {
  const d = window.parseWefDate ? window.parseWefDate(wef) : null;
  return d ? isoDate(d) : String(wef || "").trim();
}
/* Windows and macOS both reject these in a filename */
function safeName(s) {
  return String(s).replace(/[\\/:*?"<>|]+/g, " ").replace(/\s+/g, " ").trim();
}

window.isoDate = isoDate;
window.isoWef = isoWef;
window.safeName = safeName;
window.CAN_SHARE_FILES = CAN_SHARE_FILES;
window.sheetToPdf = sheetToPdf;
window.loadPdfLibs = loadPdfLibs;
window.canvasToBlob = canvasToBlob;
window.deliverFile = deliverFile;

function PrintView({ source, onSource, headerStyle, onHeaderStyle, nav }) {
  const state = PLM.useStore();
  const party = source !== "general" ? PLM.partyById(source) : null;
  const deskRef = React.useRef(null);
  const wrapRef = React.useRef(null);
  const [fit, setFit] = useState({ scale: 1, h: 0, pages: 1 });

  useEffect(() => {
    function measure() {
      const desk = deskRef.current, wrap = wrapRef.current;
      /* Retry rather than give up: on first paint the sheet child may not exist yet,
         and a single missed frame used to leave the preview stuck at full size. */
      if (!desk || !wrap || !wrap.firstChild || !desk.clientWidth) { raf = requestAnimationFrame(measure); return; }
      const sheet = wrap.firstChild;
      const cs = getComputedStyle(desk);
      const avail = desk.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
      const scale = Math.min(1, avail / 794);
      const h = sheet.offsetHeight;
      /* the sheet is A4 at 96dpi, 794x1123, so divide by its real height. 1045
         made even a single page sheet report two, which the measure fix exposed. */
      const pages = Math.max(1, Math.ceil(h / 1123));
      setFit((f) => (Math.abs(f.scale - scale) > 0.005 || Math.abs(f.h - h) > 2 || f.pages !== pages) ? { scale, h, pages } : f);
    }
    let raf = requestAnimationFrame(measure);
    window.addEventListener("resize", measure);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", measure); };
  });

  const docLabel = party ? "Price list for " + party.name : "General price list";
  const [pdfBusy, setPdfBusy] = useState(false);

  async function onDownloadPdf() {
    if (pdfBusy) return;
    const sheet = wrapRef.current ? wrapRef.current.querySelector(".sheet") : null;
    if (!sheet) return;
    setPdfBusy(true);
    try {
      const name = safeName(isoDate() + " NGIPL Price List"
        + (party ? " " + party.name : "")
        + " (WEF " + isoWef(state.settings.wef) + ")") + ".pdf";
      await sheetToPdf(sheet, name);
      PLM.logPrint("Downloaded PDF: " + docLabel + " (W.E.F. " + state.settings.wef + ")");
    } catch (err) {
      console.error(err);
      window.alert("PDF export failed: " + err.message + "\nUse Print / Save PDF instead.");
    }
    setPdfBusy(false);
  }

  return (
    <div data-screen-label="Print &amp; Export">
      <div className="print-controls">
        <div className="toolbar toolbar--tight">
          <Field label="Letterhead">
            <Seg options={[{ value: "charcoal", label: "Charcoal" }, { value: "minimal", label: "Minimal" }]}
              value={headerStyle} onChange={onHeaderStyle}></Seg>
          </Field>
          <div className="spacer"></div>
          <span className="caption tnum" style={{ whiteSpace: "nowrap" }}>A4 · ≈ {fit.pages} page{fit.pages === 1 ? "" : "s"}</span>
          <Btn variant="ghost" onClick={onDownloadPdf} disabled={pdfBusy}><IDownload size={14}></IDownload> {pdfBusy ? "Preparing…" : "Download PDF"}</Btn>
          <Btn title="In the print dialog use: Margins: Default · Scale: 100% · Background graphics: ON" onClick={() => {
            PLM.logPrint("Printed " + docLabel + " (W.E.F. " + state.settings.wef + ")");
            window.print();
          }}><IPrinter size={14}></IPrinter> Print</Btn>
        </div>

        <div className="print-opts panel">
          <span className="caption" style={{ alignSelf: "center" }}>W.E.F. {state.settings.wef}, changed by an admin under Settings</span>
          <Field label="Footer note" className="po-field--note">
            <input className="f-input f-input--sm" value={state.settings.priceNote}
              onChange={(e) => PLM.setSettings({ priceNote: e.target.value })} />
          </Field>
        </div>
      </div>

      <div className="print-desk" ref={deskRef}>
        <div className="desk-doclabel">{docLabel}</div>
        <div className="sheet-scale" ref={wrapRef}
          style={{ transform: "scale(" + fit.scale + ")", width: 794 * fit.scale, height: fit.h ? fit.h * fit.scale : "auto" }}>
          <PriceSheet party={party} headerStyle={headerStyle}></PriceSheet>
        </div>
      </div>
    </div>
  );
}

/* Rows for general list: master grouped; party: partyGrouped; quick quote: by category */
function sheetRows(state, party, quick) {
  const rows = [];
  if (quick) {
    const pb = PLM.productsById();
    const nm = PLM.numberMap();
    const sorted = quick.items.slice().sort((a, b) => {
      const an = a.productId && nm[a.productId] ? nm[a.productId] : 9999;
      const bn = b.productId && nm[b.productId] ? nm[b.productId] : 9999;
      return an - bn;
    });
    const byCat = {};
    sorted.forEach((it) => {
      const p = pb[it.productId];
      if (!p) return;
      (byCat[p.categoryId] = byCat[p.categoryId] || []).push(it);
    });
    const catIds = state.categories.map((c) => c.id);
    const bands = state.categories.slice();
    if (Object.keys(byCat).some((id) => catIds.indexOf(id) === -1)) {
      const other = { id: "cat-other", name: "Other", subs: [] };
      Object.keys(byCat).forEach((id) => {
        if (catIds.indexOf(id) === -1) {
          (byCat["cat-other"] = byCat["cat-other"] || []).push.apply(byCat["cat-other"], byCat[id]);
        }
      });
      bands.push(other);
    }
    bands.forEach((c) => {
      if (!byCat[c.id]) return;
      rows.push({ kind: "cat", cat: c });
      byCat[c.id].forEach((it) => {
        const p = pb[it.productId];
        rows.push({
          kind: "item", name: p.name, note: p.note,
          rate: it.rate, unit: p.unit, pack: p.packSize, outer: p.outerPack, gst: p.gst,
        });
      });
    });
    return rows;
  }
  if (!party) {
    PLM.groupedProducts().forEach((band) => {
      rows.push({ kind: "cat", cat: band.cat });
      band.groups.forEach((g) => {
        if (g.sub) rows.push({ kind: "sub", name: g.sub.name });
        g.items.forEach((p) => rows.push({
          kind: "item", name: p.name, note: p.note,
          rate: p.rate, unit: p.unit, pack: p.packSize, outer: p.outerPack, gst: p.gst,
        }));
      });
    });
  } else {
    const pb = PLM.productsById();
    PLM.partyGrouped(party).forEach((band) => {
      rows.push({ kind: "cat", cat: band.cat });
      band.items.forEach((it) => {
        const p = it.productId ? pb[it.productId] : null;
        rows.push({
          kind: "item",
          name: p ? (it.displayName || p.name) : it.customName,
          note: p ? p.note : "",
          rate: it.rate,
          unit: it.unit !== null && it.unit !== undefined && it.unit !== "" ? it.unit : (p ? p.unit : ""),
          outer: p ? p.outerPack : null,
          pack: it.packSize !== null && it.packSize !== undefined ? it.packSize : (p ? p.packSize : null),
          gst: it.gst !== null && it.gst !== undefined ? it.gst : (p ? p.gst : null),
        });
      });
    });
  }
  return rows;
}

function PriceSheet({ party, quick, headerStyle }) {
  const state = PLM.useStore();
  const entity = PLM.entityById("ngipl");
  const rows = sheetRows(state, party, quick);
  let no = 0;
  return (
    <div className="sheet" data-screen-label="A4 Price List Sheet">
      {headerStyle === "charcoal" ? (
        <div className="sheet-band" style={{ position: "relative" }}>
          <svg className="band-fill" aria-hidden="true" focusable="false" preserveAspectRatio="none"
            style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", display: "block", zIndex: 0 }}>
            <rect width="100%" height="100%" fill="#222021"></rect>
          </svg>
          <img src="assets/logos/lockup-stacked-white-cropped.png" alt="Nathurmal Global Industries Pvt. Ltd." style={{ position: "relative", zIndex: 1 }} />
          <div style={{ position: "relative", zIndex: 1 }}>
            <div className="co-block">
              <div className="co-name">{entity.name}</div>
              <div>{entity.address}</div>
              <div>CIN {entity.cin} · FSSAI {entity.fssai}</div>
              <div>GST {entity.gst} · UDYAM {entity.udyam}</div>
              <div>{entity.phone} · {entity.email}</div>
            </div>
            <div className="sheet-icons">
              {state.categories.map((c) => (
                <span key={c.id} className="sheet-icon" title={c.name}>
                  <CatIcon catId={c.id} size={22}></CatIcon>
                  <span className="sheet-icon-name">{c.name.replace(" Products", "")}</span>
                </span>
              ))}
            </div>
          </div>
        </div>
      ) : (
          <div className="sheet-min-head">
            <img src="assets/logos/lockup-stacked-black-cropped.png" alt="Nathurmal Global Industries Pvt. Ltd." />
            <div>
              <div className="co-block">
                <div className="co-name">{entity.name}</div>
                <div>{entity.address}</div>
                <div>CIN {entity.cin} · FSSAI {entity.fssai}</div>
                <div>GST {entity.gst} · UDYAM {entity.udyam}</div>
                <div>{entity.phone} · {entity.email}</div>
              </div>
              <div className="sheet-icons">
                {state.categories.map((c) => (
                  <span key={c.id} className="sheet-icon" title={c.name}>
                    <CatIcon catId={c.id} size={22}></CatIcon>
                    <span className="sheet-icon-name">{c.name.replace(" Products", "")}</span>
                  </span>
                ))}
              </div>
            </div>
          </div>
      )}
      {headerStyle === "charcoal" ? null : <div className="sheet-rule"></div>}

      <div className="sheet-titlerow">
        <div className="sheet-title">{quick ? "Quotation" : "Price List"}</div>
        <div className={quick ? "sheet-wef" : "sheet-wef sheet-wef--big"}>{quick ? "Dated " + quick.date : "W.E.F. " + state.settings.wef}</div>
      </div>
      {quick || party ? (
        <div className="sheet-subrow">
          <div className="sheet-for">
            {quick
              ? "Prepared for " + (quick.customer.trim() || "-")
              : "Prepared for " + party.name}
          </div>
        </div>
      ) : (
        <div style={{ height: 8 }}></div>
      )}

      <div className="pt">
        <table>
          <thead>
            <tr>
              <th style={{ width: 26 }}>#</th>
              <th>Item</th>
              <th className="num" style={{ width: 58 }}>Rate ₹</th>
              <th style={{ width: 56 }}>Unit</th>
              <th className="num" style={{ width: 36 }}>GST</th>
              <th className="num" style={{ width: 52 }}>Pack size</th>
              <th className="num" style={{ width: 62 }}>Outer pack</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => {
              if (r.kind === "cat") {
                return (
                  <tr className="s-cat" key={"c" + i}>
                    <td colSpan={7}>
                      <span className="cat-cell">
                        <CatIcon catId={r.cat.id} size={16}></CatIcon>
                        <span>{r.cat.name}</span>
                      </span>
                    </td>
                  </tr>
                );
              }
              if (r.kind === "sub") {
                return <tr className="s-sub" key={"s" + i}><td colSpan={7}>{r.name}</td></tr>;
              }
              no++;
              return (
                <tr key={"i" + i}>
                  <td className="s-no num">{no}</td>
                  <td>
                    {r.name}
                    {r.note ? <span className="s-note">({r.note})</span> : null}
                  </td>
                  <td className="num s-rate tnum">{PLM.fmtRate(r.rate)}</td>
                  <td>{r.unit}</td>
                  <td className="num tnum">{PLM.fmtGst(r.gst).replace("%", "")}</td>
                  <td className="num tnum">{PLM.fmtPack(r.pack)}</td>
                  <td className="num tnum">{PLM.fmtPack(r.outer)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="sheet-foot">
        <div className="fnote">
          {state.settings.priceNote}
          {quick && quick.note ? <div>{quick.note}</div> : null}
        </div>
        <div className="fmark">{quick ? "E. & O. E." : "Prices subject to change"}</div>
      </div>
      <div style={{ height: 12 }}></div>
    </div>
  );
}

Object.assign(window, { PrintView, PriceSheet });
