Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(insights): show the brands around yours on the leaderboard, with the gap to the next

Cihane1350c5e798e
diff --git a/web/messages/en.json b/web/messages/en.json
index 9326b3c6b..3b03e1690 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1727,6 +1727,20 @@
"lowSample": "Low sample · {count, plural, one {# run} other {# runs}}",
"noRuns": "No runs this period",
"biggestDrop": "biggest drop"
+ },
+ "leaderboard": {
+ "title": "Leaderboard",
+ "headToHead": "Head-to-Head",
+ "you": "You",
+ "coverageSov": "Coverage {coverage} · SoV {sov}",
+ "scoreDetail": "Mentioned in {mentions} answers · cited in {citations} · position factor {factor}",
+ "more": "{count} more",
+ "moreLabel": "Show {count, plural, one {# more brand} other {# more brands}}",
+ "showAll": "Show all {count}",
+ "showLess": "Show less",
+ "gapTo": "{gap} pts to #{rank}",
+ "tiedWith": "Level with #{rank}",
+ "lever": "lever: {platform}"
}
},
"topics": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
index 3233b1477..bd4d3449b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
@@ -19,15 +19,12 @@ import {
Line,
} from 'recharts';
import type {
- CompetitorComparisonEntry,
ProviderComparisonRow,
VisibilityTrendPoint,
VisibilityRateTrendData,
SoVByPlatform,
} from '@/lib/actions/tracking';
import { getFaviconUrl } from '@/lib/favicon';
-import { formatCompactNumber } from '@/lib/format';
-import { Link } from '@/i18n/navigation';
// ─── Adaptive Y-axis ─────────────────────────────────────────────────────────
// Visibility scores are theoretically 0–100 but realistic values for most
@@ -411,120 +408,6 @@ export function VisibilityRateTrendChart({ data }: { data: VisibilityRateTrendDa
);
}
-const MAX_VISIBLE = 5;
-
-function LeaderboardEntry({ entry, rank }: { entry: CompetitorComparisonEntry; rank: number }) {
- return (
- <div
- className={`flex items-center gap-3 rounded-lg border px-3 py-2.5 ${
- entry.isOwnBrand ? 'border-primary/30 bg-primary/5' : ''
- }`}
- >
- <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-bold">
- {rank}
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- {entry.competitorId ? (
- <Link
- href={`/dashboard/competitors?competitor=${entry.competitorId}`}
- className="text-sm font-medium truncate hover:underline"
- >
- {entry.name}
- </Link>
- ) : (
- <span className="text-sm font-medium truncate">{entry.name}</span>
- )}
- {entry.isOwnBrand && <span className="text-[10px] font-medium text-primary">YOU</span>}
- </div>
- <div className="flex items-center gap-3 text-xs text-muted-foreground mt-0.5">
- <span>{formatCompactNumber(entry.totalMentions)} mentions</span>
- <span>{formatCompactNumber(entry.totalCitations)} citations</span>
- </div>
- <div className="flex items-center gap-3 text-xs text-muted-foreground mt-0.5">
- <span className="tabular-nums">
- appeared in {entry.visiblePrompts}/{entry.promptCount} prompts
- </span>
- </div>
- </div>
- <div className="flex flex-col items-end gap-0.5 shrink-0">
- <span
- className="text-sm font-semibold tabular-nums"
- title={`Mentioned in ${entry.mentionAnswers} answers · cited in ${entry.citationAnswers} · position factor ${
- entry.positionFactor === null ? '—' : entry.positionFactor.toFixed(2)
- }`}
- >
- {entry.score ?? '—'}
- </span>
- {entry.scoreChange !== null && entry.scoreChange !== 0 && (
- <span
- className={`text-[10px] font-medium tabular-nums ${
- entry.scoreChange > 0 ? 'text-green-500' : 'text-red-500'
- }`}
- >
- {entry.scoreChange > 0 ? '↑' : '↓'} {Math.abs(entry.scoreChange).toFixed(1)} pts
- </span>
- )}
- {entry.scoreChange === 0 && (
- <span className="text-[10px] font-medium tabular-nums text-muted-foreground">— 0</span>
- )}
- </div>
- </div>
- );
-}
-
-export function CompetitorLeaderboard({ data }: { data: CompetitorComparisonEntry[] }) {
- const [expanded, setExpanded] = useState(false);
-
- const needsTruncation = data.length > MAX_VISIBLE;
-
- const visibleEntries: { entry: CompetitorComparisonEntry; rank: number }[] = (() => {
- if (!needsTruncation || expanded) {
- return data.map((entry, i) => ({ entry, rank: i + 1 }));
- }
-
- const ownBrandIdx = data.findIndex((e) => e.isOwnBrand);
- const ownBrandInTop = ownBrandIdx >= 0 && ownBrandIdx < MAX_VISIBLE - 1;
-
- if (ownBrandInTop || ownBrandIdx < 0) {
- return data.slice(0, MAX_VISIBLE).map((entry, i) => ({ entry, rank: i + 1 }));
- }
-
- // Show top 4 + own brand at its actual rank
- const top = data.slice(0, MAX_VISIBLE - 1).map((entry, i) => ({ entry, rank: i + 1 }));
- top.push({ entry: data[ownBrandIdx], rank: ownBrandIdx + 1 });
- return top;
- })();
-
- return (
- <div className="space-y-2">
- {visibleEntries.map(({ entry, rank }, idx) => (
- <LeaderboardEntry
- key={`lb-${idx}-${rank}-${entry.isOwnBrand ? 'own' : entry.name}`}
- entry={entry}
- rank={rank}
- />
- ))}
- {needsTruncation && !expanded && (
- <button
- onClick={() => setExpanded(true)}
- className="w-full text-center text-xs font-medium text-muted-foreground hover:text-foreground py-2 transition-colors"
- >
- Show all ({data.length})
- </button>
- )}
- {expanded && (
- <button
- onClick={() => setExpanded(false)}
- className="w-full text-center text-xs font-medium text-muted-foreground hover:text-foreground py-2 transition-colors"
- >
- Show less
- </button>
- )}
- </div>
- );
-}
-
// ─── Share of Voice Charts ───────────────────────────────────────────────────
export function ShareOfVoicePlatformChart({
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsx
new file mode 100644
index 000000000..b076705db
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsx
@@ -0,0 +1,178 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { ArrowRight, ArrowUp } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { cn } from '@/lib/utils';
+import type { CompetitorComparisonEntry, ProviderComparisonRow } from '@/lib/actions/tracking';
+import { coverage } from '@/lib/insights-kpis';
+import {
+ leaderboardCallout,
+ leaderboardLines,
+ mentionShares,
+ type LeaderboardItem,
+ type PlatformTableRow,
+} from '@/lib/insights-summary';
+import { arrowChange, TONE_TEXT } from './kpi-format';
+
+/**
+ * The leaderboard (VIS-004), as in the v2 mockup: ranks 1 and 2, the brands
+ * around yours and "Show all"; each brand's score, change, Coverage and share
+ * of voice; and under your row, the gap to the brand ahead and the platform
+ * where it leads you most.
+ */
+export function Leaderboard({
+ brands,
+ providerRows,
+ platforms,
+ className,
+}: {
+ /** Brands in rank order, yours included. */
+ brands: CompetitorComparisonEntry[];
+ providerRows: ProviderComparisonRow[];
+ /** The By AI platform rows: only a platform with enough answers can be the lever. */
+ platforms: PlatformTableRow[] | null;
+ className?: string;
+}) {
+ const t = useTranslations('insights.leaderboard');
+ // Expanded for this board only: another brand or range starts collapsed.
+ const [expandedFor, setExpandedFor] = useState<CompetitorComparisonEntry[] | null>(null);
+ const expanded = expandedFor === brands;
+
+ const { items, hidden } = leaderboardLines(
+ brands.length,
+ brands.findIndex((b) => b.isOwnBrand),
+ );
+ const lines: LeaderboardItem[] = expanded
+ ? brands.map((_, index) => ({ kind: 'brand', index }))
+ : items;
+ const shares = mentionShares(brands);
+ const callout = leaderboardCallout(brands, providerRows, (name) =>
+ (platforms ?? []).some((p) => p.name === name && p.status === 'ok'),
+ );
+ const percent = (value: number | null) => (value === null ? '—' : `${value}%`);
+
+ return (
+ <Card className={className}>
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between gap-3">
+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>
+ <Link
+ href="/dashboard/competitors"
+ className="flex shrink-0 items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {t('headToHead')}
+ <ArrowRight className="h-3 w-3" />
+ </Link>
+ </div>
+ </CardHeader>
+ <CardContent>
+ <ul className="flex flex-col gap-1.5">
+ {lines.map((line, n) => {
+ if (line.kind === 'more') {
+ return (
+ <li key={`more-${n}`}>
+ <button
+ type="button"
+ onClick={() => setExpandedFor(brands)}
+ aria-label={t('moreLabel', { count: line.count })}
+ className="w-full py-0.5 text-center text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {t('more', { count: line.count })}
+ </button>
+ </li>
+ );
+ }
+
+ const entry = brands[line.index];
+ const change = arrowChange(entry.scoreChange);
+ return (
+ <li key={`${line.index}-${entry.competitorId ?? entry.name}`}>
+ <div
+ className={cn(
+ 'flex items-center gap-2.5 rounded-lg border px-3 py-2',
+ entry.isOwnBrand && 'border-foreground/20 bg-muted',
+ )}
+ >
+ <span className="w-5 shrink-0 text-center text-xs font-semibold tabular-nums text-muted-foreground">
+ {line.index + 1}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-1.5">
+ {entry.competitorId ? (
+ <Link
+ href={`/dashboard/competitors?competitor=${entry.competitorId}`}
+ className="truncate text-sm font-medium hover:underline"
+ >
+ {entry.name}
+ </Link>
+ ) : (
+ <span className="truncate text-sm font-medium">{entry.name}</span>
+ )}
+ {entry.isOwnBrand && (
+ <span className="shrink-0 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ {t('you')}
+ </span>
+ )}
+ </span>
+ <span className="block truncate text-xs tabular-nums text-muted-foreground">
+ {t('coverageSov', {
+ coverage: percent(coverage(entry.visiblePrompts, entry.promptCount)),
+ sov: percent(shares[line.index]),
+ })}
+ </span>
+ </span>
+ <span className="shrink-0 text-right">
+ <span
+ className="block text-sm font-semibold tabular-nums"
+ title={t('scoreDetail', {
+ mentions: entry.mentionAnswers,
+ citations: entry.citationAnswers,
+ factor:
+ entry.positionFactor === null ? '—' : entry.positionFactor.toFixed(2),
+ })}
+ >
+ {entry.score ?? '—'}
+ </span>
+ {change && (
+ <span
+ className={cn(
+ 'block text-[11px] font-medium tabular-nums',
+ TONE_TEXT[change.tone],
+ )}
+ >
+ {change.text}
+ </span>
+ )}
+ </span>
+ </div>
+ {entry.isOwnBrand && callout && (
+ <p className="ml-7 mt-1.5 inline-flex items-center gap-1.5 rounded-md bg-amber-100 px-2 py-0.5 text-[11.5px] text-amber-800 dark:bg-amber-950/50 dark:text-amber-300">
+ <ArrowUp className="h-3 w-3 shrink-0" aria-hidden />
+ <span>
+ {callout.gap === 0
+ ? t('tiedWith', { rank: callout.rank })
+ : t('gapTo', { gap: callout.gap, rank: callout.rank })}
+ {callout.lever && ` · ${t('lever', { platform: callout.lever })}`}
+ </span>
+ </p>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ {hidden > 0 && (
+ <button
+ type="button"
+ onClick={() => setExpandedFor(expanded ? null : brands)}
+ className="mt-1.5 w-full py-1 text-center text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {expanded ? t('showLess') : t('showAll', { count: brands.length })}
+ </button>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
index 3cd1ade63..afa319a43 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { formatWindowBound, lowerIsGood, signedChange, signedValue, upIsGood } from './kpi-format';
+import {
+ arrowChange,
+ formatWindowBound,
+ lowerIsGood,
+ signedChange,
+ signedValue,
+ upIsGood,
+} from './kpi-format';
describe('KPI card formatting', () => {
it('writes changes with a sign, and no change as ±0', () => {
@@ -27,6 +34,13 @@ describe('KPI card formatting', () => {
expect(lowerIsGood(0)).toEqual({ text: '±0', tone: 'neutral' });
});
+ it('writes a leaderboard change with an arrow', () => {
+ expect(arrowChange(4.1)).toEqual({ text: '↑ 4.1', tone: 'good' });
+ expect(arrowChange(-1.06)).toEqual({ text: '↓ 1.1', tone: 'bad' });
+ expect(arrowChange(0)).toEqual({ text: '±0', tone: 'neutral' });
+ expect(arrowChange(null)).toBeNull();
+ });
+
it('labels whole-day windows by their UTC days', () => {
// A day-only bound is the UTC day itself, whatever the viewer's zone.
expect(formatWindowBound('2026-08-16')).toBe('Aug 16, 2026');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
index d033672bf..578a3dd27 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
@@ -51,6 +51,16 @@ export function lowerIsGood(change: number | null): Change | null {
};
}
+/** A score change on the leaderboard, as in the v2 mockup: "↑ 4.1", "↓ 1.1", "±0". */
+export function arrowChange(change: number | null): Change | null {
+ if (change === null) return null;
+ if (change === 0) return { text: '±0', tone: 'neutral' };
+ return {
+ text: `${change > 0 ? '↑' : '↓'} ${Math.abs(change).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
+ tone: change > 0 ? 'good' : 'bad',
+ };
+}
+
/**
* A comparison-window bound for the "vs <range>" label. Whole-day windows
* come as 'YYYY-MM-DD' UTC days and are shown as those days; the 24h and
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 4f7bef6ca..6bd1cb5c6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -14,14 +14,6 @@ const VisibilityRateTrendChart = dynamic(
},
);
-const CompetitorLeaderboard = dynamic(
- () => import('./_charts').then((m) => m.CompetitorLeaderboard),
- {
- ssr: false,
- loading: () => <Skeleton className="h-64 w-full" />,
- },
-);
-
import { MetricBreakdownSheet } from './_metric-breakdown-sheet';
import { FormulaDialog } from './_formula-dialog';
import { useBrandStore } from '@/stores/use-brand-store';
@@ -95,6 +87,7 @@ import type { PlatformChange, PlatformTableRow } from '@/lib/insights-summary';
import { KpiRows } from './_kpi-cards';
import { SummaryLine } from './_summary-line';
import { PlatformTable } from './_platform-table';
+import { Leaderboard } from './_leaderboard';
// ─── Filter Types ─────────────────────────────────────────────────────────────
@@ -1472,23 +1465,12 @@ export default function InsightsPage() {
</CardContent>
</Card>
- <Card className="lg:col-span-2">
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between gap-3">
- <CardTitle className="text-sm font-medium">Leaderboard</CardTitle>
- <Link
- href="/dashboard/competitors"
- className="flex shrink-0 items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
- >
- Head-to-Head Comparison
- <ArrowRight className="h-3 w-3" />
- </Link>
- </div>
- </CardHeader>
- <CardContent>
- <CompetitorLeaderboard data={competitorData.brands} />
- </CardContent>
- </Card>
+ <Leaderboard
+ className="lg:col-span-2"
+ brands={competitorData.brands}
+ providerRows={competitorData.providerRows}
+ platforms={platforms}
+ />
</div>
) : (
<NoCompetitorsTeaser />
diff --git a/web/src/lib/insights-summary.test.ts b/web/src/lib/insights-summary.test.ts
index 96a23f019..e8cd3b794 100644
--- a/web/src/lib/insights-summary.test.ts
+++ b/web/src/lib/insights-summary.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest';
import { computeAiVisibilityScore } from './visibility-score';
import {
+ leaderboardCallout,
+ leaderboardLines,
+ mentionShares,
parsePlatformRows,
platformChanges,
platformMovers,
@@ -261,3 +264,88 @@ describe('platformTable', () => {
expect(table[0].shareOfVoice).toBeNull();
});
});
+
+describe('leaderboardLines', () => {
+ const lines = (count: number, own: number) => {
+ const { items, hidden } = leaderboardLines(count, own);
+ return {
+ lines: items.map((i) => (i.kind === 'brand' ? i.index + 1 : `${i.count} more`)),
+ hidden,
+ };
+ };
+
+ it('shows ranks 1 and 2, then the brands around yours, as in the mockup', () => {
+ expect(lines(20, 5)).toEqual({ lines: [1, 2, '2 more', 5, 6, 7], hidden: 15 });
+ });
+
+ it('skips nothing in between when the brand is near the top', () => {
+ expect(lines(8, 2)).toEqual({ lines: [1, 2, 3, 4], hidden: 4 });
+ expect(lines(8, 0)).toEqual({ lines: [1, 2], hidden: 6 });
+ });
+
+ it('shows the brand directly ahead when last', () => {
+ expect(lines(8, 7)).toEqual({ lines: [1, 2, '4 more', 7, 8], hidden: 4 });
+ });
+
+ it('lists short boards whole, and starts from the top without the brand', () => {
+ expect(lines(5, 4)).toEqual({ lines: [1, 2, 3, 4, 5], hidden: 0 });
+ expect(lines(8, -1)).toEqual({ lines: [1, 2, 3, 4, 5], hidden: 3 });
+ });
+});
+
+describe('mentionShares', () => {
+ it("gives each brand's share of every brand's mentions", () => {
+ expect(
+ mentionShares([{ totalMentions: 377 }, { totalMentions: 189 }, { totalMentions: 252 }]),
+ ).toEqual([46.1, 23.1, 30.8]);
+ expect(mentionShares([{ totalMentions: 0 }, { totalMentions: 0 }])).toEqual([null, null]);
+ });
+});
+
+describe('leaderboardCallout', () => {
+ const brand = (name: string, score: number, isOwnBrand = false) => ({ name, score, isOwnBrand });
+ const board = [
+ brand('Semrush', 36.3),
+ brand('Peec AI', 18.3),
+ brand('Ansvisor', 17.4, true),
+ brand('Otterly', 16.8),
+ ];
+ const rows = [
+ { provider: 'ChatGPT', 'Peec AI': 60, Ansvisor: 30 },
+ { provider: 'Gemini', 'Peec AI': 50, Ansvisor: 45 },
+ { provider: 'Grok', 'Peec AI': 90, Ansvisor: 0 },
+ ];
+
+ it('gives the gap to the brand ahead and where it leads most', () => {
+ expect(leaderboardCallout(board, rows, (p) => p !== 'Grok')).toEqual({
+ rank: 2,
+ gap: 0.9,
+ lever: 'ChatGPT',
+ });
+ });
+
+ it('names no lever where the brand ahead leads nowhere', () => {
+ expect(leaderboardCallout(board, rows, () => false)?.lever).toBeNull();
+ });
+
+ it('reads a tie with the brand ahead as a gap of 0', () => {
+ const level = [brand('Peec AI', 18.3), brand('Ansvisor', 18.3, true)];
+ expect(leaderboardCallout(level, rows, (p) => p !== 'Grok')).toEqual({
+ rank: 1,
+ gap: 0,
+ lever: 'ChatGPT',
+ });
+ });
+
+ it('counts a platform without a row for a brand as 0 there', () => {
+ expect(
+ leaderboardCallout(board, [{ provider: 'Copilot', 'Peec AI': 12 }], () => true)?.lever,
+ ).toBe('Copilot');
+ });
+
+ it('has no callout in first place, even when level with second', () => {
+ expect(
+ leaderboardCallout([brand('Ansvisor', 20, true), brand('Peec AI', 20)], rows, () => true),
+ ).toBeNull();
+ });
+});
diff --git a/web/src/lib/insights-summary.ts b/web/src/lib/insights-summary.ts
index 9f48cc8fb..7a937a6b0 100644
--- a/web/src/lib/insights-summary.ts
+++ b/web/src/lib/insights-summary.ts
@@ -1,5 +1,5 @@
import { computeAiVisibilityScore } from '@/lib/visibility-score';
-import { coverage } from '@/lib/insights-kpis';
+import { coverage, shareOfVoice } from '@/lib/insights-kpis';
/**
* The Insights summary line (VIS-006): the brand's rank and the gap to its
@@ -160,6 +160,90 @@ export function rankSummary(
};
}
+// ─── Leaderboard (VIS-004) ──────────────────────────────────────────────────
+
+/** Up to this many brands, the leaderboard lists them all. */
+const LEADERBOARD_SHOW_ALL_UP_TO = 5;
+
+/** A leaderboard line: a brand (its index in rank order), or "n more" skipped brands. */
+export type LeaderboardItem = { kind: 'brand'; index: number } | { kind: 'more'; count: number };
+
+/**
+ * The leaderboard's lines as in the v2 mockup: ranks 1 and 2, then the brand
+ * directly ahead of yours, yours and the one directly behind, with "n more"
+ * where brands are skipped in between. `hidden` counts every brand left out,
+ * for "Show all"; short lists, or one without the brand, start from the top.
+ */
+export function leaderboardLines(
+ count: number,
+ ownIndex: number,
+): { items: LeaderboardItem[]; hidden: number } {
+ const shown =
+ count <= LEADERBOARD_SHOW_ALL_UP_TO
+ ? [...Array(count).keys()]
+ : ownIndex < 0
+ ? [...Array(LEADERBOARD_SHOW_ALL_UP_TO).keys()]
+ : [...new Set([0, 1, ownIndex - 1, ownIndex, ownIndex + 1])]
+ .filter((i) => i >= 0 && i < count)
+ .sort((a, b) => a - b);
+
+ const items: LeaderboardItem[] = [];
+ shown.forEach((index, n) => {
+ const skipped = n > 0 ? index - shown[n - 1] - 1 : 0;
+ if (skipped > 0) items.push({ kind: 'more', count: skipped });
+ items.push({ kind: 'brand', index });
+ });
+ return { items, hidden: count - shown.length };
+}
+
+/**
+ * Each brand's share of voice: its mentions out of every tracked brand's,
+ * like the Share of Voice card. Null when nobody was mentioned.
+ */
+export function mentionShares(brands: { totalMentions: number }[]): (number | null)[] {
+ const all = brands.reduce((sum, b) => sum + b.totalMentions, 0);
+ return brands.map((b) => shareOfVoice(b.totalMentions, all - b.totalMentions));
+}
+
+export interface LeaderboardCallout {
+ /** The rank of the brand directly ahead. */
+ rank: number;
+ /** Points behind it, as the summary line says; 0 when level. */
+ gap: number;
+ /** The platform where it leads the brand most, if it leads anywhere. */
+ lever: string | null;
+}
+
+/**
+ * The note under the brand's row: the gap to the brand directly ahead and
+ * the platform to work on, the one where that brand appears in the largest
+ * share of prompts more than yours. Only platforms `eligible` says have
+ * enough answers count. Null when the brand leads the board.
+ */
+export function leaderboardCallout(
+ brands: { name: string; score: number | null; isOwnBrand: boolean }[],
+ providerRows: { provider: string; [brand: string]: string | number }[],
+ eligible: (platform: string) => boolean,
+): LeaderboardCallout | null {
+ // First place has nobody ahead (rankSummary would name the runner-up).
+ const rank = rankSummary(brands);
+ if (!rank || rank.rank === 1) return null;
+ const own = brands[rank.rank - 1].name;
+ const ahead = rank.neighbour.name;
+
+ let lever: string | null = null;
+ let lead = 0;
+ for (const row of providerRows) {
+ if (!eligible(row.provider)) continue;
+ const by = Number(row[ahead] ?? 0) - Number(row[own] ?? 0);
+ if (by > lead) {
+ lead = by;
+ lever = row.provider;
+ }
+ }
+ return { rank: rank.rank - 1, gap: rank.neighbour.gap, lever };
+}
+
// ─── By AI platform table (VIS-008) ─────────────────────────────────────────
export interface PlatformTableRow {