/* =============================================================
   CoreIQ Office — Suppliers: directory + New-supplier modal
   Registers window.OFFICE_SCREENS.suppliers
   ============================================================= */
const { useState: suUseState, useMemo: suUseMemo, useEffect: suUseEffect } = React;

const LOGO = { "sup-01": "GSK", "sup-02": "SIG", "sup-03": "SYM", "sup-04": "API", "sup-05": "WEB", "sup-06": "NDS" };

function supMoney(n) { return window.officeMoney(n); }
function supK(n) {
  const a = Math.abs(n);
  if (a >= 1000) return (n < 0 ? "−$" : "$") + (a / 1000).toFixed(a >= 100000 ? 0 : 1) + "k";
  return supMoney(n);
}
function perfClass(v) { return v == null ? "" : v >= 95 ? "sup-perf--good" : v >= 90 ? "sup-perf--mid" : "sup-perf--bad"; }
function logoText(id) {
  if (LOGO[id]) return LOGO[id];
  const s = window.OFFICE_DATA.SUPPLIERS.find(x => x.id === id);
  if (!s) return "SUP";
  return s.name.replace(/[^A-Za-z ]/g, "").trim().split(/\s+/).map(w => w[0]).slice(0, 3).join("").toUpperCase();
}
function logoFor(id) {
  return <div className="sup-logo" style={{ background: window.supType(id).color }}>{logoText(id)}</div>;
}
function lineBadgeClass(id) {
  const l = window.supLine(id);
  if (typeof l === "number") return "sup-line-badge--n" + (l <= 3 ? l : "x");
  return "sup-line-badge--" + l;
}

// perf chip that tolerates new suppliers (null metrics)
function PerfCell({ v }) {
  if (v == null) return <div className="sup-perf"><span className="sup-perf-dot" style={{ background: "var(--border-strong)" }}/>—</div>;
  return <div className={"sup-perf " + perfClass(v)}><span className="sup-perf-dot"/>{v}%</div>;
}

