/* ============================================================
   Companies — the company-profile browser (replaces the old Explore page).
   The home-style company cards (.hp-card) shown two ways:
     • no search  → a full-bleed 3-row auto-marquee (top/bottom drift →,
       middle drifts ←); pauses on hover. Reduced-motion → static grid.
     • searching  → a static grid filtered by name / country / commodity.
   Every figure reads from window.KESTREL_SUMMARY.companies — nothing baked
   in (see [[feedback_kestrel_no_hardcoded_stats]]). Unique top-level names
   (these babel scripts share one global lexical scope).
   ============================================================ */

/* Re-render once the async Kestrel summary lands (same pattern as home.jsx). */
const useCompaniesReady = () => {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => {
    if (window.KESTREL_SUMMARY) return;
    const on = () => force();
    window.addEventListener('strix-loaded', on);
    return () => window.removeEventListener('strix-loaded', on);
  }, []);
  return window.KESTREL_SUMMARY;
};

const _cpct = (n, d = 2) => (n == null ? '—' : Number(n).toFixed(d) + '%');
const _coReduce = () =>
  typeof window !== 'undefined' && window.matchMedia
    ? window.matchMedia('(prefers-reduced-motion: reduce)').matches
    : false;

/* Compact extraction count, e.g. 7533 → "7.5k", 943 → "943". */
const _fmtK = (n) =>
  n == null ? '' : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n);

/* Home-grid company card — mirrors home.jsx CompanyCard / the .hp-card look.
   The footer shows which data layers cover this company — Kestrel (passage
   classifications) and/or Strix (ESG metric extractions) — with the count of
   each. Strix only covers a subset, so its badge is conditional. */
