/* =============================================================
   CoreIQ Office — Shelf Marketplace (pharmacy side)
   List shelf spots from the Floor Planner, run live auctions,
   review & award bids, track earnings. Uses window.MARKET.
   Registers window.OFFICE_SCREENS.shelfMarket (+ detail).
   ============================================================= */
const { useState: smUseState, useEffect: smUseEffect, useMemo: smUseMemo } = React;

// CoreIQ group store identities in the marketplace
const MY_PH = ["PH-0001", "PH-0002", "PH-0003"];
const MY_STORES = [
  { id: "PH-0001", name: "CoreIQ Camberwell", state: "VIC", tier: "Large", metro: true },
  { id: "PH-0002", name: "CoreIQ Glen Iris", state: "VIC", tier: "Medium", metro: true },
  { id: "PH-0003", name: "CoreIQ Ringwood", state: "VIC", tier: "Medium", metro: true },
];
// preset fixtures (from the Floor & Shelf Planner) the pharmacy can list
const FIXTURES = [
  { fixtureLabel: "Gondola G3", bayLabel: "Bay 2 · eye + reach", position: "Eye level", category: "Pain Management", monthlySales: 5400, facings: 4 },
  { fixtureLabel: "End-cap E1", bayLabel: "Promotional end-cap", position: "End-cap", category: "Vitamins & Supplements", monthlySales: 4300, facings: 4 },
  { fixtureLabel: "Wall Bay W2", bayLabel: "Bay 3 · eye level", position: "Eye level", category: "Skin & Suncare", monthlySales: 3700, facings: 3 },
  { fixtureLabel: "Dispensary front", bayLabel: "Counter end-cap", position: "Counter", category: "Cough & Cold", monthlySales: 3100, facings: 2 },
  { fixtureLabel: "Gondola G1", bayLabel: "Bay 1 · eye level", position: "Eye level", category: "Allergy & Hayfever", monthlySales: 4600, facings: 3 },
  { fixtureLabel: "Front counter", bayLabel: "Impulse rack", position: "Counter", category: "Confectionery", monthlySales: 2400, facings: 2 },
];

function useMktSync() { const [, s] = smUseState(0); smUseEffect(() => window.MARKET.subscribe(() => s(n => n + 1)), []); }
function useMktTick() { const [, s] = smUseState(0); smUseEffect(() => { const id = setInterval(() => s(n => n + 1), 1000); return () => clearInterval(id); }, []); }

function smCountPill(id) {
  const M = window.MARKET; const st = M.effectiveStatus(M.listing(id));
  if (st === "awarded") return <span className="mkt-count mkt-count--awarded"><window.OIcon name="check-circle"/> Awarded</span>;
  if (st === "ended") return <span className="mkt-count mkt-count--ended"><window.OIcon name="clock"/> Closed</span>;
  return <span className={"mkt-count" + (st === "closing" ? " mkt-count--closing" : "")}><window.OIcon name="clock"/> {M.fmtTimeLeft(M.timeLeft(id))}</span>;
}
function SmShelfStrip({ facings }) {
  const n = Math.max(5, facings + 3); const hi = Math.floor(n / 2);
  return (<>{Array.from({ length: n }).map((_, i) => <div key={i} className={"mkt-shelf-box" + (i >= hi && i < hi + facings ? " mkt-shelf-box--hi" : "")} style={{ height: (40 + ((i * 37) % 45)) + "%" }}/>)}<div className="mkt-shelf-rail"/></>);
}
function smBidderAv(id, size = 30) {
  const b = window.MARKET.BIDDERS[id] || { short: "?", color: "var(--text-subtle)" };
  return <div className="mkt-bidhist-av" style={{ width: size, height: size, background: b.color }}>{b.short}</div>;
}

