/* =============================================================
   CoreIQ Office — National catalogue (Ironbark reference)
   Live search over the shared Ironbark reference catalogue served
   by the Office API (/reference/*). This screen reads REAL data —
   no sample data. It is the source-of-truth product browser a
   pharmacy uses before adding a line to its own catalogue.
   ============================================================= */
const { useState: catUseState, useEffect: catUseEffect, useRef: catUseRef } = React;

function NationalCatalogue() {
  const [q, setQ] = catUseState("");
  const [rows, setRows] = catUseState([]);
  const [stats, setStats] = catUseState(null);
  const [loading, setLoading] = catUseState(true);
  const [err, setErr] = catUseState(null);
  const reqSeq = catUseRef(0);
  const [sort, setSort] = catUseState({ col: "description", dir: "asc" });

  // How much reference data is loaded — proves the catalogue is fully populated.
  catUseEffect(() => {
    window.OfficeAPI.referenceStats()
      .then(setStats)
      .catch((e) => setErr(String(e.message || e)));
  }, []);

  // Debounced live search (empty query = alphabetical browse).
  catUseEffect(() => {
    const seq = ++reqSeq.current;
    setLoading(true);
    const t = setTimeout(() => {
      window.OfficeAPI.referenceSearch(q.trim(), 60, 0, sort.col, sort.dir)
        .then((ps) => {
          if (seq !== reqSeq.current) return; // a newer query won
          setRows(ps);
          setErr(null);
          setLoading(false);
        })
        .catch((e) => {
          if (seq !== reqSeq.current) return;
          setErr(String(e.message || e));
          setLoading(false);
        });
    }, 220);
    return () => clearTimeout(t);
  }, [q, sort.col, sort.dir]);

  const price = (cents) =>
    cents == null ? "—" : window.officeMoney(cents / 100);

  const COLS = [
    { k: "description", label: "Product", num: false },
    { k: "barcode",     label: "Barcode", num: false },
    { k: "schedule",    label: "Sched",   num: false },
    { k: "generic",     label: "Generic / active", num: false },
    { k: "pack",        label: "Pack",    num: false },
    { k: "price",       label: "Trade ex-GST", num: true },
    { k: "provider",    label: "Source",  num: false },
  ];
  const toggleSort = (k) =>
    setSort((s) => (s.col === k ? { col: k, dir: s.dir === "asc" ? "desc" : "asc" } : { col: k, dir: k === "price" ? "desc" : "asc" }));
  const arrow = (k) => (sort.col === k ? (sort.dir === "asc" ? " ↑" : " ↓") : "");

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Catalogue · Ironbark national reference</span>
          <h2 className="off-screen-title">Product catalogue</h2>
        </div>
        <div className="off-screen-actions">
          {stats && (
            <span className="off-filter-count">
              {stats.wholesalerProducts.toLocaleString()} products ·
              {" "}{stats.drugs.toLocaleString()} drugs ·
              {" "}{stats.pbsItems.toLocaleString()} PBS ·
              {" "}{stats.artgProducts.toLocaleString()} ARTG · export v{stats.exportVersion}
            </span>
          )}
        </div>
      </header>

      <div className="off-screen-body">
        <div className="off-filters" style={{ alignItems: "center" }}>
          <div className="off-topbar-search" style={{ maxWidth: 460, flex: "0 1 460px" }}>
            <OIcon name="search" className="off-topbar-search-ic" />
            <input
              className="input"
              placeholder={
                stats
                  ? `Search ${stats.wholesalerProducts.toLocaleString()} products by name or barcode…`
                  : "Search products by name or barcode…"
              }
              value={q}
              onChange={(e) => setQ(e.target.value)}
              autoFocus
            />
          </div>
          <span className="off-filter-count">
            {loading ? "Searching…" : `${rows.length} shown`}
          </span>
        </div>

        {err && (
          <div className="signin-error" style={{ marginBottom: 12 }}>
            Couldn’t reach the catalogue API — {err}
          </div>
        )}

        <div className="off-table" style={{ minWidth: 0 }}>
          <div
            className="off-grid"
            style={{ gridTemplateColumns: "1.9fr 130px 64px 1.1fr 96px 110px 72px" }}
          >
            {COLS.map((c) => (
              <div
                key={c.k}
                className="off-grid-headcell"
                onClick={() => toggleSort(c.k)}
                title="Sort"
                style={Object.assign({ cursor: "pointer", userSelect: "none" }, c.num ? { justifyContent: "flex-end" } : {})}
              >
                {c.label}{arrow(c.k)}
              </div>
            ))}

            {rows.map((r) => (
              <div className="off-grid-row" key={r.wholesalerProductId}>
                <div className="off-grid-cell off-cell-strong">{r.description || "—"}</div>
                <div className="off-grid-cell off-cell-mono">{r.barcode || "—"}</div>
                <div className="off-grid-cell">
                  {r.drugSchedule
                    ? <window.SchedBadge schedule={r.drugSchedule} compact />
                    : <span className="off-muted">—</span>}
                </div>
                <div className="off-grid-cell off-muted">{r.genericName || "—"}</div>
                <div className="off-grid-cell">
                  {r.packQuantity ? `${r.packQuantity} ${r.packUom || ""}`.trim() : "—"}
                </div>
                <div className="off-grid-cell off-cell-num">{price(r.tradePriceExGstCents)}</div>
                <div className="off-grid-cell off-cell-mono off-muted">{r.provider || "—"}</div>
              </div>
            ))}
          </div>
        </div>

        {!loading && rows.length === 0 && !err && (
          <div className="off-empty">
            <div className="empty-icon"><OIcon name="search" width={20} height={20} /></div>
            <div className="empty-title">No products match “{q}”.</div>
          </div>
        )}
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  catalogue: NationalCatalogue,
});