const CoCard = ({ c, setRoute }) => {
  const hasKestrel = (c.n_passages || 0) > 0;
  // Strix coverage. Prefer the precise count from the full gated dataset when a paid
  // session has THIS company's observations loaded; otherwise fall back to the public
  // counts-only block (served to everyone). hasStrixData() only checks the static id
  // map — true for every mapped company even when no rows are loaded — so gating on it
  // made unloaded companies render a bogus "Strix 0" badge. Gate on real data instead.
  const cov = typeof window.strixCoverageFor === 'function' ? window.strixCoverageFor(c.id) : null;
  const fullObs = typeof window.strixObsForCompany === 'function' ? (window.strixObsForCompany(c.id) || []) : [];
  const strixN = fullObs.length || (cov ? cov.n : 0);
  const hasStrix = strixN > 0;
  const isDemo = window.isDemoCompany ? window.isDemoCompany(c.id) : false;
  const demoMode = window.isDemoMode ? window.isDemoMode() : false;
  return (
    <a href="#" className="hp-card co-card"
      onClick={(e) => { e.preventDefault(); setRoute({ page: 'company', id: c.id }); }}>
      <div className="hp-logo"><CompanyLogo id={c.id} /></div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
            {c.country} · {c.commodity}
          </span>
          {isDemo
            ? <span style={{ flex: '0 0 auto', display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: 999, background: 'rgba(166,225,94,0.16)', border: '1px solid rgba(166,225,94,0.45)', color: 'var(--moss-deep)', fontFamily: 'var(--mono)', fontSize: 9.5, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>Demo</span>
            : demoMode ? <Icon name="lock" size={11} style={{ flex: '0 0 auto', color: 'var(--ink-3)' }} /> : null}
        </div>
        <div className="hp-meta" style={{ marginTop: 10 }}>
          <div className="co-sources">
            {hasKestrel && (
              <span className="co-src co-src-kestrel" title={`${(c.n_passages || 0).toLocaleString()} passages classified by Kestrel`}>
                <span className="co-src-dot" />Kestrel<span className="co-src-n">{_fmtK(c.n_passages)}</span>
              </span>
            )}
            {hasStrix && (
              <span className="co-src co-src-strix" title={`${strixN.toLocaleString()} ESG metric extractions by Strix`}>
                <span className="co-src-dot" />Strix<span className="co-src-n">{_fmtK(strixN)}</span>
              </span>
            )}
          </div>
          <span className="co-card-go"><Icon name="arrow-right" size={14} /></span>
        </div>
      </div>
    </a>
  );
};

/* One repeating marquee unit, padded out so it always exceeds the viewport
   (otherwise a -50% loop would expose a gap on wide screens). */
const _CO_CARD_W = 320; // .hp-card 300 + 20px right margin
const _coLoopUnit = (slice) => {
  if (!slice.length) return slice;
  const reps = Math.max(2, Math.ceil(2200 / (slice.length * _CO_CARD_W)));
  const unit = [];
  for (let r = 0; r < reps; r++) unit.push(...slice);
  return unit; // the track renders this twice and slides -50% for a seamless loop
};

const CompanyMarquee = ({ companies, setRoute }) => {
  if (_coReduce()) {
    return (
      <div className="site-wrap">
        <div className="co-grid">{companies.map((c) => <CoCard key={c.id} c={c} setRoute={setRoute} />)}</div>
      </div>
    );
  }
  const per = Math.ceil(companies.length / 3);
  const rows = [companies.slice(0, per), companies.slice(per, per * 2), companies.slice(per * 2)];
  const dirs = ['right', 'left', 'right']; // top →, middle ←, bottom →
  return (
    <div className="co-marquee">
      {rows.map((row, i) => {
        if (!row.length) return null;
        const unit = _coLoopUnit(row);
        const dur = Math.round((unit.length * _CO_CARD_W) / 70); // ~70px/s, uniform across rows
        return (
          <div className="co-mq-row" key={i}>
            <div className={`co-mq-track co-mq-${dirs[i]}`} style={{ animationDuration: `${dur}s` }}>
              {unit.concat(unit).map((c, j) => <CoCard key={i + '-' + j} c={c} setRoute={setRoute} />)}
            </div>
          </div>
        );
      })}
    </div>
  );
};

const Companies = ({ setRoute }) => {
  const summary = useCompaniesReady();
  // Full directory = passage-classified companies ∪ Strix-only companies (Vale,
  // Glencore, Fortescue…). Live union, so every company with any data layer is
  // reachable here — not just the passage corpus. See data.jsx allPlatformCompanies.
  const companies = (typeof window.allPlatformCompanies === 'function')
    ? window.allPlatformCompanies()
    : ((summary && summary.companies) || []);
  const n = companies.length || (summary && summary.meta && summary.meta.n_companies) || null;

  const [q, setQ] = React.useState('');
  const query = q.trim().toLowerCase();
  const filtered = query
    ? companies.filter((c) => ((c.name || '') + ' ' + (c.country || '') + ' ' + (c.commodity || '')).toLowerCase().includes(query))
    : companies;

  return (
    <section className="section first">
      <div className="site-wrap">
        <div style={{ marginTop: 'clamp(26px, 4vw, 38px)' }}>
          <GooeyInput
            value={q}
            onValueChange={setQ}
            placeholder="Search a company, country or commodity…"
            collapsedLabel="Search companies"
            collapsedWidth={200}
            expandedWidth={380} />
        </div>
        {query && (
          <div className="co-count">{filtered.length} of {companies.length} {companies.length === 1 ? 'company' : 'companies'}</div>
        )}
      </div>

      {query ? (
        <div className="site-wrap">
          {filtered.length
            ? <div className="co-grid">{filtered.map((c) => <CoCard key={c.id} c={c} setRoute={setRoute} />)}</div>
            : <div className="co-empty">No companies match “{q.trim()}”.</div>}
        </div>
      ) : companies.length ? (
        <div style={{ marginTop: 'clamp(30px, 4vw, 46px)' }}>
          <CompanyMarquee companies={companies} setRoute={setRoute} />
        </div>
      ) : (
        <div className="site-wrap" style={{ marginTop: 30, color: 'var(--ink-3)', fontFamily: 'var(--mono)', fontSize: 13 }}>
          Loading companies…
        </div>
      )}
    </section>
  );
};
window.Companies = Companies;
