/* Banyan Pharmacy — Stores (stores-as-projects) */

function SupplierChips({ ids, max = 3 }) {
  const app = useApp();
  return (
    <div className="flex ic g6 wrap">
      {ids.slice(0, max).map((id) => {
        const s = D.supplierById[id];
        return <span key={id} className="tag" style={{ cursor: "pointer" }} onClick={(e) => { e.stopPropagation(); app.nav({ name: "supplier", id }); }}>{s.name}</span>;
      })}
    </div>
  );
}

function StoresPage() {
  const app = useApp();
  const stage = app.stage;
  const focusId = app.loopFocus && app.loopFocus.kind === "store" ? app.loopFocus.id : null;
  const rows = [...D.stores].sort((a, b) => {
    const ra = D.HEALTH_RANK[window.storeStatusAt(a, stage)], rb = D.HEALTH_RANK[window.storeStatusAt(b, stage)];
    return ra - rb;
  });
  return (
    <main className="page">
      <div className="ph">
        <div>
          <h1>Stores</h1>
          <div className="sub">10 stores · 3 hospital · 1 flagship · 6 neighbourhood — each store is its own record</div>
        </div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <table className="t">
          <thead>
            <tr>
              <th>Store</th><th>Format</th><th>Region</th><th>Manager</th><th>Shelf-health</th>
              <th className="right">Open</th><th>Primary suppliers</th><th></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((s) => {
              const status = window.storeStatusAt(s, stage);
              const focus = focusId === s.id;
              return (
                <tr key={s.id} className={cx("click", focus && "focus-glow")} style={{ cursor: "pointer" }}
                  onClick={() => app.nav({ name: "store", id: s.id })}>
                  <td>
                    <div className="store-name">{s.locality}</div>
                    <div className="store-sub mono">{s.id}</div>
                  </td>
                  <td><window.FormatBadge format={s.format} /></td>
                  <td className="muted">{s.region}</td>
                  <td className="mgr-cell">{s.manager}</td>
                  <td><window.HealthPill status={status} /></td>
                  <td className="right">{s.openAlerts > 0 ? <span className="pill clay"><span className="dot" />{s.openAlerts}</span> : <span className="faint">—</span>}</td>
                  <td><SupplierChips ids={s.suppliers} /></td>
                  <td className="right"><Icons.chevRight size={16} className="muted" /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <div className="mt12" style={{ fontSize: 13, color: "var(--mute)" }}>
        <window.Prov muted>Shelf-health is an estimate; thresholds are tighter for hospital stores.</window.Prov>
      </div>
    </main>
  );
}

function ShelfHealthRow({ item }) {
  return (
    <div className="row bare">
      <div className="main">
        <div className="flex ic g8">
          <span className="title" style={{ fontSize: 14 }}>{window.skuName(item.sku)}</span>
          {item.expiry && <span className="tag" style={{ fontSize: 11 }}>Expiry</span>}
        </div>
        <div className="meta">{item.note}</div>
      </div>
      <div className="right"><window.HealthPill status={item.status} /></div>
    </div>
  );
}

function StoreDetail({ route }) {
  const app = useApp();
  const store = D.storeById[route.id];
  if (!store) return <main className="page"><div className="empty">Store not found.</div></main>;
  const stage = app.stage;
  const status = window.storeStatusAt(store, stage);
  const f = D.FORMAT[store.format];
  const orders = (D.ordersByStore[store.id] || []);
  const shelf = D.shelf[store.id] || [];

  return (
    <main className="page">
      <a className="back" onClick={() => app.nav({ name: "stores" })}><Icons.arrowLeft size={15} />All stores</a>
      <div className="ph">
        <div>
          <div className="flex ic g10" style={{ marginBottom: 8 }}>
            <window.FormatBadge format={store.format} />
            <window.HealthPill status={status} />
          </div>
          <h1>{store.locality}</h1>
          <div className="sub">{store.name} · {store.region} · Manager: {store.manager} <span className="ref">{store.id}</span></div>
        </div>
      </div>

      {/* Format frames everything */}
      <div className="kv-grid">
        <div className="kv">
          <div className="kv-k">Format · {f.label}</div>
          <div className="kv-v">{f.note}</div>
        </div>
        <div className="kv">
          <div className="kv-k">SKU mix &amp; criticality</div>
          <div className="kv-v">{f.mix}. <span style={{ color: "var(--body)" }}>{f.crit}</span></div>
        </div>
      </div>

      <div className="grid2 mt24" style={{ alignItems: "start" }}>
        <section className="section" style={{ marginTop: 0 }}>
          <SectionHead title="Shelf-health estimate" count={shelf.length} />
          <div className="card"><div className="list">
            {shelf.map((it) => <ShelfHealthRow key={it.sku} item={it} />)}
          </div></div>
          <div className="mt8"><window.Prov muted>{store.format === "hospital" ? "Tighter thresholds — a ward needs it now." : "Inferred from sales pace, last delivery, and store reports."}</window.Prov></div>
        </section>

        <section className="section" style={{ marginTop: 0 }}>
          <SectionHead title="Dependent suppliers" count={store.suppliers.length} />
          <div className="card"><div className="list">
            {store.suppliers.map((id) => {
              const s = D.supplierById[id];
              return (
                <div key={id} className="row bare click" onClick={() => app.nav({ name: "supplier", id })}>
                  <div className="main">
                    <div className="title" style={{ fontSize: 14 }}>{s.name}</div>
                    <div className="meta">{s.kind}</div>
                  </div>
                  <div className="right"><span className={cx("rel-chip", s.reliability)}><span className="dot" />{s.reliability === "reliable" ? "Reliable" : s.reliability === "watch" ? "Watch" : "Slipping"}</span></div>
                </div>
              );
            })}
          </div></div>
        </section>
      </div>

      <section className="section">
        <SectionHead title="Key pending orders" count={orders.length} />
        <div className="card" style={{ overflow: "hidden" }}>
          <table className="t">
            <thead><tr><th>Order</th><th>SKU</th><th>Supplier</th><th className="right">Qty</th><th>Due</th><th>Status</th></tr></thead>
            <tbody>
              {orders.map((o) => (
                <tr key={o.id}>
                  <td className="mono" style={{ fontSize: 12 }}>{o.id}</td>
                  <td>{window.skuName(o.sku)}</td>
                  <td className="muted">{D.supplierById[o.supplierId].name}</td>
                  <td className="right tnum">{o.qty}</td>
                  <td className="muted">{window.shortDate(o.due)}</td>
                  <td><span className={cx("ord-status", o.status)}>{o.status}</span></td>
                </tr>
              ))}
              {!orders.length && <tr><td colSpan="6" className="empty">No pending orders.</td></tr>}
            </tbody>
          </table>
        </div>
      </section>

      <section className="section">
        <SectionHead title="Location" action={<span className="prov muted">{store.region}</span>} />
        <window.MapLocator store={store} />
      </section>
    </main>
  );
}

window.Pages = window.Pages || {};
window.Pages.Stores = StoresPage;
window.Pages.StoreDetail = StoreDetail;
