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(citations): Competitor Gaps — domains citing competitors but not us + per-competitor source map (#326)

Gökhan Geyikb2b72efe33e2
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
index 9f6cf92d4..f6a314b6e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
@@ -11,15 +11,26 @@ const DynamicSourceTypeDonutChart = dynamic(
loading: () => <Skeleton className="h-[200px] w-full" />,
},
);
-import { Quote, Globe, ExternalLink, Filter as FilterIcon, Layers } from 'lucide-react';
+import {
+ Quote,
+ Globe,
+ ExternalLink,
+ Filter as FilterIcon,
+ Layers,
+ Loader2,
+ Info,
+} from 'lucide-react';
import { useBrandStore } from '@/stores/use-brand-store';
import {
getCitationsOverview,
+ getCitationGaps,
type CitationsFilters,
type CitationsOverview,
type CitationDomainRow,
type CitationUrlRow,
type CitationsDatePreset,
+ type CitationGaps,
+ type CitationGapDomain,
} from '@/lib/actions/citations';
import { getTopics } from '@/lib/actions/topic';
import { getBrandPrompts } from '@/lib/actions/tracking';
@@ -759,6 +770,261 @@ function EmptyRows() {
);
}
+// ─── Competitor Gaps (#300) ───────────────────────────────────────────────────
+
+const GAP_METHODOLOGY =
+ 'Sources that appear in answers mentioning competitors but not you, weighted by how many sources each answer had.';
+
+function StrengthBar({ value, max }: { value: number; max: number }) {
+ const pct = max > 0 ? Math.round((value / max) * 100) : 0;
+ return (
+ <div className="h-1.5 w-20 rounded-full bg-muted overflow-hidden" title={`Strength ${pct}%`}>
+ <div className="h-full rounded-full bg-primary" style={{ width: `${Math.max(6, pct)}%` }} />
+ </div>
+ );
+}
+
+function DomainCell({ domain }: { domain: string }) {
+ return (
+ <div className="flex items-center gap-2 min-w-0">
+ <DomainFavicon domain={domain} />
+ <span className="truncate text-sm font-medium">{domain}</span>
+ <a
+ href={`https://${domain}`}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="inline-flex items-center text-muted-foreground hover:text-foreground"
+ aria-label={`Open ${domain} in a new tab`}
+ >
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </div>
+ );
+}
+
+function GapListTable({ rows }: { rows: CitationGapDomain[] }) {
+ if (rows.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center py-16 text-center">
+ <Layers className="h-8 w-8 text-muted-foreground/40 mb-3" />
+ <p className="text-sm font-medium">No gap domains for these filters</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Every domain citing a competitor also cites you, or there isn&apos;t enough data yet.
+ </p>
+ </div>
+ );
+ }
+ const max = rows[0]?.strength ?? 0;
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">Domain</TableHead>
+ <TableHead className="text-xs">Source type</TableHead>
+ <TableHead className="text-right text-xs">Competitor answers</TableHead>
+ <TableHead className="text-xs">Which competitors</TableHead>
+ <TableHead className="text-xs">Strength</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <TableRow key={row.domain}>
+ <TableCell>
+ <DomainCell domain={row.domain} />
+ </TableCell>
+ <TableCell>
+ <CategoryBadge category={row.category} />
+ </TableCell>
+ <TableCell className="text-right text-xs tabular-nums">
+ {row.competitorAnswers}
+ </TableCell>
+ <TableCell>
+ <div className="flex flex-wrap gap-1">
+ {row.competitors.map((c) => (
+ <Badge key={c} variant="outline" className="text-[10px] whitespace-nowrap">
+ {c}
+ </Badge>
+ ))}
+ </div>
+ </TableCell>
+ <TableCell>
+ <StrengthBar value={row.strength} max={max} />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ );
+}
+
+function ByCompetitorView({
+ gaps,
+ competitorId,
+ onSelect,
+}: {
+ gaps: CitationGaps;
+ competitorId: string;
+ onSelect: (id: string) => void;
+}) {
+ const rows = gaps.byCompetitor[competitorId] ?? [];
+ const max = rows[0]?.strength ?? 0;
+
+ if (gaps.competitors.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center py-16 text-center">
+ <Layers className="h-8 w-8 text-muted-foreground/40 mb-3" />
+ <p className="text-sm font-medium">No competitor source data yet</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Add competitors (with domains) and let a few tracking runs complete.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-muted-foreground">Competitor</span>
+ <Select
+ value={competitorId}
+ onValueChange={(v) => {
+ if (v) onSelect(v);
+ }}
+ >
+ <SelectTrigger className="h-8 w-56 text-xs">
+ <SelectValue placeholder="Select competitor" />
+ </SelectTrigger>
+ <SelectContent>
+ {gaps.competitors.map((c) => (
+ <SelectItem key={c.id} value={c.id}>
+ {c.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {rows.length === 0 ? (
+ <EmptyRows />
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">Domain</TableHead>
+ <TableHead className="text-xs">Source type</TableHead>
+ <TableHead className="text-right text-xs">Answers feeding</TableHead>
+ <TableHead className="text-center text-xs">Also cites us?</TableHead>
+ <TableHead className="text-xs">Strength</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <TableRow key={row.domain}>
+ <TableCell>
+ <DomainCell domain={row.domain} />
+ </TableCell>
+ <TableCell>
+ <CategoryBadge category={row.category} />
+ </TableCell>
+ <TableCell className="text-right text-xs tabular-nums">
+ {row.answersFeeding}
+ </TableCell>
+ <TableCell className="text-center">
+ <Badge
+ variant="outline"
+ className={cn(
+ 'text-[10px] whitespace-nowrap',
+ row.alsoCitesUs
+ ? 'border-emerald-500/30 text-emerald-700 dark:text-emerald-300'
+ : 'text-muted-foreground',
+ )}
+ >
+ {row.alsoCitesUs ? '✓ Yes' : '✗ No'}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <StrengthBar value={row.strength} max={max} />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </div>
+ );
+}
+
+function CompetitorGapsTab({ loading, gaps }: { loading: boolean; gaps: CitationGaps | null }) {
+ const [view, setView] = useState<'list' | 'byCompetitor'>('list');
+ // The user's pick; falls back to the first competitor (derived, no effect) so
+ // it stays valid when the gaps data changes under a filter switch.
+ const [picked, setPicked] = useState('');
+ const competitorId =
+ gaps && gaps.competitors.some((c) => c.id === picked)
+ ? picked
+ : (gaps?.competitors[0]?.id ?? '');
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-16">
+ <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+ if (!gaps) return <EmptyRows />;
+
+ return (
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="inline-flex rounded-md border p-0.5 text-xs">
+ <button
+ type="button"
+ onClick={() => setView('list')}
+ className={cn(
+ 'rounded px-2.5 py-1 transition-colors',
+ view === 'list'
+ ? 'bg-muted font-medium text-foreground'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ >
+ Gap list
+ </button>
+ <button
+ type="button"
+ onClick={() => setView('byCompetitor')}
+ className={cn(
+ 'rounded px-2.5 py-1 transition-colors',
+ view === 'byCompetitor'
+ ? 'bg-muted font-medium text-foreground'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ >
+ By competitor
+ </button>
+ </div>
+ <span
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground cursor-help"
+ title={GAP_METHODOLOGY}
+ >
+ <Info className="h-3.5 w-3.5" /> How this works
+ </span>
+ </div>
+
+ {gaps.lowVisibility && (
+ <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">
+ Your visibility is low in this window, so this list may be broad — focus on baseline
+ visibility first.
+ </div>
+ )}
+
+ {view === 'list' ? (
+ <GapListTable rows={gaps.gapDomains} />
+ ) : (
+ <ByCompetitorView gaps={gaps} competitorId={competitorId} onSelect={setPicked} />
+ )}
+ </div>
+ );
+}
+
// ─── Page ─────────────────────────────────────────────────────────────────────
function getDateRange(
@@ -798,6 +1064,40 @@ export default function CitationsPage() {
const activeBrandId = brand?.id ?? null;
+ const [sourceTab, setSourceTab] = useState<'domains' | 'urls' | 'gaps'>('domains');
+ const [gaps, setGaps] = useState<CitationGaps | null>(null);
+ const [gapsLoading, setGapsLoading] = useState(false);
+
+ const apiFilters = useMemo<CitationsFilters>(() => {
+ const { dateFrom, dateTo } = getDateRange(filters.datePreset, {
+ from: filters.dateFrom,
+ to: filters.dateTo,
+ });
+ return {
+ datePreset: filters.datePreset,
+ dateFrom,
+ dateTo,
+ platforms: filters.platform ? [filters.platform] : undefined,
+ regions: filters.region ? [filters.region] : undefined,
+ topicIds: filters.topic ? [filters.topic] : undefined,
+ promptIds: filters.prompt ? [filters.prompt] : undefined,
+ excludeOwnDomain: filters.excludeOwnDomain,
+ competitorOnly: filters.competitorOnly,
+ ownOnly: filters.ownOnly,
+ };
+ }, [
+ filters.datePreset,
+ filters.dateFrom,
+ filters.dateTo,
+ filters.platform,
+ filters.region,
+ filters.topic,
+ filters.prompt,
+ filters.excludeOwnDomain,
+ filters.competitorOnly,
+ filters.ownOnly,
+ ]);
+
useEffect(() => {
if (!activeBrandId) return;
getTopics(activeBrandId)
@@ -815,22 +1115,6 @@ export default function CitationsPage() {
}
setIsLoading(true);
try {
- const { dateFrom, dateTo } = getDateRange(filters.datePreset, {
- from: filters.dateFrom,
- to: filters.dateTo,
- });
- const apiFilters: CitationsFilters = {
- datePreset: filters.datePreset,
- dateFrom,
- dateTo,
- platforms: filters.platform ? [filters.platform] : undefined,
- regions: filters.region ? [filters.region] : undefined,
- topicIds: filters.topic ? [filters.topic] : undefined,
- promptIds: filters.prompt ? [filters.prompt] : undefined,
- excludeOwnDomain: filters.excludeOwnDomain,
- competitorOnly: filters.competitorOnly,
- ownOnly: filters.ownOnly,
- };
const overview = await getCitationsOverview(activeBrandId, apiFilters);
setData(overview);
@@ -854,24 +1138,33 @@ export default function CitationsPage() {
} finally {
setIsLoading(false);
}
- }, [
- activeBrandId,
- filters.datePreset,
- filters.dateFrom,
- filters.dateTo,
- filters.platform,
- filters.region,
- filters.topic,
- filters.prompt,
- filters.excludeOwnDomain,
- filters.competitorOnly,
- filters.ownOnly,
- ]);
+ }, [activeBrandId, apiFilters]);
useEffect(() => {
loadData();
}, [loadData]);
+ // Lazy-load Competitor Gaps only when its tab is active; re-fetch when the
+ // shared filters change while it's open.
+ useEffect(() => {
+ if (sourceTab !== 'gaps' || !activeBrandId) return;
+ let cancelled = false;
+ setGapsLoading(true);
+ getCitationGaps(activeBrandId, apiFilters)
+ .then((res) => {
+ if (!cancelled) setGaps(res);
+ })
+ .catch(() => {
+ if (!cancelled) setGaps(null);
+ })
+ .finally(() => {
+ if (!cancelled) setGapsLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [sourceTab, activeBrandId, apiFilters]);
+
const totals = data?.totals;
const kpis = useMemo(
() => [
@@ -945,7 +1238,10 @@ export default function CitationsPage() {
<CardTitle className="text-base">{t('sourcesTitle')}</CardTitle>
</CardHeader>
<CardContent>
- <Tabs defaultValue="domains">
+ <Tabs
+ value={sourceTab}
+ onValueChange={(v) => setSourceTab(v as 'domains' | 'urls' | 'gaps')}
+ >
<TabsList>
<TabsTrigger value="domains">
{t('tabDomains')} ({data?.totals.domains ?? 0})
@@ -953,6 +1249,7 @@ export default function CitationsPage() {
<TabsTrigger value="urls">
{t('tabUrls')} ({data?.totals.urls ?? 0})
</TabsTrigger>
+ <TabsTrigger value="gaps">Competitor Gaps</TabsTrigger>
</TabsList>
{/* keepMounted: data is already in memory, so mount both panels
once and make switching a pure CSS visibility toggle (#299). */}
@@ -962,6 +1259,9 @@ export default function CitationsPage() {
<TabsContent value="urls" keepMounted className="mt-4">
<UrlsTable rows={data?.urlRows ?? []} />
</TabsContent>
+ <TabsContent value="gaps" className="mt-4">
+ <CompetitorGapsTab loading={gapsLoading} gaps={gaps} />
+ </TabsContent>
</Tabs>
</CardContent>
</Card>
diff --git a/web/src/lib/actions/citations.ts b/web/src/lib/actions/citations.ts
index 51ad11f45..3e34aaa03 100644
--- a/web/src/lib/actions/citations.ts
+++ b/web/src/lib/actions/citations.ts
@@ -2,7 +2,7 @@
import { createClient } from '@/lib/supabase/server';
import { expandDateToEndOfDay } from '@/lib/dates';
-import type { Citation } from '@/types';
+import type { Citation, CompetitorMention } from '@/types';
import {
classifyDomain,
extractHostname,
@@ -364,3 +364,256 @@ export async function getCitationsOverview(
sourceTypeBreakdown,
};
}
+
+// ─── Competitor Gaps (#300) ─────────────────────────────────────────────────
+
+/** A third-party domain that cites competitors but never cites/mentions us. */
+export interface CitationGapDomain {
+ domain: string;
+ category: SourceCategory;
+ /** Distinct answers where this domain co-occurs with a competitor and we're absent. */
+ competitorAnswers: number;
+ /** Competitor display names seen alongside this domain (top few). */
+ competitors: string[];
+ /** Weighted co-occurrence score (each answer split across its distinct sources). */
+ strength: number;
+}
+
+/** A domain that feeds a specific competitor's AI visibility. */
+export interface CompetitorSourceDomain {
+ domain: string;
+ category: SourceCategory;
+ /** Distinct answers where the competitor is mentioned and this domain is cited. */
+ answersFeeding: number;
+ /** Whether this domain also appears in any answer where our brand is present. */
+ alsoCitesUs: boolean;
+ strength: number;
+}
+
+export interface CitationGapCompetitor {
+ id: string;
+ name: string;
+}
+
+export interface CitationGaps {
+ /** Outreach list: domains citing ≥1 competitor and never citing/mentioning us. */
+ gapDomains: CitationGapDomain[];
+ /** Per-competitor source map, keyed by competitor id. */
+ byCompetitor: Record<string, CompetitorSourceDomain[]>;
+ /** Competitors that have ≥1 feeding domain (for the selector). */
+ competitors: CitationGapCompetitor[];
+ /** Answers in the window where our brand was present. */
+ ourAnswerCount: number;
+ /** Total answers in the window. */
+ totalAnswers: number;
+ /** True when our presence is so low the gap list is likely too broad to act on. */
+ lowVisibility: boolean;
+}
+
+const GAP_MIN_COMPETITOR_ANSWERS = 2;
+const GAP_LOW_VISIBILITY_RATIO = 0.1;
+const GAP_MAX_ROWS = 100;
+const GAP_MAX_COMPETITOR_CHIPS = 6;
+
+/**
+ * Compute Competitor Gaps from the same `prompt_results` data the citations
+ * overview reads — no LLM/scraper calls, no new writes.
+ *
+ * For each AI answer we look at response-level co-occurrence: the set of cited
+ * domains, whether any competitor was mentioned, and whether we were present
+ * (our brand mentioned or one of our domains cited). A "gap" domain cites a
+ * competitor in an answer where we're absent and never appears in an answer
+ * where we're present. Each co-occurrence is weighted by `1 / distinct sources
+ * in the answer`, so a focused 2-source answer counts more than a 20-source one.
+ */
+export async function getCitationGaps(
+ brandId: string,
+ filters: CitationsFilters,
+): Promise<CitationGaps> {
+ const supabase = await createClient();
+
+ const { data: brandDomainRows } = await supabase
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId);
+ const brandDomains = (brandDomainRows ?? [])
+ .map((r) => normalizeDomain((r as { domain: string }).domain))
+ .filter(Boolean);
+
+ const { data: competitorRows } = await supabase
+ .from('competitors')
+ .select('id, name, domain')
+ .eq('brand_id', brandId);
+ const competitorList = (competitorRows ?? []) as Array<{
+ id: string;
+ name: string;
+ domain: string;
+ }>;
+ const competitorDomains = competitorList.map((c) => normalizeDomain(c.domain)).filter(Boolean);
+ const competitorNameById = new Map(
+ competitorList.map((c) => [c.id, (c.name || '').trim() || 'Competitor']),
+ );
+
+ const classifyCtx = { brandDomains, competitorDomains };
+
+ let query = supabase
+ .from('prompt_results')
+ .select('id, model_used, region, created_at, citations, competitor_mentions, mention_count')
+ .eq('brand_id', brandId);
+
+ const { from, to } = resolveDateRange(filters);
+ const expandedTo = expandDateToEndOfDay(to);
+ if (from) query = query.gte('created_at', from);
+ if (expandedTo) query = query.lte('created_at', expandedTo);
+ if (filters.platforms && filters.platforms.length > 0) {
+ query = applyModelFilter(query, filters.platforms);
+ }
+ if (filters.regions && filters.regions.length > 0) {
+ query = query.in('region', filters.regions);
+ }
+ if (filters.promptIds && filters.promptIds.length > 0) {
+ query = query.in('prompt_id', filters.promptIds);
+ }
+ if (filters.topicIds && filters.topicIds.length > 0) {
+ const { data: topicPrompts } = await supabase
+ .from('prompts')
+ .select('id')
+ .in('topic_id', filters.topicIds);
+ const topicPromptIds = ((topicPrompts ?? []) as { id: string }[]).map((p) => p.id);
+ query = query.in(
+ 'prompt_id',
+ topicPromptIds.length > 0 ? topicPromptIds : ['00000000-0000-0000-0000-000000000000'],
+ );
+ }
+
+ const { data: rows, error } = await query;
+ if (error) throw new Error(error.message);
+
+ const results = (rows ?? []) as Array<{
+ id: string;
+ citations: Citation[] | null;
+ competitor_mentions: CompetitorMention[] | null;
+ mention_count: number | null;
+ }>;
+
+ interface DomainAgg {
+ domain: string;
+ category: SourceCategory;
+ competitorAnswers: Set<string>;
+ appearsInOurAnswers: boolean;
+ strength: number;
+ competitorNames: Set<string>;
+ }
+ interface CompDomainAgg {
+ domain: string;
+ category: SourceCategory;
+ answersFeeding: Set<string>;
+ strength: number;
+ }
+
+ const domainMap = new Map<string, DomainAgg>();
+ const byCompMap = new Map<string, Map<string, CompDomainAgg>>();
+ let ourAnswerCount = 0;
+ const totalAnswers = results.length;
+
+ for (const r of results) {
+ const citations = Array.isArray(r.citations) ? r.citations : [];
+ const domainCat = new Map<string, SourceCategory>();
+ for (const cite of citations) {
+ const host = extractHostname(cite.url);
+ if (!host || domainCat.has(host)) continue;
+ domainCat.set(host, classifyDomain(host, classifyCtx));
+ }
+ // Weight each answer's co-occurrences by 1 / distinct sources so a focused
+ // answer counts more per domain than a sprawling multi-source one.
+ const weight = domainCat.size > 0 ? 1 / domainCat.size : 0;
+
+ const ourDomainCited = Array.from(domainCat.values()).some((cat) => cat === 'you');
+ const wePresent = (r.mention_count ?? 0) > 0 || ourDomainCited;
+ if (wePresent) ourAnswerCount += 1;
+
+ const mentions = Array.isArray(r.competitor_mentions) ? r.competitor_mentions : [];
+ const mentionedCompetitors = mentions.filter((m) => (m.mention_count ?? 0) > 0);
+ const competitorPresent = mentionedCompetitors.length > 0;
+ const competitorNamesInAnswer = mentionedCompetitors.map(
+ (m) => competitorNameById.get(m.competitor_id) ?? ((m.name || '').trim() || 'Competitor'),
+ );
+
+ for (const [domain, category] of domainCat) {
+ // Only third-party publications are actionable — skip our and competitor sites.
+ if (category === 'you' || category === 'competitor') continue;
+
+ const agg = domainMap.get(domain) ?? {
+ domain,
+ category,
+ competitorAnswers: new Set<string>(),
+ appearsInOurAnswers: false,
+ strength: 0,
+ competitorNames: new Set<string>(),
+ };
+ if (wePresent) agg.appearsInOurAnswers = true;
+ if (competitorPresent && !wePresent) {
+ agg.competitorAnswers.add(r.id);
+ agg.strength += weight;
+ for (const name of competitorNamesInAnswer) agg.competitorNames.add(name);
+ }
+ domainMap.set(domain, agg);
+
+ if (competitorPresent) {
+ for (const m of mentionedCompetitors) {
+ let perDomain = byCompMap.get(m.competitor_id);
+ if (!perDomain) {
+ perDomain = new Map<string, CompDomainAgg>();
+ byCompMap.set(m.competitor_id, perDomain);
+ }
+ const cd = perDomain.get(domain) ?? {
+ domain,
+ category,
+ answersFeeding: new Set<string>(),
+ strength: 0,
+ };
+ cd.answersFeeding.add(r.id);
+ cd.strength += weight;
+ perDomain.set(domain, cd);
+ }
+ }
+ }
+ }
+
+ const gapDomains: CitationGapDomain[] = Array.from(domainMap.values())
+ .filter((g) => !g.appearsInOurAnswers && g.competitorAnswers.size >= GAP_MIN_COMPETITOR_ANSWERS)
+ .map((g) => ({
+ domain: g.domain,
+ category: g.category,
+ competitorAnswers: g.competitorAnswers.size,
+ competitors: Array.from(g.competitorNames).sort().slice(0, GAP_MAX_COMPETITOR_CHIPS),
+ strength: Math.round(g.strength * 1000) / 1000,
+ }))
+ .sort((a, b) => b.strength - a.strength || b.competitorAnswers - a.competitorAnswers)
+ .slice(0, GAP_MAX_ROWS);
+
+ const byCompetitor: Record<string, CompetitorSourceDomain[]> = {};
+ for (const [competitorId, perDomain] of byCompMap) {
+ const list = Array.from(perDomain.values())
+ .map((cd) => ({
+ domain: cd.domain,
+ category: cd.category,
+ answersFeeding: cd.answersFeeding.size,
+ alsoCitesUs: domainMap.get(cd.domain)?.appearsInOurAnswers ?? false,
+ strength: Math.round(cd.strength * 1000) / 1000,
+ }))
+ .sort((a, b) => b.strength - a.strength || b.answersFeeding - a.answersFeeding)
+ .slice(0, GAP_MAX_ROWS);
+ if (list.length > 0) byCompetitor[competitorId] = list;
+ }
+
+ const competitors: CitationGapCompetitor[] = competitorList
+ .filter((c) => byCompetitor[c.id]?.length)
+ .map((c) => ({ id: c.id, name: competitorNameById.get(c.id) ?? c.name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ const lowVisibility =
+ totalAnswers > 0 && ourAnswerCount / totalAnswers < GAP_LOW_VISIBILITY_RATIO;
+
+ return { gapDomains, byCompetitor, competitors, ourAnswerCount, totalAnswers, lowVisibility };
+}