// =================================================================
// NEW SUPPLIER MODAL
// =================================================================
function NewSupplierModal({ onClose, onCreated }) {
  const nextLine = (window.supRankedIds().length || 0) + 1;
  const [form, setForm] = suUseState({
    name: "", type: "wholesaler", line: nextLine,
    account: "", contact: "", phone: "", payment: "Net 30",
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // line options depend on type
  const lineOpts = form.type === "wholesaler"
    ? [{ v: 1, l: "1st line" }, { v: 2, l: "2nd line" }, { v: 3, l: "3rd line" }, { v: nextLine, l: "Next available" }]
    : form.type === "program"
      ? [{ v: "program", l: "Program" }]
      : [{ v: "direct", l: "Direct" }];

  // keep line valid when type changes
  suUseEffect(() => {
    if (form.type === "program" && form.line !== "program") set("line", "program");
    else if (form.type === "brand-direct" && form.line !== "direct") set("line", "direct");
    else if (form.type === "wholesaler" && typeof form.line !== "number") set("line", 1);
  }, [form.type]);

  const valid = form.name.trim().length > 1;

  function submit() {
    if (!valid) return;
    const id = window.supAddSupplier(form);
    onCreated(id, form);
  }

  const TYPE_OPTS = [
    { v: "wholesaler", l: "Wholesaler" },
    { v: "brand-direct", l: "Brand direct" },
    { v: "program", l: "Program" },
  ];

  return (
    <div className="sup-modal-overlay" onClick={onClose}>
      <div className="sup-modal" onClick={e => e.stopPropagation()}>
        <div className="sup-modal-head">
          <div className="sup-modal-head-ic"><window.OIcon name="truck"/></div>
          <div style={{ flex: 1 }}>
            <div className="sup-modal-title">New supplier</div>
            <div className="sup-modal-sub">Add a wholesaler, brand-direct or program account</div>
          </div>
          <button className="off-topbar-btn" onClick={onClose}><window.OIcon name="x"/></button>
        </div>

        <div className="sup-modal-body">
          <div>
            <label className="sup-field-label">Supplier name</label>
            <input className="input" autoFocus placeholder="e.g. CH2 · Clifford Hallam" value={form.name} onChange={e => set("name", e.target.value)}/>
          </div>

          <div className="sup-form-grid">
            <div>
              <label className="sup-field-label">Type</label>
              <select className="input select" value={form.type} onChange={e => set("type", e.target.value)}>
                {TYPE_OPTS.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
              </select>
            </div>
            <div>
              <label className="sup-field-label">Payment terms</label>
              <select className="input select" value={form.payment} onChange={e => set("payment", e.target.value)}>
                {["Net 7", "Net 14", "Net 30", "Net 30 EOM"].map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
          </div>

          <div>
            <label className="sup-field-label">Order priority {form.type === "wholesaler" ? "— which line does it sit on?" : ""}</label>
            <div className="sup-line-pick">
              {lineOpts.map(o => (
                <button key={String(o.v)} className={"sup-line-opt" + (String(form.line) === String(o.v) ? " sup-line-opt--active" : "")} onClick={() => set("line", o.v)}>{o.l}</button>
              ))}
            </div>
            {form.type === "wholesaler" && typeof form.line === "number" && form.line <= window.supRankedIds().length && (
              <div className="sup-modal-hint" style={{ marginTop: 8 }}>Inserting at {form.line === 1 ? "1st" : form.line === 2 ? "2nd" : form.line === 3 ? "3rd" : form.line + "th"} line will push lower-priority wholesalers down one.</div>
            )}
          </div>

          <div className="sup-form-grid">
            <div>
              <label className="sup-field-label">Account number</label>
              <input className="input" placeholder="e.g. CH2-44120" value={form.account} onChange={e => set("account", e.target.value)}/>
            </div>
            <div>
              <label className="sup-field-label">Contact</label>
              <input className="input" placeholder="Rep name" value={form.contact} onChange={e => set("contact", e.target.value)}/>
            </div>
            <div className="sup-form-full">
              <label className="sup-field-label">Phone</label>
              <input className="input" placeholder="1300 000 000" value={form.phone} onChange={e => set("phone", e.target.value)}/>
            </div>
          </div>
        </div>

        <div className="sup-modal-foot">
          <div className="sup-modal-hint" style={{ flex: 1 }}>New accounts start with no order history — add SKUs and PDEs from the supplier’s Catalogue tab.</div>
          <button className="btn btn--secondary" onClick={onClose}>Cancel</button>
          <button className="btn btn--primary" disabled={!valid} onClick={submit}><window.OIcon name="plus"/> Add supplier</button>
        </div>
      </div>
    </div>
  );
}

// =================================================================
// DIRECTORY
// =================================================================
// -----------------------------------------------------------------
// SUPPLIERS — LIVE · this pharmacy
// The org's 226 real suppliers (migrated from Z), with how many catalogue
// products name each as primary supplier. Spend / on-time / backorders are NOT
// shown — none of that was migrated, so we don't fabricate it.
// -----------------------------------------------------------------
function Suppliers() {
  const { setScreen, setScreenState } = window.useOffice();
  const [suppliers, setSuppliers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);
  const [q, setQ] = React.useState("");
  const [sort, setSort] = React.useState({ key: "productCount", dir: "desc" });

  React.useEffect(() => {
    let alive = true;
    window.OfficeAPI.listSuppliers()
      .then((ss) => { if (alive) { setSuppliers(ss || []); setLoading(false); } })
      .catch((e) => { if (alive) { setErr(String((e && e.message) || e)); setLoading(false); } });
    return () => { alive = false; };
  }, []);

  const withProducts = suppliers.filter((s) => s.productCount > 0).length;
  const withContact = suppliers.filter((s) => s.email || s.phone).length;
  const active = suppliers.filter((s) => s.isActive).length;

  const filtered = suppliers.filter((s) => {
    if (!q.trim()) return true;
    const n = q.trim().toLowerCase();
    return (s.name + " " + (s.code || "") + " " + (s.email || "") + " " + (s.locality || "")).toLowerCase().includes(n);
  });
  const dir = sort.dir === "asc" ? 1 : -1;
  const sorted = [...filtered].sort((a, b) => {
    const ka = a[sort.key], kb = b[sort.key];
    if (typeof ka === "number" || typeof kb === "number") return ((ka || 0) - (kb || 0)) * dir;
    return String(ka || "").localeCompare(String(kb || "")) * dir;
  });
  function sortBy(k) { setSort((s) => (s.key === k ? { key: k, dir: s.dir === "asc" ? "desc" : "asc" } : { key: k, dir: "asc" })); }
  function open(s) { setScreenState((st) => ({ ...st, supplier: s })); setScreen("supplierDetail"); }

  const COLS = [
    { k: "name", label: "Supplier" },
    { k: "code", label: "Code" },
    { k: "supplierType", label: "Type" },
    { k: "email", label: "Contact" },
    { k: "productCount", label: "Products", num: true },
    { k: "accountNumber", label: "Account #" },
    { k: "paymentTermsDays", label: "Terms", num: true },
  ];

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Buying · this pharmacy · live from Aurora</span>
          <h2 className="off-screen-title">Suppliers</h2>
        </div>
      </header>

      <div className="off-screen-body">
        {err && (
          <div className="off-card" style={{borderColor:'var(--void-border)',background:'var(--void-bg)',color:'var(--void-text)',marginBottom:14,padding:'12px 16px',flexDirection:'row',alignItems:'center',gap:10}}>
            <window.OIcon name="alert"/> <span>Couldn't load suppliers: {err}</span>
          </div>
        )}

        <div className="off-kpi-grid">
          <KpiCard label="Suppliers" value={loading ? "…" : suppliers.length.toLocaleString("en-AU")} delta={{ text: active + " active" }}/>
          <KpiCard label="Supplying products" value={loading ? "…" : withProducts.toLocaleString("en-AU")} delta={{ text: "named as primary supplier" }}/>
          <KpiCard label="With contact details" value={loading ? "…" : withContact.toLocaleString("en-AU")} delta={{ text: "email or phone on file" }}/>
          <KpiCard label="Migrated from Z" value={loading ? "…" : suppliers.length.toLocaleString("en-AU")} delta={{ dir: "up", text: "incoming data" }}/>
        </div>

        <div className="off-table" style={{marginTop:16}}>
          <div className="off-table-toolbar">
            <div className="input-wrap" style={{flex:1, maxWidth:340}}>
              <window.OIcon name="search" className="input-wrap-icon"/>
              <input className="input" placeholder="Search suppliers (name, code, email, town)…" value={q} onChange={(e) => setQ(e.target.value)} style={{height:34, fontSize:'var(--fs-13)'}}/>
            </div>
            <div style={{marginLeft:'auto', fontSize:'var(--fs-12)', color:'var(--text-muted)'}}>{loading ? "loading…" : sorted.length + " of " + suppliers.length}</div>
          </div>
          <div className="off-grid" style={{gridTemplateColumns:'minmax(200px,1.6fr) 90px 130px minmax(180px,1.2fr) 90px 130px 70px'}}>
            {COLS.map((c) => (
              <div key={c.k} className="off-grid-headcell" onClick={() => sortBy(c.k)} style={c.num ? {justifyContent:'flex-end'} : null}>
                {c.label}{sort.key === c.k && <window.OIcon className="sort-arrow" name={sort.dir === "asc" ? "arrow-up" : "arrow-down"}/>}
              </div>
            ))}
            {sorted.map((s) => (
              <div key={s.id} className="off-grid-row" onClick={() => open(s)}>
                <div className="off-grid-cell off-cell-strong">
                  {s.name}{!s.isActive && <span style={{marginLeft:6, fontSize:10, color:'var(--text-subtle)'}}>inactive</span>}
                </div>
                <div className="off-grid-cell off-cell-mono">{s.code || "—"}</div>
                <div className="off-grid-cell off-muted">{s.supplierType || "—"}</div>
                <div className="off-grid-cell off-cell-mono" style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{s.email || s.phone || <span style={{color:'var(--text-subtle)'}}>—</span>}</div>
                <div className="off-grid-cell off-cell-num off-cell-strong">{s.productCount.toLocaleString("en-AU")}</div>
                <div className="off-grid-cell off-cell-mono">{s.accountNumber || "—"}</div>
                <div className="off-grid-cell off-cell-num">{s.paymentTermsDays != null ? "Net " + s.paymentTermsDays : "—"}</div>
              </div>
            ))}
          </div>
          {!loading && sorted.length === 0 && <div className="off-empty" style={{padding:30}}><div className="empty-title">No suppliers match “{q}”.</div></div>}
        </div>
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, { suppliers: Suppliers });
window.SupLogo = logoFor;
window.supMoneyK = supK;
window.supLogoText = LOGO;
window.supLogoTextFor = logoText;
window.supPerfClass = perfClass;
