// Community section: live stats strip + recent activity feed + submission
// heatmap. (Curated people-cards section was removed.)

function fmtGap(ms) {
  const s = ms / 1000;
  if (s < 10) return `${s.toFixed(2)}s`;
  if (s < 60) return `${s.toFixed(1)}s`;
  const m = Math.floor(s / 60);
  return `${m}:${String(Math.round(s - m * 60)).padStart(2, "0")}`;
}

function CommunityStats() {
  useDataTick();
  const stats = window.RUN_DATA.communityStats;
  if (!stats) return null;

  const cells = [
    {
      label: "TRACKED RUNNERS",
      value: stats.uniqueRunners,
      sub: `across ${window.RUN_DATA.runs.length} levels`,
    },
    {
      label: "TOTAL RUNS",
      value: stats.totalSubmissions,
      sub: "submissions on speedrun.com",
    },
    stats.mostActive ? {
      label: "MOST ACTIVE",
      value: stats.mostActive.name,
      sub: `${stats.mostActive.runCount} runs · ${stats.mostActive.wrLevels.length || "—"} WR${stats.mostActive.wrLevels.length === 1 ? "" : "s"}`,
      accent: true,
    } : null,
    stats.mostCompetitive ? {
      label: "TIGHTEST PODIUM",
      value: stats.mostCompetitive.name,
      sub: `${fmtGap(stats.mostCompetitive.gap)} between #1 and #3`,
      accent: true,
    } : null,
  ].filter(Boolean);

  return (
    <div className="community__stats">
      {cells.map((c) => (
        <div key={c.label} className="community__stat">
          <div className="community__stat-label">{c.label}</div>
          <div className={`community__stat-value ${c.accent ? "is-accent" : ""}`}>{c.value}</div>
          <div className="community__stat-sub">{c.sub}</div>
        </div>
      ))}
    </div>
  );
}

function Community() {
  useDataTick();
  const stats = window.RUN_DATA.communityStats;
  if (!stats) return null;

  return (
    <section className="community" id="community">
      <SectionHead
        n="03"
        kicker="COMMUNITY"
        title="Runners, routers, and where they gather."
        sub="Mirror's Edge speedrunning is small and generous — these are the people and places shaping it."
      />

      <CommunityStats />

      <RecentActivity />
    </section>
  );
}

Object.assign(window, { Community, CommunityStats });
