/* NGIPL PLM Visual catalogue view: photo catalogue generated live from PLM data.
   Formats: A4 (print/PDF/email) and Mobile (WhatsApp image). Prices togglable.
   Three layout styles to compare: Grid / Showcase / Compact. */
const { useState, useMemo, useRef } = React;

function catPhoto(p) { return (window.PLM_PHOTOS || {})[p.id] || null; }

function CatCard({ p, style, prices, catId }) {
  const src = catPhoto(p);
  return (
    <div className={"vc-card vc-card--" + style}>
      <div className={"vc-ph" + (src ? "" : " vc-ph--empty")}>
        {src
          ? <img src={src} alt={p.name} loading="lazy" />
          : (
            <span className="vc-ph-fallback">
              <CatIcon catId={catId} size={style === "showcase" ? 30 : 20}></CatIcon>
              <span className="vc-ph-soon">Image coming soon</span>
            </span>
          )}
      </div>
      <div className="vc-bd">
        <div className="vc-nm">{p.name}</div>
        {p.note ? <div className="vc-note">{p.note}</div> : null}
        {prices ? (
          <div className="vc-meta">
            <span className="vc-rate tnum">₹{PLM.fmtRate(p.rate)}</span>
            <span className="vc-unit">{p.unit}{p.packSize ? " · " + PLM.fmtPack(p.packSize) : ""}</span>
          </div>
        ) : null}
      </div>
    </div>
  );
}

function CatalogueSheet({ format, style, prices, sheetRef }) {
  const state = PLM.useStore();
  const bands = PLM.groupedProducts();
  const entity = PLM.entityById("ngipl");
  return (
    <div ref={sheetRef} className={"sheet vc-sheet vc-sheet--" + format} data-screen-label="Visual Catalogue">
      <div className="vc-cover">
        <img src="assets/logos/lockup-stacked-black-cropped.png" alt="Nathurmal Global Industries Pvt. Ltd." />
        <div className="vc-cover-rule"></div>
        <div className="vc-cover-title">Product Catalogue</div>
        {prices ? <div className="vc-cover-wef">W.E.F. {state.settings.wef}</div> : null}
      </div>
      {bands.map((b) => {
        const items = b.groups.flatMap((g) => g.items);
        if (!items.length) return null;
        return (
          <section className="vc-cat" key={b.cat.id}>
            <div className="vc-band">
              <CatIcon catId={b.cat.id} size={18}></CatIcon>
              <span className="vc-band-nm">{b.cat.name}</span>
              <span className="vc-band-ct tnum">{String(items.length).padStart(2, "0")} products</span>
            </div>
            <div className={"vc-grid vc-grid--" + style}>
              {items.map((p) => <CatCard key={p.id} p={p} style={style} prices={prices} catId={b.cat.id}></CatCard>)}
            </div>
          </section>
        );
      })}
      <div className="vc-foot">
        <div>{entity ? entity.name : ""} · {entity ? entity.phone : ""} · {entity ? entity.email : ""}</div>
        <div className="fmark">Prices subject to change</div>
      </div>
    </div>
  );
}

function CatalogueView({ toast }) {
  const state = PLM.useStore();
  const [format, setFormat] = useState("a4");
  const [style, setStyle] = useState("grid");
  const [prices, setPrices] = useState(true);
  const [busy, setBusy] = useState(false);
  const sheetRef = useRef(null);
  const photoCount = useMemo(() => state.products.filter((p) => catPhoto(p)).length, [state]);

  async function downloadPdf() {
    if (busy || !sheetRef.current) return;
    setBusy(true);
    try {
      const name = window.safeName(window.isoDate() + " NGIPL Product Catalogue" + (prices ? " (WEF " + window.isoWef(state.settings.wef) + ")" : "")) + ".pdf";
      await window.sheetToPdf(sheetRef.current, name, ".vc-card, .vc-band, .vc-cover, .vc-foot");
      PLM.logPrint("Downloaded visual catalogue PDF (" + style + (prices ? ", with prices" : ", no prices") + ")");
    } catch (err) { window.alert("PDF export failed: " + err.message); }
    setBusy(false);
  }

  async function downloadImage() {
    if (busy || !sheetRef.current) return;
    setBusy(true);
    try {
      await window.loadPdfLibs();
      const canvas = await window.html2canvas(sheetRef.current, { scale: 2, useCORS: true, backgroundColor: "#ffffff", logging: false });
      const name = window.safeName(window.isoDate() + " NGIPL Catalogue Mobile" + (prices ? " (WEF " + window.isoWef(state.settings.wef) + ")" : "")) + ".jpg";
      const how = await window.deliverFile(await window.canvasToBlob(canvas, "image/jpeg", 0.9), name, { title: name });
      if (how !== "cancelled") {
        PLM.logPrint("Sent mobile catalogue image" + (prices ? " (with prices)" : " (no prices)"));
      }
    } catch (err) { window.alert("Image export failed: " + err.message); }
    setBusy(false);
  }

  return (
    <section>
      <div className="view-toolbar print-controls vc-controls">
        <div className="vc-ctl">
          <span className="f-label">Format</span>
          <Seg value={format} options={[{ value: "a4", label: "A4 · Print / PDF" }, { value: "mobile", label: "Mobile · WhatsApp" }]} onChange={setFormat}></Seg>
          <span className="caption">{format === "a4" ? "A4 pages. Print it or download a PDF to email" : "Narrow layout. Downloads as one image to forward on WhatsApp"}</span>
        </div>
        <div className="vc-ctl">
          <span className="f-label">Layout</span>
          <Seg value={style} options={[{ value: "grid", label: "Grid" }, { value: "showcase", label: "Showcase" }, { value: "compact", label: "Compact" }]} onChange={setStyle}></Seg>
          <span className="caption">{style === "grid" ? "3 per row, balanced everyday catalogue" : style === "showcase" ? "2 per row with big photos, premium look" : "4 per row, dense, fewest pages"}</span>
        </div>
        <div className="vc-ctl">
          <span className="f-label">Prices</span>
          <label className="caption vc-check">
            <input type="checkbox" checked={prices} onChange={(e) => setPrices(e.target.checked)} /> Show prices
          </label>
          <span className="caption">{prices ? "Rates + W.E.F. date printed on the catalogue" : "Photo book only, send rates separately"}</span>
        </div>
        <div className="spacer"></div>
        <div className="vc-ctl vc-ctl--actions">
          <div className="vc-actions">
            {format === "mobile"
              ? <Btn onClick={downloadImage} disabled={busy}><IDownload size={14}></IDownload> {busy ? "Preparing…" : (window.CAN_SHARE_FILES ? "Share image" : "Download image")}</Btn>
              : (
                <React.Fragment>
                  <Btn variant="ghost" onClick={downloadPdf} disabled={busy}><IDownload size={14}></IDownload> {busy ? "Preparing…" : "Download PDF"}</Btn>
                  <Btn title="In the print dialog use: Margins: Default · Scale: 100% · Background graphics: ON"
                    onClick={() => { PLM.logPrint("Printed visual catalogue"); window.print(); }}>
                    <IPrinter size={14}></IPrinter> Print
                  </Btn>
                </React.Fragment>
              )}
          </div>
          <span className="caption tnum">{photoCount} of {state.products.length} items have photos</span>
        </div>
      </div>
      <div className="vc-desk">
        <CatalogueSheet format={format} style={style} prices={prices} sheetRef={sheetRef}></CatalogueSheet>
      </div>
    </section>
  );
}

Object.assign(window, { CatalogueView });