// =================================================================
// MAIN — tabbed
// =================================================================
function ShelfMarket() {
  const M = window.MARKET;
  const { setScreen, setScreenState, pushToast } = window.useOffice();
  useMktSync(); useMktTick();
  const [tab, setTab] = smUseState("live");
  const [creating, setCreating] = smUseState(false);

  const mine = M.listingsByPharmacy(MY_PH);
  const live = mine.filter(l => ["open", "closing"].includes(M.effectiveStatus(l)));
  const ended = mine.filter(l => M.effectiveStatus(l) === "ended");
  const awarded = mine.filter(l => M.effectiveStatus(l) === "awarded");

  const monthlyEarnings = awarded.reduce((s, l) => s + M.currentPrice(l.id), 0);
  const liveTopBids = live.reduce((s, l) => s + M.currentPrice(l.id), 0);

  function openListing(id) { setScreenState(s => ({ ...s, smListingId: id })); setScreen("shelfMarketListing"); }

  const TABS = [["live", "Live auctions", live.length], ["award", "Awaiting award", ended.length], ["earnings", "Earnings", awarded.length]];

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Shelf marketplace · earn from your space</span>
          <h2 className="off-screen-title">Shelf auctions</h2>
        </div>
        <div className="off-screen-actions">
          <button className="btn btn--primary" onClick={() => setCreating(true)}><window.OIcon name="plus"/> List a shelf spot</button>
        </div>
      </header>

      <div className="off-screen-body">
        <div className="mkt-stat-row" style={{ marginBottom: 16 }}>
          <div className="mkt-stat"><div className="mkt-stat-l">Live auctions</div><div className="mkt-stat-v">{live.length}</div><div className="mkt-stat-sub">{ended.length} awaiting award</div></div>
          <div className="mkt-stat"><div className="mkt-stat-l">Current top bids</div><div className="mkt-stat-v">{M.money(liveTopBids)}<small style={{ fontSize: 12, color: "var(--text-subtle)", fontWeight: 500 }}>/mo</small></div><div className="mkt-stat-sub">if awarded now</div></div>
          <div className="mkt-stat"><div className="mkt-stat-l">Monthly earnings</div><div className="mkt-stat-v">{M.money(monthlyEarnings)}<small style={{ fontSize: 12, color: "var(--text-subtle)", fontWeight: 500 }}>/mo</small></div><div className="mkt-stat-sub">{awarded.length} live placements</div></div>
          <div className="mkt-stat"><div className="mkt-stat-l">Annualised</div><div className="mkt-stat-v">{M.money(monthlyEarnings * 12)}</div><div className="mkt-stat-sub">from shelf space</div></div>
        </div>

        <div className="mfr-tabs" style={{ marginBottom: 18 }}>
          {TABS.map(([k, l, n]) => (
            <button key={k} className={"mfr-tab" + (tab === k ? " mfr-tab--active" : "")} onClick={() => setTab(k)}>{l}{n > 0 ? <span className="off-filter-count" style={{ marginLeft: 6 }}>{n}</span> : null}</button>
          ))}
        </div>

        {tab === "live" && (live.length ? (
          <div className="mkt-grid">
            {live.map(l => (
              <div key={l.id} className="mkt-card" onClick={() => openListing(l.id)}>
                <div className="mkt-shelf"><span className="mkt-shelf-tag">{l.fixtureLabel}</span><span className="mkt-shelf-pos">{l.position}</span><SmShelfStrip facings={l.facings}/></div>
                <div className="mkt-card-body">
                  <div className="mkt-card-top">
                    <div><div className="mkt-card-pharm">{l.pharmacy}</div><div className="mkt-card-loc">{l.bayLabel}</div></div>
                    <span className="mkt-card-cat">{l.category}</span>
                  </div>
                  <div className="mkt-sales"><span className="mkt-sales-v">{M.money(l.monthlySales)}/mo</span><span className="mkt-sales-l">category sales here</span></div>
                  <div className="mkt-meta-row"><span><b>{M.bidCount(l.id)}</b> bids</span><span><b>{M.uniqueBidders(l.id)}</b> bidders</span>{M.leader(l.id) && <span>leader <b>{M.BIDDERS[M.leader(l.id)].name}</b></span>}</div>
                  <div className="mkt-card-foot">
                    <div><div className="mkt-bid-now-l">{M.bidCount(l.id) ? "Top bid" : "Reserve"}</div><div className="mkt-bid-now-v">{M.money(M.currentPrice(l.id))}<small>/mo</small></div></div>
                    {smCountPill(l.id)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : <EmptyCard icon="tag" title="No live auctions" meta="List a shelf spot to start earning from your space."/>)}

        {tab === "award" && (ended.length ? (
          <div className="mfr-card">
            <div className="mfr-card-head"><div className="mfr-card-title">Closed auctions — award the winner</div></div>
            <div className="mfr-table">
              <div className="mfr-trow mfr-trow--head" style={{ gridTemplateColumns: "1.8fr 1fr 90px 120px 130px 110px" }}>
                <span>Position</span><span>Category</span><span style={{ textAlign: "right" }}>Bids</span><span>Top bidder</span><span style={{ textAlign: "right" }}>Winning bid</span><span/>
              </div>
              {ended.map(l => {
                const lead = M.leader(l.id);
                return (
                  <div key={l.id} className="mfr-trow mfr-trow--body" style={{ gridTemplateColumns: "1.8fr 1fr 90px 120px 130px 110px" }} onClick={() => openListing(l.id)}>
                    <div><div className="mfr-tstrong">{l.fixtureLabel}</div><div className="mfr-prod-sub">{l.pharmacy} · {l.position}</div></div>
                    <div className="mfr-tmuted">{l.category}</div>
                    <div className="mfr-tnum">{M.bidCount(l.id)}</div>
                    <div>{lead ? <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>{smBidderAv(lead, 24)} <span style={{ fontSize: 12.5 }}>{M.BIDDERS[lead].name}</span></span> : <span className="mfr-tmuted">No bids</span>}</div>
                    <div className="mfr-tnum mfr-tstrong">{lead ? M.money(M.currentPrice(l.id)) : "—"}</div>
                    <div style={{ textAlign: "right" }}>{lead ? <button className="btn btn--primary btn--sm" onClick={e => { e.stopPropagation(); M.award(l.id, lead); pushToast({ kind: "paid", icon: "check-circle", title: "Awarded to " + M.BIDDERS[lead].name, meta: l.fixtureLabel + " · " + M.money(M.currentPrice(l.id)) + "/mo" }); }}>Award</button> : <span className="mfr-tmuted" style={{ fontSize: 12 }}>—</span>}</div>
                  </div>
                );
              })}
            </div>
          </div>
        ) : <EmptyCard icon="check-circle" title="Nothing awaiting award" meta="Closed auctions with bids will appear here to award."/>)}

        {tab === "earnings" && (awarded.length ? (
          <div className="mfr-card">
            <div className="mfr-card-head"><div className="mfr-card-title">Live placements &amp; earnings</div><div className="mfr-card-sub mfr-card-action">{M.money(monthlyEarnings)}/mo total</div></div>
            <div className="mfr-table">
              <div className="mfr-trow mfr-trow--head" style={{ gridTemplateColumns: "1.8fr 1fr 130px 120px 110px" }}>
                <span>Position</span><span>Category</span><span>Manufacturer</span><span style={{ textAlign: "right" }}>$/mo</span><span style={{ textAlign: "right" }}>Term</span>
              </div>
              {awarded.map(l => (
                <div key={l.id} className="mfr-trow mfr-trow--body" style={{ gridTemplateColumns: "1.8fr 1fr 130px 120px 110px" }} onClick={() => openListing(l.id)}>
                  <div><div className="mfr-tstrong">{l.fixtureLabel}</div><div className="mfr-prod-sub">{l.pharmacy} · {l.position}</div></div>
                  <div className="mfr-tmuted">{l.category}</div>
                  <div style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>{smBidderAv(l.awardedTo, 24)} <span style={{ fontSize: 12.5 }}>{M.BIDDERS[l.awardedTo] ? M.BIDDERS[l.awardedTo].name : "—"}</span></div>
                  <div className="mfr-tnum mfr-tstrong" style={{ color: "var(--paid-text)" }}>{M.money(M.currentPrice(l.id))}</div>
                  <div className="mfr-tnum mfr-tmuted">{l.term}mo</div>
                </div>
              ))}
            </div>
          </div>
        ) : <EmptyCard icon="cash" title="No earnings yet" meta="Award a closed auction to start earning."/>)}
      </div>

      {creating && <CreateListing onClose={() => setCreating(false)} onCreate={(o) => { const l = M.createListing(o); setCreating(false); pushToast({ kind: "paid", icon: "check-circle", title: "Listing live", meta: l.fixtureLabel + " · reserve " + M.money(l.reserve) + "/mo" }); setTab("live"); }}/>}
    </div>
  );
}

function EmptyCard({ icon, title, meta }) {
  return <div className="mfr-card"><div className="empty" style={{ padding: 48 }}><div className="empty-icon"><window.OIcon name={icon} width={22} height={22}/></div><h4 className="empty-title">{title}</h4><p className="empty-meta">{meta}</p></div></div>;
}

// =================================================================
// CREATE LISTING (modal) — pick a fixture from the planner
// =================================================================
function CreateListing({ onClose, onCreate }) {
  const M = window.MARKET;
  const [storeId, setStoreId] = smUseState(MY_STORES[0].id);
  const [fxIdx, setFxIdx] = smUseState(0);
  const [rate, setRate] = smUseState(10);     // % of sales as reserve
  const [term, setTerm] = smUseState(6);
  const [days, setDays] = smUseState(3);
  const [catOnly, setCatOnly] = smUseState(true);
  const fx = FIXTURES[fxIdx];
  const store = MY_STORES.find(s => s.id === storeId);
  const reserve = Math.round(fx.monthlySales * rate / 100 / 5) * 5;

  function submit() {
    onCreate({
      pharmacyId: store.id, pharmacy: store.name, state: store.state, tier: store.tier, metro: store.metro,
      category: fx.category, fixtureLabel: fx.fixtureLabel, bayLabel: fx.bayLabel, position: fx.position,
      monthlySales: fx.monthlySales, facings: fx.facings, reserve, term, days,
      eligibility: { categoryOnly: catOnly },
    });
  }

  return (
    <div className="pd-modal-back" onClick={onClose}>
      <div className="pd-modal" style={{ width: 720 }} onClick={e => e.stopPropagation()}>
        <div className="pd-modal-head">
          <div><h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>List a shelf spot</h3><p style={{ margin: "3px 0 0", fontSize: 12.5, color: "var(--text-muted)" }}>Pick a fixture from your Floor &amp; Shelf Planner. The reserve is anchored on the category sales the position drives.</p></div>
          <button className="off-topbar-btn" onClick={onClose}><window.OIcon name="x"/></button>
        </div>
        <div className="pd-modal-body" style={{ gap: 16, maxHeight: "70vh", overflowY: "auto" }}>
          <div className="field">
            <label className="field-label">Store</label>
            <select className="input select" value={storeId} onChange={e => setStoreId(e.target.value)}>
              {MY_STORES.map(s => <option key={s.id} value={s.id}>{s.name} · {s.state}</option>)}
            </select>
          </div>

          <div className="field">
            <label className="field-label">Fixture &amp; position (from planner)</label>
            <div className="mkt-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)", gap: 10 }}>
              {FIXTURES.map((f, i) => (
                <div key={i} onClick={() => setFxIdx(i)} style={{ cursor: "pointer", border: "1px solid " + (i === fxIdx ? "var(--brand)" : "var(--border)"), borderRadius: 10, padding: "11px 13px", background: i === fxIdx ? "var(--brand-bg)" : "var(--surface)", boxShadow: i === fxIdx ? "0 0 0 3px var(--brand-bg)" : "none" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                    <span style={{ fontWeight: 600, fontSize: 13 }}>{f.fixtureLabel}</span>
                    <span className="mkt-card-cat" style={{ fontSize: 10 }}>{f.category}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 2 }}>{f.bayLabel} · {f.facings} facings</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "var(--paid-text)", marginTop: 6 }}>{M.money(f.monthlySales)}/mo <span style={{ fontSize: 11, fontWeight: 500, color: "var(--text-subtle)" }}>sales</span></div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            <div className="field">
              <label className="field-label">Reserve · {rate}% of sales</label>
              <input type="range" min="5" max="20" value={rate} onChange={e => setRate(+e.target.value)} style={{ width: "100%" }}/>
              <div style={{ fontSize: 18, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{M.money(reserve)}<span style={{ fontSize: 12, color: "var(--text-subtle)", fontWeight: 500 }}>/mo</span></div>
            </div>
            <div className="field">
              <label className="field-label">Term</label>
              <select className="input select" value={term} onChange={e => setTerm(+e.target.value)}>
                {[3, 6, 12].map(t => <option key={t} value={t}>{t} months</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Auction runs</label>
              <select className="input select" value={days} onChange={e => setDays(+e.target.value)}>
                {[1, 3, 5, 7].map(d => <option key={d} value={d}>{d} days</option>)}
              </select>
            </div>
          </div>

          <label className="checkbox" style={{ alignItems: "center" }}>
            <input type="checkbox" checked={catOnly} onChange={e => setCatOnly(e.target.checked)}/>
            <span className="checkbox-box"><window.OIcon name="check" width={14} height={14}/></span>
            <span>Restrict bidding to <strong>{fx.category}</strong> manufacturers</span>
          </label>
        </div>
        <div className="pd-modal-foot">
          <button className="btn btn--secondary" onClick={onClose}>Cancel</button>
          <button className="btn btn--primary" onClick={submit}><window.OIcon name="plus"/> Publish auction</button>
        </div>
      </div>
    </div>
  );
}

// =================================================================
// DETAIL — review bids & award
// =================================================================
function ShelfMarketListing() {
  const M = window.MARKET;
  const { screenState, setScreen, pushToast } = window.useOffice();
  useMktSync(); useMktTick();
  const id = screenState.smListingId;
  const l = M.listing(id);
  if (!l) return <div className="off-screen"><div className="off-screen-body">Listing not found.</div></div>;
  const st = M.effectiveStatus(l);
  const bids = M.bidsFor(id);
  const lead = M.leader(id);
  const maxSales = Math.max(...l.salesHistory, 1);
  const months = ["6mo", "5mo", "4mo", "3mo", "2mo", "Now"];

  function awardTo(bidder) { M.award(id, bidder); pushToast({ kind: "paid", icon: "check-circle", title: "Awarded to " + M.BIDDERS[bidder].name, meta: l.fixtureLabel + " · " + M.money(bids.find(b => b.bidder === bidder).amount) + "/mo" }); }

  return (
    <div className="off-screen">
      <header className="off-screen-header" style={{ paddingBottom: 14 }}>
        <div className="off-screen-header-meta" style={{ width: "100%" }}>
          <button className="mfr-back" onClick={() => setScreen("shelfMarket")} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-muted)", fontSize: 12.5, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 10 }}><window.OIcon name="chevron-right" width={13} height={13} style={{ transform: "rotate(180deg)" }}/> Shelf auctions</button>
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <h2 className="off-screen-title" style={{ margin: 0 }}>{l.fixtureLabel} · {l.category}</h2>
            <span className="mkt-card-cat">{l.pharmacy}</span>
            {smCountPill(id)}
          </div>
        </div>
      </header>

      <div className="off-screen-body">
        <div className="mkt-detail">
          <div className="mkt-detail-main">
            <div className="mkt-hero-shelf"><SmShelfStrip facings={l.facings}/><div className="mkt-hero-shelf-rail"/></div>
            <div className="mfr-card">
              <div className="mfr-card-head"><div><div className="mfr-card-title">Position value</div><div className="mfr-card-sub">Reserve is anchored on the category sales this spot drives</div></div></div>
              <div className="mfr-card-body">
                <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: 16 }}>
                  <div className="mkt-sales" style={{ flex: 1, minWidth: 200 }}><span className="mkt-sales-v">{M.money(l.monthlySales)}/mo</span><span className="mkt-sales-l">category sales from this position</span></div>
                  <div className="mkt-stat" style={{ flex: 1, minWidth: 160 }}><div className="mkt-stat-l">Reserve</div><div className="mkt-stat-v">{M.money(l.reserve)}<small style={{ fontSize: 12, fontWeight: 500, color: "var(--text-subtle)" }}>/mo</small></div><div className="mkt-stat-sub">{Math.round(l.reserve / l.monthlySales * 100)}% of sales</div></div>
                </div>
                <div className="mfr-section-label">Category sales · last 6 months</div>
                <div className="mkt-saleschart">
                  {l.salesHistory.map((v, i) => <div key={i} className="mkt-saleschart-col"><div className={"mkt-saleschart-bar" + (i < 5 ? " mkt-saleschart-bar--dim" : "")} style={{ height: (v / maxSales * 100) + "%" }}/><div className="mkt-saleschart-x">{months[i]}</div></div>)}
                </div>
              </div>
            </div>
            <div className="mfr-card">
              <div className="mfr-card-head"><div className="mfr-card-title">Position details</div></div>
              <div className="mfr-card-body">
                <div className="mkt-spec">
                  <div className="mkt-spec-row"><span className="mkt-spec-k">Fixture</span><span className="mkt-spec-v">{l.fixtureLabel}</span></div>
                  <div className="mkt-spec-row"><span className="mkt-spec-k">Bay</span><span className="mkt-spec-v">{l.bayLabel}</span></div>
                  <div className="mkt-spec-row"><span className="mkt-spec-k">Position</span><span className="mkt-spec-v">{l.position}</span></div>
                  <div className="mkt-spec-row"><span className="mkt-spec-k">Facings</span><span className="mkt-spec-v">{l.facings}</span></div>
                  <div className="mkt-spec-row"><span className="mkt-spec-k">Term</span><span className="mkt-spec-v">{l.term} months</span></div>
                  <div className="mkt-spec-row"><span className="mkt-spec-k">Eligibility</span><span className="mkt-spec-v">{l.eligibility.categoryOnly ? l.category + " only" : "Open"}</span></div>
                </div>
              </div>
            </div>
          </div>

          {/* side — bids + award */}
          <div className="mkt-detail-side">
            <div className="mkt-bidbox">
              <div className="mkt-bidbox-head">
                <div className="mkt-bidbox-count-l">{st === "awarded" ? "Awarded" : st === "ended" ? "Closed · review bids" : "Closes in"}</div>
                <div className={"mkt-bidbox-count" + (st === "closing" ? " is-closing" : "")}>{st === "awarded" ? "Done" : st === "ended" ? M.money(M.currentPrice(id)) : M.fmtTimeLeft(M.timeLeft(id))}</div>
              </div>
              <div className="mkt-bidbox-body">
                <div className="mkt-bidbox-cur">
                  <div><div className="mkt-bid-now-l">{M.bidCount(id) ? "Top bid" : "Reserve"}</div><div className="mkt-bidbox-cur-v">{M.money(M.currentPrice(id))}<small>/mo</small></div></div>
                  <div style={{ textAlign: "right" }}><div className="mkt-bid-now-l">Total contract</div><div className="mkt-bidbox-cur-v" style={{ fontSize: 18 }}>{M.money(M.currentPrice(id) * l.term)}</div></div>
                </div>
                {st === "awarded" ? (
                  <div className="mkt-status mkt-status--won" style={{ alignSelf: "flex-start" }}><window.OIcon name="check-circle" width={12} height={12}/> Awarded to {M.BIDDERS[l.awardedTo] ? M.BIDDERS[l.awardedTo].name : "—"}</div>
                ) : lead ? (
                  <>
                    <button className="btn btn--primary btn--block" onClick={() => awardTo(lead)}><window.OIcon name="check-circle"/> Award to {M.BIDDERS[lead].name}</button>
                    <div style={{ fontSize: 11.5, color: "var(--text-subtle)", lineHeight: 1.5 }}>{st === "ended" ? "Auction closed — award the highest bid, or pick another bidder below." : "You can award early to the current leader, or wait for close."}</div>
                  </>
                ) : <div style={{ fontSize: 13, color: "var(--text-subtle)" }}>No bids yet.</div>}
              </div>
            </div>

            <div className="mfr-card">
              <div className="mfr-card-head"><div className="mfr-card-title">Bids</div><div className="mfr-card-sub mfr-card-action">{bids.length} · {M.uniqueBidders(id)} bidders</div></div>
              <div className="mfr-card-body" style={{ paddingTop: 4, paddingBottom: 4 }}>
                {bids.length === 0 ? <div style={{ fontSize: 13, color: "var(--text-subtle)", padding: "12px 0" }}>No bids yet.</div> : (
                  <div className="mkt-bidhist">
                    {bids.map((b, i) => (
                      <div key={b.id} className={"mkt-bidhist-row" + (i === 0 ? " mkt-bidhist-row--top" : "")}>
                        {smBidderAv(b.bidder)}
                        <div><div className="mkt-bidhist-name">{M.BIDDERS[b.bidder].name}{i === 0 && <span className="mkt-bidhist-lead">High</span>}</div><div className="mkt-bidhist-when">{M.money(b.amount)}/mo</div></div>
                        {st !== "awarded" && <button className="btn btn--ghost btn--sm" style={{ marginLeft: "auto" }} onClick={() => awardTo(b.bidder)}>Award</button>}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, { shelfMarket: ShelfMarket, shelfMarketListing: ShelfMarketListing });
