// Recent activity feed — flat list of the latest leaderboard submissions
// across every tracked Mirror's Edge level, freshest first.
// Renders as a vertical ticker with up-to-the-minute relative times.

function RecentActivity() {
  useDataTick();
  const allItems = window.RUN_DATA.recentActivity;
  const [limit, setLimit] = React.useState(8);
  // Filter: "all" shows every recent submission; "podium" narrows to runs
  // that landed top-3 on their board. Reset the visible-count whenever the
  // filter flips so the user doesn't have to scroll past hidden rows.
  const [filter, setFilter] = React.useState("all");
  // Independently toggle whether obsolete rows (runs not on the
  // leaderboard because the same player has a faster PB) appear. Defaults
  // to ON so users see the full picture; clicking hides them.
  const [hideObsolete, setHideObsolete] = React.useState(false);
  const [ref, visible] = useReveal();

  const items = React.useMemo(() => {
    if (!Array.isArray(allItems)) return allItems;
    let out = allItems;
    if (filter === "podium") out = out.filter(r => r.place >= 1 && r.place <= 3);
    if (hideObsolete) out = out.filter(r => !r.obsoleted);
    return out;
  }, [allItems, filter, hideObsolete]);

  React.useEffect(() => { setLimit(8); }, [filter, hideObsolete]);

  // How many obsolete rows exist in the current filter view — surfaced in
  // the chip label so the user knows what they're toggling.
  const obsoleteCount = React.useMemo(() => {
    if (!Array.isArray(allItems)) return 0;
    const base = filter === "podium"
      ? allItems.filter(r => r.place >= 1 && r.place <= 3)
      : allItems;
    return base.filter(r => r.obsoleted).length;
  }, [allItems, filter]);

  if (!allItems || !allItems.length) {
    return (
      <div className="feed feed--empty">
        <div className="feed__head">
          <span className="feed__kicker">RECENT ACTIVITY</span>
          <span className="feed__live"><span className="feed__live-dot" /> LIVE</span>
        </div>
        <div className="feed__loading">Syncing with speedrun.com…</div>
      </div>
    );
  }

  const shown = items.slice(0, limit);
  const more = items.length - limit;

  return (
    <div className={`feed ${visible ? "rv" : ""}`} ref={ref}>
      <div className="feed__head">
        <span className="feed__kicker">RECENT ACTIVITY · ALL RUNNERS</span>
        <div className="feed__filter" role="tablist" aria-label="Filter recent activity">
          <button
            role="tab"
            aria-selected={filter === "all"}
            className={`feed__filter-btn ${filter === "all" ? "is-active" : ""}`}
            onClick={() => setFilter("all")}
          >All runs</button>
          <button
            role="tab"
            aria-selected={filter === "podium"}
            className={`feed__filter-btn ${filter === "podium" ? "is-active" : ""}`}
            onClick={() => setFilter("podium")}
          >Podiums only</button>
          {obsoleteCount > 0 && (
            <button
              type="button"
              aria-pressed={hideObsolete}
              className={`feed__filter-btn feed__filter-btn--toggle ${hideObsolete ? "is-active" : ""}`}
              onClick={() => setHideObsolete(v => !v)}
              title={hideObsolete
                ? `Click to show ${obsoleteCount} run${obsoleteCount === 1 ? "" : "s"} not on the leaderboard.`
                : `Hide ${obsoleteCount} run${obsoleteCount === 1 ? "" : "s"} the runner has since improved on.`}
            >
              {hideObsolete ? "Obsolete: hidden" : `Hide obsolete (${obsoleteCount})`}
            </button>
          )}
        </div>
        <span className="feed__live"><span className="feed__live-dot" /> LIVE</span>
      </div>
      {filter === "podium" && !items.length && (
        <div className="feed__loading">No top-3 finishes in the current window.</div>
      )}
      <ol className="feed__list">
        {shown.map((it, i) => {
          const ago = relativeTime(it.ts);
          // Top 3 get medal icons (matching the leaderboard); WR is "1st place"
          // here too — we no longer label it as "WR" since "WR" only really
          // applies if you're the world's first across an entire game/category,
          // and these are per-board top finishes.
          //
          // For rows that came from the game-wide /runs feed (boards we don't
          // have a full leaderboard for) `place` is null — we render a neutral
          // dot in that slot instead of a medal or rank number.
          const showMedal = it.place >= 1 && it.place <= 3;
          const placeClass = it.place ? `feed__item--p${it.place}` : "feed__item--noplace";
          const wrClass = it.place === 1 ? "is-wr" : "";
          // Show the category if it differs from the level name (full-game
          // runs) or if it's not the default "Any%" — keeps the line tight
          // for typical IL Glitchless rows while still disambiguating
          // "Any%" vs "Glitchless" on the same level.
          const showCat = it.categoryName && it.categoryName !== "Any%";
          return (
            <li key={i} className={`feed__item ${placeClass} ${it.isMe ? "is-me" : ""} ${wrClass}`}>
              <span className="feed__place">
                {showMedal ? <MedalIcon place={it.place} />
                  : it.place ? `#${it.place}`
                  : it.obsoleted ? <span className="feed__place-obs" title="This run isn’t on the leaderboard — the runner has a faster PB." aria-label="Superseded by a faster run from the same player">—</span>
                  : <span className="feed__place-dot" aria-hidden="true">·</span>}
              </span>
              <div className="feed__main">
                <span className="feed__line">
                  <a className="feed__runner"
                     href={it.runnerUrl || "#"}
                     target={it.runnerUrl ? "_blank" : undefined}
                     rel="noreferrer">{it.runner}</a>
                  <span className="feed__verb">on</span>
                  <span className="feed__level">{it.level}</span>
                  {showCat && <span className="feed__cat">{it.categoryName}</span>}
                </span>
                <span className="feed__sub">
                  <span className="feed__time">{it.time}</span>
                  <span className="feed__sep">·</span>
                  <span className="feed__when">{ago}</span>
                  {it.runUrl && <>
                    <span className="feed__sep">·</span>
                    <a className="feed__link" href={it.runUrl} target="_blank" rel="noreferrer">VOD ↗</a>
                  </>}
                </span>
              </div>
            </li>
          );
        })}
      </ol>
      {more > 0 && (
        <button className="feed__more" onClick={() => setLimit(limit + 12)}>
          Show {Math.min(more, 12)} more <span className="feed__more-count">({more} hidden)</span>
        </button>
      )}
    </div>
  );
}

Object.assign(window, { RecentActivity });
