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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(citations): per-URL detail page with cited-in answers, prompt breakdown and owned-URL bridges (#535) (#556)
Gökhan Geyikb1eaa8514628
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsxindex 117fba7be..cb35826db 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx@@ -1,6 +1,6 @@'use client';-import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import dynamic from 'next/dynamic';const DynamicSourceTypeDonutChart = dynamic(@@ -18,12 +18,22 @@ import {Layers,Loader2,Info,- Plus,Download,} from 'lucide-react';import { toast } from 'sonner';import { useBrandStore } from '@/stores/use-brand-store';-import { addCompetitor } from '@/lib/actions/competitor';+import { Link } from '@/i18n/navigation';+import { AddCompetitorButton } from '@/components/citations/add-competitor-button';+import {+ CitationsFilterBar,+ DEFAULT_CITATIONS_FILTERS as DEFAULT_FILTERS,+ buildPlatformOptions,+ buildCitationDetailHref,+ getDateRange,+ type CitationsUIFilters as UIFilters,+ type PlatformOption,+ type PromptOption,+} from '@/components/citations/filter-bar';import {getCitationsOverview,getCitationGaps,@@ -38,21 +48,9 @@ import {} from '@/lib/actions/citations';import { getTopics } from '@/lib/actions/topic';import { getBrandPrompts } from '@/lib/actions/tracking';-import {- Combobox,- ComboboxCollection,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxItem,- ComboboxList,- ComboboxTrigger,- ComboboxValue,-} from '@/components/ui/combobox';import { toCsv } from '@/lib/csv';import type { Topic } from '@/types';import { SOURCE_CATEGORY_LABELS, type SourceCategory } from '@/lib/citations/classify';-import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';import {CategoryBadge,DomainFavicon,@@ -61,18 +59,8 @@ import {} from '@/components/citations/source-cells';import { PAGE_SIZE, TablePager, usePagination } from '@/components/table-pager';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';import {Select,SelectContent,@@ -91,12 +79,9 @@ import {} from '@/components/ui/table';import { Skeleton } from '@/components/ui/skeleton';import { cn } from '@/lib/utils';-import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';// ─── Constants ───────────────────────────────────────────────────────────────-const DATE_PRESETS: CitationsDatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];-const CATEGORY_COLORS: Record<SourceCategory, string> = {you: '#6366f1',competitor: '#f97316',@@ -108,93 +93,8 @@ const CATEGORY_COLORS: Record<SourceCategory, string> = {other: '#94a3b8',};-function getPlatformDisplayLabel(slug: string): string {- return (- MODEL_PROVIDER_LABELS[slug] ??- PLATFORM_LABELS[slug] ??- getAIProviderDisplayName(resolveAIProvider(slug))- );-}--function getGroupedPlatformLabel(value: string): string {- const firstSlug = value- .split(',')- .map((slug) => slug.trim())- .find(Boolean);- return firstSlug ? getPlatformDisplayLabel(firstSlug) : value;-}-// ─── Filter types ─────────────────────────────────────────────────────────────-interface UIFilters {- datePreset: CitationsDatePreset;- dateFrom: string;- dateTo: string;- platform: string;- region: string;- topic: string;- prompt: string;- excludeOwnDomain: boolean;- competitorOnly: boolean;- ownOnly: boolean;-}--interface PromptOption {- id: string;- text: string;-}--// base-ui's Combobox auto-uses `label` for display and `value` for selection-// when items are `{ value, label }` shaped — no extra helpers needed.-interface PromptComboboxItem {- value: string;- label: string;- /** Untruncated prompt text, shown as a native tooltip on hover (#298). */- fullText: string;-}--interface PlatformOption {- value: string;- label: string;-}--const DEFAULT_FILTERS: UIFilters = {- datePreset: '24h',- dateFrom: '',- dateTo: '',- platform: '',- region: '',- topic: '',- prompt: '',- excludeOwnDomain: false,- competitorOnly: false,- ownOnly: false,-};--function buildPlatformOptions(rows: CitationsOverview['rows']): PlatformOption[] {- const slugToLabel = new Map<string, string>();- for (const row of rows) {- for (const slug of row.models) {- if (!slug || slugToLabel.has(slug)) continue;- slugToLabel.set(slug, getPlatformDisplayLabel(slug));- }- }-- const familyToSlugs = new Map<string, string[]>();- for (const [slug, label] of slugToLabel) {- const slugs = familyToSlugs.get(label) ?? [];- slugs.push(slug);- familyToSlugs.set(label, slugs);- }-- return Array.from(familyToSlugs.entries())- .map(([label, slugs]) => ({- label,- value: slugs.sort().join(','),- }))- .sort((a, b) => a.label.localeCompare(b.label) || a.value.localeCompare(b.value));-}-// ─── Sub-components ───────────────────────────────────────────────────────────// ─── Donut ────────────────────────────────────────────────────────────────────@@ -274,243 +174,6 @@ function SourceTypeDonut({// ─── Filter bar ───────────────────────────────────────────────────────────────-function FilterBar({- filters,- onChange,- topics,- prompts,- platforms,- regions,-}: {- filters: UIFilters;- onChange: (patch: Partial<UIFilters>) => void;- topics: Topic[];- prompts: PromptOption[];- platforms: PlatformOption[];- regions: string[];-}) {- // base-ui Combobox needs `{ value, label }` shaped items so it can use the- // built-in filter and display logic without custom item-to-string helpers.- // Truncate long prompt text so the dropdown stays a sensible width.- const promptComboboxItems = useMemo<PromptComboboxItem[]>(- () =>- prompts.map((p) => ({- value: p.id,- // Let the combobox's CSS `truncate` handle visual overflow; keep the- // full text for the hover tooltip instead of slicing it away (#298).- label: p.text,- fullText: p.text,- })),- [prompts],- );-- return (- <div className="flex flex-wrap items-end gap-3">- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Date Range</label>- <div className="flex rounded-md border overflow-hidden">- {DATE_PRESETS.map((p) => (- <button- key={p}- type="button"- onClick={() => onChange({ datePreset: p })}- className={cn(- 'px-3 py-1.5 text-xs font-medium transition-colors',- filters.datePreset === p- ? 'bg-primary text-primary-foreground'- : 'bg-card hover:bg-muted text-foreground',- )}- >- {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}- </button>- ))}- </div>- </div>-- {filters.datePreset === 'custom' && (- <>- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>- <Input- type="date"- value={filters.dateFrom}- onChange={(e) => onChange({ dateFrom: e.target.value })}- className="h-8 w-36 text-xs"- />- </div>- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>- <Input- type="date"- value={filters.dateTo}- onChange={(e) => onChange({ dateTo: e.target.value })}- className="h-8 w-36 text-xs"- />- </div>- </>- )}-- {topics.length > 0 && (- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topic</label>- <Select- value={filters.topic || null}- onValueChange={(v) => onChange({ topic: !v || v === '__all__' ? '' : v })}- >- <SelectTrigger className="h-8 w-40 text-xs">- <SelectValue placeholder="All Topics">- {(value) =>- value && value !== '__all__'- ? (topics.find((t) => t.id === value)?.name ?? 'All Topics')- : 'All Topics'- }- </SelectValue>- </SelectTrigger>- <SelectContent>- <SelectItem value="__all__">All Topics</SelectItem>- {topics.map((t) => (- <SelectItem key={t.id} value={t.id}>- {t.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- )}-- {prompts.length > 0 && (- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Prompt</label>- <Combobox- items={promptComboboxItems}- value={- filters.prompt- ? (promptComboboxItems.find((item) => item.value === filters.prompt) ?? null)- : null- }- onValueChange={(item: PromptComboboxItem | null) =>- onChange({- prompt: !item || item.value === '__all__' ? '' : item.value,- })- }- >- <ComboboxTrigger className="h-8 w-56 text-xs">- <ComboboxValue placeholder="All Prompts" />- </ComboboxTrigger>- <ComboboxContent>- <ComboboxInput placeholder="Search prompts…" />- <ComboboxList>- <ComboboxEmpty>No prompts match.</ComboboxEmpty>- <ComboboxCollection>- {(item: PromptComboboxItem) => (- <ComboboxItem key={item.value} value={item} title={item.fullText}>- {item.label}- </ComboboxItem>- )}- </ComboboxCollection>- </ComboboxList>- </ComboboxContent>- </Combobox>- </div>- )}-- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Platform</label>- <Select- value={filters.platform || null}- onValueChange={(v) => onChange({ platform: !v || v === '__all__' ? '' : v })}- >- <SelectTrigger className="h-8 w-40 text-xs">- <SelectValue placeholder="All Platforms">- {(value) =>- value && value !== '__all__'- ? (platforms.find((platform) => platform.value === value)?.label ??- getGroupedPlatformLabel(value))- : 'All Platforms'- }- </SelectValue>- </SelectTrigger>- <SelectContent>- <SelectItem value="__all__">All Platforms</SelectItem>- {platforms.map((platform) => (- <SelectItem key={platform.value} value={platform.value}>- {platform.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Region</label>- <Select- value={filters.region || null}- onValueChange={(v) => onChange({ region: !v || v === '__all__' ? '' : v })}- >- <SelectTrigger className="h-8 w-32 text-xs">- <SelectValue placeholder="All Regions" />- </SelectTrigger>- <SelectContent>- <SelectItem value="__all__">All Regions</SelectItem>- {regions.map((r) => (- <SelectItem key={r} value={r}>- {r}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div className="flex items-center gap-2 pb-0.5">- <Button- type="button"- variant={filters.excludeOwnDomain ? 'default' : 'outline'}- size="sm"- className="h-8 text-xs"- onClick={() =>- onChange({- excludeOwnDomain: !filters.excludeOwnDomain,- ownOnly: false,- })- }- >- Exclude own domain- </Button>- <Button- type="button"- variant={filters.competitorOnly ? 'default' : 'outline'}- size="sm"- className="h-8 text-xs"- onClick={() =>- onChange({- competitorOnly: !filters.competitorOnly,- excludeOwnDomain: !filters.competitorOnly ? true : filters.excludeOwnDomain,- ownOnly: false,- })- }- >- Competitors only- </Button>- <Button- type="button"- variant={filters.ownOnly ? 'default' : 'outline'}- size="sm"- className="h-8 text-xs"- onClick={() =>- onChange({- ownOnly: !filters.ownOnly,- excludeOwnDomain: false,- competitorOnly: false,- })- }- >- Own domain only- </Button>- </div>- </div>- );-}-// ─── KPI Card ─────────────────────────────────────────────────────────────────function KpiCard({@@ -542,104 +205,6 @@ function KpiCard({// ─── Tables ───────────────────────────────────────────────────────────────────-/** Turn a domain into a first-guess competitor name, e.g. caranddriver.com → "Caranddriver". */-function deriveCompetitorName(domain: string): string {- const first = domain- .replace(/^www\./, '')- .split('.')[0]- ?.trim();- if (!first) return domain;- return first.charAt(0).toUpperCase() + first.slice(1);-}--/**- * Inline "+" on a Domains-table row: opens a confirm dialog pre-filled with a- * name derived from the domain, then adds it as a tracked competitor (#301).- */-function AddCompetitorButton({- brandId,- domain,- onAdded,-}: {- brandId: string;- domain: string;- onAdded: () => void;-}) {- const [open, setOpen] = useState(false);- const [name, setName] = useState('');- const [saving, setSaving] = useState(false);- const nameId = useId();-- function openDialog() {- setName(deriveCompetitorName(domain));- setOpen(true);- }-- async function handleAdd() {- const trimmed = name.trim();- if (!trimmed || saving) return;- setSaving(true);- try {- await addCompetitor(brandId, { name: trimmed, domain });- toast.success(`${domain} added as competitor`);- setOpen(false);- onAdded();- } catch {- toast.error('Could not add this domain as a competitor. Please try again.');- } finally {- setSaving(false);- }- }-- return (- <Dialog- open={open}- onOpenChange={(next) => {- if (!saving) setOpen(next);- }}- >- <Button- variant="ghost"- size="icon"- className="h-7 w-7"- onClick={openDialog}- aria-label={`Add ${domain} as competitor`}- title="Add as competitor"- >- <Plus className="h-3.5 w-3.5" />- </Button>- <DialogContent>- <DialogHeader>- <DialogTitle>Add {domain} as competitor?</DialogTitle>- <DialogDescription>- Track this domain as a competitor. You can edit the name below.- </DialogDescription>- </DialogHeader>- <div className="space-y-2">- <Label htmlFor={nameId}>Name</Label>- <Input- id={nameId}- value={name}- onChange={(e) => setName(e.target.value)}- onKeyDown={(e) => e.key === 'Enter' && handleAdd()}- placeholder="Competitor name"- autoFocus- />- </div>- <DialogFooter>- <Button variant="outline" onClick={() => setOpen(false)} disabled={saving}>- Cancel- </Button>- <Button onClick={handleAdd} disabled={!name.trim() || saving} className="gap-2">- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}- Add- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-}-const DomainsTable = memo(function DomainsTable({rows,brandId,@@ -800,15 +365,25 @@ const UrlsTable = memo(function UrlsTable({<div className="flex items-start gap-2 min-w-0"><DomainFavicon domain={row.domain} /><div className="flex min-w-0 max-w-[480px] flex-col">- <a- href={row.url}- target="_blank"- rel="noreferrer noopener"- className="truncate text-sm font-medium text-foreground hover:underline"- title={row.title || row.url}- >- {row.title || row.url}- </a>+ <div className="flex items-center gap-1.5 min-w-0">+ <Link+ href={buildCitationDetailHref(row.url, filters)}+ className="truncate text-sm font-medium text-foreground hover:underline"+ title={row.title || row.url}+ >+ {row.title || row.url}+ </Link>+ <a+ href={row.url}+ target="_blank"+ rel="noreferrer noopener"+ className="shrink-0 text-muted-foreground hover:text-foreground"+ aria-label="Open cited page in a new tab"+ title="Open cited page"+ >+ <ExternalLink className="h-3 w-3" />+ </a>+ </div><div className="flex items-center gap-1.5 pt-0.5"><span className="truncate text-[11px] text-muted-foreground">{row.domain}@@ -1177,28 +752,6 @@ function CompetitorGapsTab({ loading, gaps }: { loading: boolean; gaps: Citation// ─── Page ─────────────────────────────────────────────────────────────────────-function getDateRange(- preset: CitationsDatePreset,- custom: { from: string; to: string },-): { dateFrom?: string; dateTo?: string } {- if (preset === 'all') return {};- if (preset === 'custom') {- return {- dateFrom: custom.from || undefined,- dateTo: custom.to ? `${custom.to}T23:59:59.999Z` : undefined,- };- }- if (preset === '24h') {- const from = new Date();- from.setHours(from.getHours() - 24);- return { dateFrom: from.toISOString() };- }- const days = preset === '7d' ? 7 : preset === '30d' ? 30 : 90;- const from = new Date();- from.setDate(from.getDate() - days);- return { dateFrom: from.toISOString() };-}-function triggerDownload(csv: string, filename: string) {const blob = new Blob([csv], {type: 'text/csv;charset=utf-8;',@@ -1475,7 +1028,7 @@ export default function CitationsPage() {</Button></div>- <FilterBar+ <CitationsFilterBarfilters={filters}onChange={(patch) => setFilters((f) => ({ ...f, ...patch }))}topics={topics}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsxnew file mode 100644index 000000000..fd8f79255--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsx@@ -0,0 +1,561 @@+'use client';++/**+ * Per-URL citation detail page (#535): everything one cited URL is doing for+ * the brand — the answers citing it, the prompts triggering it and, for+ * brand-owned URLs, the targeting + AI-referred traffic bridges. Keyed by+ * `?u=<encoded-url>`; scoped by the shared citations filter bar so counts+ * agree with the overview for the same URL, window and filters.+ */++import { useCallback, useEffect, useMemo, useState } from 'react';+import { useSearchParams } from 'next/navigation';+import { Link } from '@/i18n/navigation';+import { useBrandStore } from '@/stores/use-brand-store';+import {+ getCitationUrlDetail,+ type CitationsDatePreset,+ type CitationsFilters,+ type CitationUrlDetail,+} from '@/lib/actions/citations';+import {+ CitationsFilterBar,+ DEFAULT_CITATIONS_FILTERS,+ buildPlatformOptions,+ getDateRange,+ getPlatformDisplayLabel,+ type CitationsUIFilters,+} from '@/components/citations/filter-bar';+import { AddCompetitorButton } from '@/components/citations/add-competitor-button';+import { CategoryBadge, DomainFavicon, PlatformsCell } from '@/components/citations/source-cells';+import { TablePager, usePagination } from '@/components/table-pager';+import { Badge } from '@/components/ui/badge';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import {+ ArrowLeft,+ Check,+ Clock,+ ExternalLink,+ Layers,+ ListChecks,+ MessagesSquare,+ Quote,+ Target,+ TrendingUp,+} from 'lucide-react';+import { cn } from '@/lib/utils';++const CITED_IN_PAGE_SIZE = 10;+const DATE_PRESET_VALUES: CitationsDatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];++function formatDate(iso: string | null): string {+ if (!iso) return '—';+ return new Date(iso).toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ });+}++function KpiCard({+ title,+ value,+ sub,+ icon: Icon,+}: {+ title: string;+ value: string;+ sub: string;+ icon: React.ComponentType<{ className?: string }>;+}) {+ return (+ <Card>+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-1">+ <CardTitle className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ {title}+ </CardTitle>+ <Icon className="h-3.5 w-3.5 text-muted-foreground" />+ </CardHeader>+ <CardContent>+ <div className="text-2xl font-bold tabular-nums truncate">{value}</div>+ <p className="text-xs mt-1 text-muted-foreground truncate">{sub}</p>+ </CardContent>+ </Card>+ );+}++function SentimentBadge({ sentiment }: { sentiment: string | null }) {+ if (!sentiment) return <span className="text-xs text-muted-foreground">—</span>;+ return (+ <Badge+ variant="outline"+ className={cn(+ 'text-[10px] font-medium capitalize',+ sentiment === 'positive' &&+ 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',+ sentiment === 'negative' &&+ 'border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300',+ )}+ >+ {sentiment}+ </Badge>+ );+}++/** "Early · #2 of 7" — where in the answer the URL's first citation sits. */+function PositionCell({ rank, totalSources }: { rank: number; totalSources: number }) {+ const ratio = totalSources > 1 ? (rank - 1) / (totalSources - 1) : 0;+ const tone = ratio <= 1 / 3 ? 'Early' : ratio >= 2 / 3 ? 'Late' : 'Mid';+ return (+ <span className="text-xs tabular-nums whitespace-nowrap">+ <span+ className={cn(+ 'font-medium',+ tone === 'Early' && 'text-emerald-600 dark:text-emerald-400',+ tone === 'Late' && 'text-amber-600 dark:text-amber-400',+ )}+ >+ {tone}+ </span>+ <span className="text-muted-foreground">+ {' '}+ · #{rank} of {totalSources}+ </span>+ </span>+ );+}++export default function CitationUrlDetailPage() {+ const { getActiveBrand } = useBrandStore();+ const brand = getActiveBrand();+ const searchParams = useSearchParams();+ const targetUrl = searchParams.get('u') ?? '';++ const [filters, setFilters] = useState<CitationsUIFilters>(() => {+ const presetParam = searchParams.get('preset');+ const preset = DATE_PRESET_VALUES.includes(presetParam as CitationsDatePreset)+ ? (presetParam as CitationsDatePreset)+ : DEFAULT_CITATIONS_FILTERS.datePreset;+ return {+ ...DEFAULT_CITATIONS_FILTERS,+ datePreset: preset,+ dateFrom: searchParams.get('from') ?? '',+ dateTo: searchParams.get('to') ?? '',+ platform: searchParams.get('platform') ?? '',+ region: searchParams.get('region') ?? '',+ };+ });+ const [data, setData] = useState<CitationUrlDetail | null>(null);+ const [loading, setLoading] = useState(true);+ const [loadFailed, setLoadFailed] = useState(false);++ const activeBrandId = brand?.id ?? null;+ const filterKey = JSON.stringify(filters);+ const citedInPager = usePagination(data?.occurrences.length ?? 0, filterKey, CITED_IN_PAGE_SIZE);++ 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,+ };+ }, [filters.datePreset, filters.dateFrom, filters.dateTo, filters.platform, filters.region]);++ const loadData = useCallback(async () => {+ if (!activeBrandId || !targetUrl) {+ setLoading(false);+ return;+ }+ setLoading(true);+ setLoadFailed(false);+ try {+ setData(await getCitationUrlDetail(activeBrandId, targetUrl, apiFilters));+ } catch {+ setData(null);+ setLoadFailed(true);+ } finally {+ setLoading(false);+ }+ }, [activeBrandId, targetUrl, apiFilters]);++ useEffect(() => {+ loadData();+ }, [loadData]);++ const platformOptions = useMemo(+ () => (data ? buildPlatformOptions([{ models: data.totals.models }]) : []),+ [data],+ );++ const pageOccurrences = data?.occurrences.slice(citedInPager.start, citedInPager.end) ?? [];++ if (!targetUrl) {+ return (+ <div className="space-y-4">+ <BackLink />+ <p className="text-sm text-muted-foreground">+ No URL provided. Open this page from a citation row on the Citations page.+ </p>+ </div>+ );+ }++ if (!brand) {+ return (+ <div className="space-y-4">+ <BackLink />+ <p className="text-sm text-muted-foreground">Select a brand from the top switcher first.</p>+ </div>+ );+ }++ return (+ <div className="space-y-6">+ <div>+ <BackLink />+ {/* Header */}+ <div className="mt-2 flex flex-wrap items-start justify-between gap-3">+ <div className="flex items-start gap-3 min-w-0">+ <div className="pt-1">+ <DomainFavicon domain={data?.domain || extractDisplayHost(targetUrl)} />+ </div>+ <div className="min-w-0">+ <h1 className="text-xl font-bold tracking-tight leading-tight break-all">+ {data?.title || targetUrl}+ </h1>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <a+ href={targetUrl}+ target="_blank"+ rel="noreferrer noopener"+ className="inline-flex max-w-[560px] items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline"+ >+ <span className="truncate">{targetUrl}</span>+ <ExternalLink className="h-3 w-3 shrink-0" />+ </a>+ {data && <CategoryBadge category={data.category} />}+ {data?.articleType && (+ <Badge variant="outline" className="text-[10px] font-medium">+ {data.articleType}+ </Badge>+ )}+ </div>+ </div>+ </div>+ <div className="shrink-0">+ {data &&+ (data.category === 'you' ? (+ <Badge className="bg-indigo-500/10 text-indigo-700 dark:text-indigo-300 border-indigo-500/30 border">+ Owned+ </Badge>+ ) : (+ <AddCompetitorButton+ brandId={brand.id}+ domain={data.domain}+ onAdded={loadData}+ appearance="button"+ />+ ))}+ </div>+ </div>+ </div>++ {/* Filters */}+ <CitationsFilterBar+ filters={filters}+ onChange={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}+ platforms={platformOptions}+ regions={[]}+ showCategoryToggles={false}+ />++ {loading ? (+ <div className="space-y-4">+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-[104px]" />+ ))}+ </div>+ <Skeleton className="h-[320px]" />+ </div>+ ) : !data || data.totals.answers === 0 ? (+ <Card>+ <CardContent className="py-16 text-center text-sm text-muted-foreground">+ {loadFailed+ ? 'Could not load this URL — please try again.'+ : 'No citations recorded for this URL in the selected window.'}+ </CardContent>+ </Card>+ ) : (+ <>+ {/* KPI strip */}+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">+ <KpiCard+ title="Total citations"+ value={data.totals.citations.toLocaleString()}+ sub={`across ${data.totals.answers} answers`}+ icon={Quote}+ />+ <KpiCard+ title="Answers citing"+ value={data.totals.answers.toLocaleString()}+ sub="AI answers include this URL"+ icon={MessagesSquare}+ />+ <KpiCard+ title="Prompts"+ value={data.totals.prompts.toLocaleString()}+ sub="distinct prompts triggering it"+ icon={ListChecks}+ />+ <KpiCard+ title="Platforms"+ value={String(+ new Set(data.totals.models.map((m) => getPlatformDisplayLabel(m))).size,+ )}+ sub={Array.from(new Set(data.totals.models.map((m) => getPlatformDisplayLabel(m))))+ .sort()+ .join(', ')}+ icon={Layers}+ />+ <KpiCard+ title="Last seen"+ value={formatDate(data.totals.lastSeen)}+ sub={`first seen ${formatDate(data.totals.firstSeen)}`}+ icon={Clock}+ />+ </div>++ {/* Owned-URL bridges */}+ {data.owned && (+ <div className="grid gap-4 lg:grid-cols-2">+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium flex items-center gap-2">+ <Target className="h-4 w-4" />+ Targeted in {data.owned.targetingPrompts.length} prompt+ {data.owned.targetingPrompts.length === 1 ? '' : 's'}+ </CardTitle>+ <p className="text-xs text-muted-foreground">+ Prompts tracking this URL as a target in the prompt workflow+ </p>+ </CardHeader>+ <CardContent>+ {data.owned.targetingPrompts.length === 0 ? (+ <p className="py-6 text-center text-sm text-muted-foreground">+ Not targeted yet — add it from a prompt's Target URLs card.+ </p>+ ) : (+ <ul className="divide-y">+ {data.owned.targetingPrompts.map((tp) => (+ <li key={tp.promptId} className="flex items-center gap-3 py-2">+ <Link+ href={`/dashboard/prompts/${tp.promptId}`}+ className="flex-1 truncate text-sm hover:underline"+ title={tp.promptText}+ >+ {tp.promptText}+ </Link>+ {tp.label && (+ <Badge variant="outline" className="text-[10px] shrink-0">+ {tp.label}+ </Badge>+ )}+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">+ cited {tp.citedCount}×+ </span>+ </li>+ ))}+ </ul>+ )}+ </CardContent>+ </Card>+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium flex items-center gap-2">+ <TrendingUp className="h-4 w-4" />+ AI-referred visits+ </CardTitle>+ <p className="text-xs text-muted-foreground">+ Visits to this page from AI platforms in the selected window+ </p>+ </CardHeader>+ <CardContent>+ {data.owned.traffic.totalVisits === 0 ? (+ <p className="py-6 text-center text-sm text-muted-foreground">+ No AI-referred visits recorded for this page yet.+ </p>+ ) : (+ <div className="space-y-3">+ <div className="text-2xl font-bold tabular-nums">+ {data.owned.traffic.totalVisits.toLocaleString()}+ </div>+ <ul className="space-y-1.5">+ {data.owned.traffic.byPlatform.map((p) => (+ <li key={p.platform} className="flex items-center gap-2 text-xs">+ <span className="flex-1 truncate capitalize">+ {p.platform === 'unknown'+ ? 'Unknown'+ : getPlatformDisplayLabel(p.platform)}+ </span>+ <span className="tabular-nums text-muted-foreground">{p.visits}</span>+ </li>+ ))}+ </ul>+ </div>+ )}+ </CardContent>+ </Card>+ </div>+ )}++ {/* Cited-in list */}+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Cited in</CardTitle>+ <p className="text-xs text-muted-foreground">+ Every AI answer citing this URL in the selected window+ </p>+ </CardHeader>+ <CardContent className="px-0 pb-0">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6 text-xs">Date</TableHead>+ <TableHead className="text-xs">Platform</TableHead>+ <TableHead className="text-xs">Prompt</TableHead>+ <TableHead className="text-xs">Sentiment</TableHead>+ <TableHead className="text-xs">Brand mentioned</TableHead>+ <TableHead className="pr-6 text-xs">Position</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {pageOccurrences.map((o) => (+ <TableRow key={o.resultId}>+ <TableCell className="pl-6 text-xs tabular-nums whitespace-nowrap">+ {formatDate(o.createdAt)}+ </TableCell>+ <TableCell>+ <PlatformsCell models={[o.modelUsed || o.platform || ''].filter(Boolean)} />+ </TableCell>+ <TableCell className="max-w-[380px]">+ <Link+ href={`/dashboard/prompts/${o.promptId}`}+ className="block truncate text-sm hover:underline"+ title={o.promptText}+ >+ {o.promptText}+ </Link>+ </TableCell>+ <TableCell>+ <SentimentBadge sentiment={o.sentiment} />+ </TableCell>+ <TableCell>+ {o.brandMentioned ? (+ <Check className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />+ ) : (+ <span className="text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ <TableCell className="pr-6">+ <PositionCell rank={o.rank} totalSources={o.totalSources} />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ <TablePager+ page={citedInPager.page}+ totalPages={citedInPager.totalPages}+ total={data.occurrences.length}+ start={citedInPager.start}+ end={citedInPager.end}+ onPage={citedInPager.setPage}+ />+ </CardContent>+ </Card>++ {/* Prompts breakdown */}+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Prompts breakdown</CardTitle>+ <p className="text-xs text-muted-foreground">+ The queries this page is winning, grouped by prompt+ </p>+ </CardHeader>+ <CardContent className="px-0 pb-0">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6 text-xs">Prompt</TableHead>+ <TableHead className="text-right text-xs">Answers</TableHead>+ <TableHead className="text-right text-xs">Citations</TableHead>+ <TableHead className="pr-6 text-right text-xs">Last seen</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {data.promptGroups.map((g) => (+ <TableRow key={g.promptId}>+ <TableCell className="pl-6 max-w-[520px]">+ <Link+ href={`/dashboard/prompts/${g.promptId}`}+ className="block truncate text-sm hover:underline"+ title={g.promptText}+ >+ {g.promptText}+ </Link>+ </TableCell>+ <TableCell className="text-right text-xs tabular-nums">{g.answers}</TableCell>+ <TableCell className="text-right text-xs tabular-nums">+ {g.citations}+ </TableCell>+ <TableCell className="pr-6 text-right text-xs tabular-nums whitespace-nowrap">+ {formatDate(g.lastSeen)}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ </>+ )}+ </div>+ );+}++function BackLink() {+ return (+ <Link+ href="/dashboard/citations"+ className="-ml-2 inline-flex h-8 items-center gap-1 rounded-md px-2 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ <ArrowLeft className="h-4 w-4" />+ Citations+ </Link>+ );+}++/** Display-only host fallback while the detail payload is loading. */+function extractDisplayHost(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./, '');+ } catch {+ return url;+ }+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsxindex 6906724f8..6232d2b8c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx@@ -2,7 +2,8 @@import { useEffect, useMemo, useState, type ComponentType } from 'react';import { useParams } from 'next/navigation';-import { useRouter } from '@/i18n/navigation';+import { Link, useRouter } from '@/i18n/navigation';+import { buildCitationDetailHref } from '@/components/citations/filter-bar';import {getPromptDetail,type PromptDetailData,@@ -342,15 +343,25 @@ function TopSourceUrlsTable({<div className="flex min-w-0 items-start gap-2"><DomainFavicon domain={row.domain} /><div className="flex min-w-0 max-w-[480px] flex-col">- <a- href={row.url}- target="_blank"- rel="noreferrer noopener"- className="truncate text-sm font-medium text-foreground hover:underline"- title={row.title || row.url}- >- {row.title || row.url}- </a>+ <div className="flex min-w-0 items-center gap-1.5">+ <Link+ href={buildCitationDetailHref(row.url, { datePreset: 'all' })}+ className="truncate text-sm font-medium text-foreground hover:underline"+ title={row.title || row.url}+ >+ {row.title || row.url}+ </Link>+ <a+ href={row.url}+ target="_blank"+ rel="noreferrer noopener"+ className="shrink-0 text-muted-foreground hover:text-foreground"+ aria-label="Open cited page in a new tab"+ title="Open cited page"+ >+ <ExternalLink className="h-3 w-3" />+ </a>+ </div><div className="flex items-center gap-1.5 pt-0.5"><span className="truncate text-[11px] text-muted-foreground">{row.domain}diff --git a/web/src/components/citations/add-competitor-button.tsx b/web/src/components/citations/add-competitor-button.tsxnew file mode 100644index 000000000..aabcdf5ef--- /dev/null+++ b/web/src/components/citations/add-competitor-button.tsx@@ -0,0 +1,127 @@+'use client';++/**+ * Add-as-competitor confirm dialog (#301), shared by the citations tables and+ * the per-URL citation detail page (#535). Opens pre-filled with a name+ * derived from the domain, then adds it as a tracked competitor.+ */++import { useId, useState } from 'react';+import { toast } from 'sonner';+import { Loader2, Plus } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { addCompetitor } from '@/lib/actions/competitor';++/** Turn a domain into a first-guess competitor name, e.g. caranddriver.com → "Caranddriver". */+export function deriveCompetitorName(domain: string): string {+ const first = domain+ .replace(/^www\./, '')+ .split('.')[0]+ ?.trim();+ if (!first) return domain;+ return first.charAt(0).toUpperCase() + first.slice(1);+}++export function AddCompetitorButton({+ brandId,+ domain,+ onAdded,+ appearance = 'icon',+}: {+ brandId: string;+ domain: string;+ onAdded: () => void;+ /** 'icon' — compact "+" for table rows; 'button' — labeled outline button. */+ appearance?: 'icon' | 'button';+}) {+ const [open, setOpen] = useState(false);+ const [name, setName] = useState('');+ const [saving, setSaving] = useState(false);+ const nameId = useId();++ function openDialog() {+ setName(deriveCompetitorName(domain));+ setOpen(true);+ }++ async function handleAdd() {+ const trimmed = name.trim();+ if (!trimmed || saving) return;+ setSaving(true);+ try {+ await addCompetitor(brandId, { name: trimmed, domain });+ toast.success(`${domain} added as competitor`);+ setOpen(false);+ onAdded();+ } catch {+ toast.error('Could not add this domain as a competitor. Please try again.');+ } finally {+ setSaving(false);+ }+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!saving) setOpen(next);+ }}+ >+ {appearance === 'icon' ? (+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={openDialog}+ aria-label={`Add ${domain} as competitor`}+ title="Add as competitor"+ >+ <Plus className="h-3.5 w-3.5" />+ </Button>+ ) : (+ <Button variant="outline" size="sm" className="h-8 gap-1.5 text-xs" onClick={openDialog}>+ <Plus className="h-3.5 w-3.5" />+ Add as competitor+ </Button>+ )}+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Add {domain} as competitor?</DialogTitle>+ <DialogDescription>+ Track this domain as a competitor. You can edit the name below.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-2">+ <Label htmlFor={nameId}>Name</Label>+ <Input+ id={nameId}+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && handleAdd()}+ placeholder="Competitor name"+ autoFocus+ />+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => setOpen(false)} disabled={saving}>+ Cancel+ </Button>+ <Button onClick={handleAdd} disabled={!name.trim() || saving} className="gap-2">+ {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}+ Add+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/components/citations/filter-bar.tsx b/web/src/components/citations/filter-bar.tsxnew file mode 100644index 000000000..ef81a459a--- /dev/null+++ b/web/src/components/citations/filter-bar.tsx@@ -0,0 +1,412 @@+'use client';++/**+ * Shared filter bar for citation surfaces: the Citations overview and the+ * per-URL citation detail page (#535). Owns the UI filter shape, the+ * date-preset → date-range resolution and the platform grouping so both+ * pages scope their data with identical semantics.+ */++import { useMemo } from 'react';+import { cn } from '@/lib/utils';+import type { Topic } from '@/types';+import type { CitationsDatePreset } from '@/lib/actions/citations';+import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';+import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import {+ Combobox,+ ComboboxCollection,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxTrigger,+ ComboboxValue,+} from '@/components/ui/combobox';++export const DATE_PRESETS: CitationsDatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];++export interface CitationsUIFilters {+ datePreset: CitationsDatePreset;+ dateFrom: string;+ dateTo: string;+ platform: string;+ region: string;+ topic: string;+ prompt: string;+ excludeOwnDomain: boolean;+ competitorOnly: boolean;+ ownOnly: boolean;+}++export const DEFAULT_CITATIONS_FILTERS: CitationsUIFilters = {+ datePreset: '24h',+ dateFrom: '',+ dateTo: '',+ platform: '',+ region: '',+ topic: '',+ prompt: '',+ excludeOwnDomain: false,+ competitorOnly: false,+ ownOnly: false,+};++export interface PromptOption {+ id: string;+ text: string;+}++// base-ui's Combobox auto-uses `label` for display and `value` for selection+// when items are `{ value, label }` shaped — no extra helpers needed.+interface PromptComboboxItem {+ value: string;+ label: string;+ /** Untruncated prompt text, shown as a native tooltip on hover (#298). */+ fullText: string;+}++export interface PlatformOption {+ value: string;+ label: string;+}++export function getPlatformDisplayLabel(slug: string): string {+ return (+ MODEL_PROVIDER_LABELS[slug] ??+ PLATFORM_LABELS[slug] ??+ getAIProviderDisplayName(resolveAIProvider(slug))+ );+}++export function getGroupedPlatformLabel(value: string): string {+ const firstSlug = value+ .split(',')+ .map((slug) => slug.trim())+ .find(Boolean);+ return firstSlug ? getPlatformDisplayLabel(firstSlug) : value;+}++/**+ * Group observed model slugs into provider-family options (one dropdown entry+ * per display label, value = comma-joined slugs of the family).+ */+export function buildPlatformOptions(rows: { models: string[] }[]): PlatformOption[] {+ const slugToLabel = new Map<string, string>();+ for (const row of rows) {+ for (const slug of row.models) {+ if (!slug || slugToLabel.has(slug)) continue;+ slugToLabel.set(slug, getPlatformDisplayLabel(slug));+ }+ }++ const familyToSlugs = new Map<string, string[]>();+ for (const [slug, label] of slugToLabel) {+ const slugs = familyToSlugs.get(label) ?? [];+ slugs.push(slug);+ familyToSlugs.set(label, slugs);+ }++ return Array.from(familyToSlugs.entries())+ .map(([label, slugs]) => ({+ label,+ value: slugs.sort().join(','),+ }))+ .sort((a, b) => a.label.localeCompare(b.label) || a.value.localeCompare(b.value));+}++/** Resolve a date preset (+ custom range) into API date bounds. */+export function getDateRange(+ preset: CitationsDatePreset,+ custom: { from: string; to: string },+): { dateFrom?: string; dateTo?: string } {+ if (preset === 'all') return {};+ if (preset === 'custom') {+ return {+ dateFrom: custom.from || undefined,+ dateTo: custom.to ? `${custom.to}T23:59:59.999Z` : undefined,+ };+ }+ if (preset === '24h') {+ const from = new Date();+ from.setHours(from.getHours() - 24);+ return { dateFrom: from.toISOString() };+ }+ const days = preset === '7d' ? 7 : preset === '30d' ? 30 : 90;+ const from = new Date();+ from.setDate(from.getDate() - days);+ return { dateFrom: from.toISOString() };+}++/**+ * Href for the per-URL citation detail page, carrying the current scoping+ * filters so the detail page opens with the same window applied (#535).+ */+export function buildCitationDetailHref(+ url: string,+ filters?: Partial<CitationsUIFilters>,+): string {+ const params = new URLSearchParams({ u: url });+ if (filters?.datePreset && filters.datePreset !== DEFAULT_CITATIONS_FILTERS.datePreset) {+ params.set('preset', filters.datePreset);+ }+ if (filters?.datePreset === 'custom') {+ if (filters.dateFrom) params.set('from', filters.dateFrom);+ if (filters.dateTo) params.set('to', filters.dateTo);+ }+ if (filters?.platform) params.set('platform', filters.platform);+ if (filters?.region) params.set('region', filters.region);+ return `/dashboard/citations/url?${params.toString()}`;+}++export function CitationsFilterBar({+ filters,+ onChange,+ topics = [],+ prompts = [],+ platforms,+ regions,+ showCategoryToggles = true,+}: {+ filters: CitationsUIFilters;+ onChange: (patch: Partial<CitationsUIFilters>) => void;+ topics?: Topic[];+ prompts?: PromptOption[];+ platforms: PlatformOption[];+ regions: string[];+ /** Hide the own/competitor domain toggles (meaningless on a single URL). */+ showCategoryToggles?: boolean;+}) {+ // base-ui Combobox needs `{ value, label }` shaped items so it can use the+ // built-in filter and display logic without custom item-to-string helpers.+ // Truncate long prompt text so the dropdown stays a sensible width.+ const promptComboboxItems = useMemo<PromptComboboxItem[]>(+ () =>+ prompts.map((p) => ({+ value: p.id,+ // Let the combobox's CSS `truncate` handle visual overflow; keep the+ // full text for the hover tooltip instead of slicing it away (#298).+ label: p.text,+ fullText: p.text,+ })),+ [prompts],+ );++ return (+ <div className="flex flex-wrap items-end gap-3">+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Date Range</label>+ <div className="flex rounded-md border overflow-hidden">+ {DATE_PRESETS.map((p) => (+ <button+ key={p}+ type="button"+ onClick={() => onChange({ datePreset: p })}+ className={cn(+ 'px-3 py-1.5 text-xs font-medium transition-colors',+ filters.datePreset === p+ ? 'bg-primary text-primary-foreground'+ : 'bg-card hover:bg-muted text-foreground',+ )}+ >+ {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}+ </button>+ ))}+ </div>+ </div>++ {filters.datePreset === 'custom' && (+ <>+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>+ <Input+ type="date"+ value={filters.dateFrom}+ onChange={(e) => onChange({ dateFrom: e.target.value })}+ className="h-8 w-36 text-xs"+ />+ </div>+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>+ <Input+ type="date"+ value={filters.dateTo}+ onChange={(e) => onChange({ dateTo: e.target.value })}+ className="h-8 w-36 text-xs"+ />+ </div>+ </>+ )}++ {topics.length > 0 && (+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topic</label>+ <Select+ value={filters.topic || null}+ onValueChange={(v) => onChange({ topic: !v || v === '__all__' ? '' : v })}+ >+ <SelectTrigger className="h-8 w-40 text-xs">+ <SelectValue placeholder="All Topics">+ {(value) =>+ value && value !== '__all__'+ ? (topics.find((t) => t.id === value)?.name ?? 'All Topics')+ : 'All Topics'+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="__all__">All Topics</SelectItem>+ {topics.map((t) => (+ <SelectItem key={t.id} value={t.id}>+ {t.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}++ {prompts.length > 0 && (+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Prompt</label>+ <Combobox+ items={promptComboboxItems}+ value={+ filters.prompt+ ? (promptComboboxItems.find((item) => item.value === filters.prompt) ?? null)+ : null+ }+ onValueChange={(item: PromptComboboxItem | null) =>+ onChange({+ prompt: !item || item.value === '__all__' ? '' : item.value,+ })+ }+ >+ <ComboboxTrigger className="h-8 w-56 text-xs">+ <ComboboxValue placeholder="All Prompts" />+ </ComboboxTrigger>+ <ComboboxContent>+ <ComboboxInput placeholder="Search prompts…" />+ <ComboboxList>+ <ComboboxEmpty>No prompts match.</ComboboxEmpty>+ <ComboboxCollection>+ {(item: PromptComboboxItem) => (+ <ComboboxItem key={item.value} value={item} title={item.fullText}>+ {item.label}+ </ComboboxItem>+ )}+ </ComboboxCollection>+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </div>+ )}++ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Platform</label>+ <Select+ value={filters.platform || null}+ onValueChange={(v) => onChange({ platform: !v || v === '__all__' ? '' : v })}+ >+ <SelectTrigger className="h-8 w-40 text-xs">+ <SelectValue placeholder="All Platforms">+ {(value) =>+ value && value !== '__all__'+ ? (platforms.find((platform) => platform.value === value)?.label ??+ getGroupedPlatformLabel(value))+ : 'All Platforms'+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="__all__">All Platforms</SelectItem>+ {platforms.map((platform) => (+ <SelectItem key={platform.value} value={platform.value}>+ {platform.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Region</label>+ <Select+ value={filters.region || null}+ onValueChange={(v) => onChange({ region: !v || v === '__all__' ? '' : v })}+ >+ <SelectTrigger className="h-8 w-32 text-xs">+ <SelectValue placeholder="All Regions" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="__all__">All Regions</SelectItem>+ {regions.map((r) => (+ <SelectItem key={r} value={r}>+ {r}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ {showCategoryToggles && (+ <div className="flex items-center gap-2 pb-0.5">+ <Button+ type="button"+ variant={filters.excludeOwnDomain ? 'default' : 'outline'}+ size="sm"+ className="h-8 text-xs"+ onClick={() =>+ onChange({+ excludeOwnDomain: !filters.excludeOwnDomain,+ ownOnly: false,+ })+ }+ >+ Exclude own domain+ </Button>+ <Button+ type="button"+ variant={filters.competitorOnly ? 'default' : 'outline'}+ size="sm"+ className="h-8 text-xs"+ onClick={() =>+ onChange({+ competitorOnly: !filters.competitorOnly,+ excludeOwnDomain: !filters.competitorOnly ? true : filters.excludeOwnDomain,+ ownOnly: false,+ })+ }+ >+ Competitors only+ </Button>+ <Button+ type="button"+ variant={filters.ownOnly ? 'default' : 'outline'}+ size="sm"+ className="h-8 text-xs"+ onClick={() =>+ onChange({+ ownOnly: !filters.ownOnly,+ excludeOwnDomain: false,+ competitorOnly: false,+ })+ }+ >+ Own domain only+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/web/src/lib/actions/citations.ts b/web/src/lib/actions/citations.tsindex ba7dfeeaa..e402f45dc 100644--- a/web/src/lib/actions/citations.ts+++ b/web/src/lib/actions/citations.ts@@ -78,6 +78,40 @@ export interface CitationsOverview {// ─── Helpers ──────────────────────────────────────────────────────────────────+/**+ * Canonical URL key for citation aggregation: strip query/fragment and one+ * trailing slash. The overview tables, the prompt detail Top Sources card and+ * the per-URL detail page (#535) must all bucket with this exact rule so+ * their counts agree for the same URL.+ */+function normalizeCitationUrl(raw: string): string {+ try {+ const parsed = new URL(raw);+ parsed.search = '';+ parsed.hash = '';+ return parsed.toString().replace(/\/$/, '');+ } catch {+ return raw;+ }+}++/**+ * Looser cross-source match key (host without `www.` + path without trailing+ * slashes) — mirrors `urlMatchKey` in prompt-workflow.ts / the server's+ * `normalizeUrlForMatch`, so the owned-URL bridges match targeted URLs and+ * traffic-log URLs the same way the cited-stats pipeline does.+ */+function citationUrlMatchKey(raw: string): string | null {+ try {+ const parsed = new URL(raw.trim());+ const host = parsed.hostname.toLowerCase().replace(/^www\./, '');+ const path = parsed.pathname.replace(/\/+$/, '');+ return `${host}${path}`;+ } catch {+ return null;+ }+}+function resolveDateRange(filters: CitationsFilters): { from?: string; to?: string } {if (filters.datePreset === 'custom') {return { from: filters.dateFrom, to: filters.dateTo };@@ -323,15 +357,7 @@ export async function getCitationsOverview(domainMap.set(host, existingDomain);// URL aggregation (strip query/fragment and trailing slash for dedupe).- let normalizedUrl = cite.url;- try {- const parsed = new URL(cite.url);- parsed.search = '';- parsed.hash = '';- normalizedUrl = parsed.toString().replace(/\/$/, '');- } catch {- // leave as-is- }+ const normalizedUrl = normalizeCitationUrl(cite.url);const existingUrl = urlMap.get(normalizedUrl) ?? {url: normalizedUrl,domain: host,@@ -689,3 +715,310 @@ export async function getCitationsTotal(brandId: string): Promise<number> {if (error) throw new Error(error.message);return count ?? 0;}++// ─── Per-URL detail (#535) ────────────────────────────────────────────────────++/** One answer citing the URL, for the detail page's "Cited in" list. */+export interface CitationUrlOccurrence {+ resultId: string;+ promptId: string;+ promptText: string;+ platform: string | null;+ modelUsed: string | null;+ region: string | null;+ createdAt: string;+ sentiment: string | null;+ /** Whether the brand was mentioned in the same answer. */+ brandMentioned: boolean;+ /** How many times this URL was cited within this one answer. */+ citationsInAnswer: number;+ /** 1-based order of the URL's first citation in the answer (by start index). */+ rank: number;+ /** Total citations in the answer (the rank's denominator). */+ totalSources: number;+}++/** Prompts that trigger this citation, grouped with counts. */+export interface CitationUrlPromptGroup {+ promptId: string;+ promptText: string;+ answers: number;+ citations: number;+ lastSeen: string;+}++export interface CitationUrlTargetingPrompt {+ promptId: string;+ promptText: string;+ label: string | null;+ citedCount: number;+}++export interface CitationUrlDetail {+ /** The normalized URL the page is keyed by. */+ url: string;+ domain: string;+ category: SourceCategory;+ title: string;+ articleType: string | null;+ totals: {+ citations: number;+ answers: number;+ prompts: number;+ models: string[];+ firstSeen: string | null;+ lastSeen: string | null;+ };+ /** Newest first. */+ occurrences: CitationUrlOccurrence[];+ promptGroups: CitationUrlPromptGroup[];+ /** Present only when the URL is on one of the brand's own domains. */+ owned: {+ targetingPrompts: CitationUrlTargetingPrompt[];+ traffic: { totalVisits: number; byPlatform: { platform: string; visits: number }[] };+ } | null;+}++/** Escape `\`, `%` and `_` for a PostgREST ilike pattern (mirrors traffic.ts). */+function escapeIlike(value: string): string {+ return value.replace(/[\\%_]/g, (ch) => `\\${ch}`);+}++const URL_DETAIL_TRAFFIC_MAX_ROWS = 5000;++/**+ * Everything the per-URL citation detail page needs (#535): a URL-filtered+ * scan of prompt_results plus, for brand-owned URLs, the targeting and+ * traffic bridges. Uses the same scan, filters and URL bucketing as+ * getCitationsOverview so the counts here agree with the overview tables for+ * the same URL, window and filters.+ */+export async function getCitationUrlDetail(+ brandId: string,+ rawUrl: string,+ filters: CitationsFilters,+): Promise<CitationUrlDetail> {+ const supabase = await createClient();+ const targetUrl = normalizeCitationUrl(rawUrl);+ const targetHost = extractHostname(targetUrl) ?? '';+ const targetMatchKey = citationUrlMatchKey(targetUrl);++ // Brand + competitor domains → category (same context as the overview).+ const [{ data: brandDomainRows }, { data: competitorRows }] = await Promise.all([+ supabase.from('brand_domains').select('domain').eq('brand_id', brandId),+ supabase.from('competitors').select('domain').eq('brand_id', brandId),+ ]);+ const brandDomains = (brandDomainRows ?? [])+ .map((r) => normalizeDomain((r as { domain: string }).domain))+ .filter(Boolean);+ const competitorDomains = (competitorRows ?? [])+ .map((r) => normalizeDomain((r as { domain: string }).domain))+ .filter(Boolean);+ const category = targetHost+ ? classifyDomain(targetHost, { brandDomains, competitorDomains })+ : 'other';++ interface DetailResultRow {+ id: string;+ prompt_id: string;+ platform: string | null;+ model_used: string | null;+ region: string | null;+ created_at: string;+ sentiment: string | null;+ mention_count: number | null;+ citations: Citation[] | null;+ }++ interface RawOccurrence extends Omit<CitationUrlOccurrence, 'promptText'> {+ promptText: string | null;+ }++ const occurrences: RawOccurrence[] = [];+ const models = new Set<string>();+ let title = '';+ let totalCitations = 0;+ let firstSeen: string | null = null;+ let lastSeen: string | null = null;++ await scanFilteredResults<DetailResultRow>(+ supabase,+ brandId,+ filters,+ 'id, prompt_id, platform, model_used, region, created_at, sentiment, mention_count, citations',+ (batch) => {+ for (const result of batch) {+ const citations = Array.isArray(result.citations) ? result.citations : [];+ if (citations.length === 0) continue;++ // Rank citations by their position in the answer; find ours.+ const ordered = [...citations].sort((a, b) => (a.startIndex ?? 0) - (b.startIndex ?? 0));+ let rank = 0;+ let citationsInAnswer = 0;+ for (let i = 0; i < ordered.length; i++) {+ if (normalizeCitationUrl(ordered[i].url) !== targetUrl) continue;+ citationsInAnswer += 1;+ if (rank === 0) rank = i + 1;+ if (!title && ordered[i].title) title = ordered[i].title;+ }+ if (citationsInAnswer === 0) continue;++ totalCitations += citationsInAnswer;+ const modelKey = result.model_used || result.platform || '';+ if (modelKey) models.add(modelKey);+ if (!firstSeen || result.created_at < firstSeen) firstSeen = result.created_at;+ if (!lastSeen || result.created_at > lastSeen) lastSeen = result.created_at;++ occurrences.push({+ resultId: result.id,+ promptId: result.prompt_id,+ promptText: null,+ platform: result.platform,+ modelUsed: result.model_used,+ region: result.region,+ createdAt: result.created_at,+ sentiment: result.sentiment,+ brandMentioned: (result.mention_count ?? 0) > 0,+ citationsInAnswer,+ rank,+ totalSources: citations.length,+ });+ }+ },+ );++ occurrences.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));++ // Resolve prompt texts for everything the scan touched.+ const promptIds = Array.from(new Set(occurrences.map((o) => o.promptId)));+ const promptTextById = new Map<string, string>();+ if (promptIds.length > 0) {+ const { data: promptRows, error: promptErr } = await supabase+ .from('prompts')+ .select('id, text')+ .in('id', promptIds);+ if (promptErr) throw new Error(promptErr.message);+ for (const p of (promptRows ?? []) as { id: string; text: string }[]) {+ promptTextById.set(p.id, p.text);+ }+ }+ const withText: CitationUrlOccurrence[] = occurrences.map((o) => ({+ ...o,+ promptText: o.promptText ?? promptTextById.get(o.promptId) ?? '(deleted prompt)',+ }));++ // Prompts breakdown — the queries this page is winning.+ const groupMap = new Map<string, CitationUrlPromptGroup>();+ for (const o of withText) {+ const existing = groupMap.get(o.promptId) ?? {+ promptId: o.promptId,+ promptText: o.promptText,+ answers: 0,+ citations: 0,+ lastSeen: o.createdAt,+ };+ existing.answers += 1;+ existing.citations += o.citationsInAnswer;+ if (o.createdAt > existing.lastSeen) existing.lastSeen = o.createdAt;+ groupMap.set(o.promptId, existing);+ }+ const promptGroups = Array.from(groupMap.values()).sort(+ (a, b) => b.citations - a.citations || b.answers - a.answers,+ );++ // Owned-URL bridges: targeting + AI-referred traffic, brand-domain URLs only.+ let owned: CitationUrlDetail['owned'] = null;+ if (category === 'you' && targetMatchKey) {+ const { from, to } = resolveDateRange(filters);+ const expandedTo = expandDateToEndOfDay(to);++ // (a) Prompts targeting this URL, via the workflow's prompt_target_urls.+ // Scoped to the brand through the prompts → prompt_sets join; matched with+ // the same loose key the cited-stats pipeline uses.+ const targetingPromise = supabase+ .from('prompt_target_urls')+ .select(+ 'prompt_id, url, label, cited_count, prompts!inner(text, prompt_sets!inner(brand_id))',+ )+ .eq('prompts.prompt_sets.brand_id', brandId);++ // (b) AI-referred visits to this page. The ilike narrows server-side; the+ // exact match happens on the loose key below.+ const pathForSearch = (() => {+ try {+ return new URL(targetUrl).pathname.replace(/\/+$/, '');+ } catch {+ return '';+ }+ })();+ let trafficQuery = supabase+ .from('ai_traffic_logs')+ .select('url, source_platform, created_at')+ .eq('brand_id', brandId)+ .order('created_at', { ascending: false })+ .range(0, URL_DETAIL_TRAFFIC_MAX_ROWS - 1);+ if (pathForSearch) trafficQuery = trafficQuery.ilike('url', `%${escapeIlike(pathForSearch)}%`);+ if (from) trafficQuery = trafficQuery.gte('created_at', from);+ if (expandedTo) trafficQuery = trafficQuery.lte('created_at', expandedTo);++ const [targetingRes, trafficRes] = await Promise.all([targetingPromise, trafficQuery]);+ if (targetingRes.error) throw new Error(targetingRes.error.message);+ if (trafficRes.error) throw new Error(trafficRes.error.message);++ interface TargetRow {+ prompt_id: string;+ url: string;+ label: string | null;+ cited_count: number;+ prompts: { text: string } | { text: string }[];+ }+ const targetingPrompts: CitationUrlTargetingPrompt[] = [];+ for (const row of (targetingRes.data ?? []) as unknown as TargetRow[]) {+ if (citationUrlMatchKey(row.url) !== targetMatchKey) continue;+ const prompt = Array.isArray(row.prompts) ? row.prompts[0] : row.prompts;+ targetingPrompts.push({+ promptId: row.prompt_id,+ promptText: prompt?.text ?? '(deleted prompt)',+ label: row.label,+ citedCount: row.cited_count,+ });+ }+ targetingPrompts.sort((a, b) => b.citedCount - a.citedCount);++ const visitsByPlatform = new Map<string, number>();+ let totalVisits = 0;+ for (const row of (trafficRes.data ?? []) as {+ url: string;+ source_platform: string | null;+ }[]) {+ if (citationUrlMatchKey(row.url) !== targetMatchKey) continue;+ totalVisits += 1;+ const platform = row.source_platform || 'unknown';+ visitsByPlatform.set(platform, (visitsByPlatform.get(platform) ?? 0) + 1);+ }+ const byPlatform = Array.from(visitsByPlatform.entries())+ .map(([platform, visits]) => ({ platform, visits }))+ .sort((a, b) => b.visits - a.visits);++ owned = { targetingPrompts, traffic: { totalVisits, byPlatform } };+ }++ return {+ url: targetUrl,+ domain: targetHost,+ category,+ title,+ articleType: classifyArticleType(targetUrl, title) ?? null,+ totals: {+ citations: totalCitations,+ answers: withText.length,+ prompts: promptIds.length,+ models: Array.from(models).sort(),+ firstSeen,+ lastSeen,+ },+ occurrences: withText,+ promptGroups,+ owned,+ };+}