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(content): review opportunities in a drawer without leaving the list (#963)

Gökhan Geyik6032a7ae364a
diff --git a/web/messages/en.json b/web/messages/en.json
index 47d4f8cb8..f7994f33a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1647,6 +1647,7 @@
"undoFailed": "Failed to undo",
"cancel": "Cancel",
"viewDetails": "View Details",
+ "openInNewTab": "Open in new tab",
"configureWebhook": "Configure Webhook",
"noOpportunities": "No content opportunities yet",
"noOpportunitiesHint": "Generate opportunities to get AI-powered content recommendations based on your prompt data.",
@@ -1670,6 +1671,10 @@
"owned": "Owned",
"earned": "Earned"
},
+ "typeHint": {
+ "owned": "Content on your own site",
+ "earned": "Coverage on other sites: articles, reviews, links"
+ },
"kpi": {
"total": "Total Opportunities",
"highImpact": "High Impact",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
index 40cd18edd..071acc534 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
@@ -1,638 +1,9 @@
'use client';
-import { useState, useEffect } from 'react';
-import { useTranslations } from 'next-intl';
import { useParams } from 'next/navigation';
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import {
- ArrowLeft,
- Send,
- Loader2,
- TrendingUp,
- Eye,
- Users,
- Search,
- Tag,
- Clock,
- X,
- Sparkles,
- FileText,
- Target,
- ListOrdered,
- Crown,
- RotateCcw,
- CheckCheck,
-} from 'lucide-react';
-import { cn } from '@/lib/utils';
-import { Link } from '@/i18n/navigation';
-import {
- getOpportunity,
- updateOpportunityStatus,
- sendToWebhook,
- generateBrief,
- getBriefQuota,
- sendOpportunityToActionCenter,
- type BriefQuota,
-} from '@/lib/actions/content';
-import type { ContentBrief, ContentOpportunity } from '@/types';
-import { getPromptFanout, type FanoutSubQuery } from '@/lib/actions/fanout';
-import {
- AssetsCard,
- OpportunityResultsCard,
- OpportunityBasketCard,
- ScoreBreakdown,
- TargetPagesCard,
-} from '@/components/content/opportunity-basket';
-import { toast } from 'sonner';
-
-const IMPACT_COLORS: Record<string, string> = {
- high: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
- medium: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
- low: 'border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-400',
-};
-
-const STATUS_COLORS: Record<string, string> = {
- new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
- reviewed: 'border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400',
- sent: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
- in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',
- done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
- dismissed: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400',
- archived: 'border-zinc-500/30 bg-zinc-500/5 text-zinc-500 dark:text-zinc-400',
-};
-
-const INTENT_LABELS: Record<string, string> = {
- comparison: 'Comparison',
- 'how-to': 'How-to',
- 'what-is': 'What is',
- 'best-top': 'Best / Top',
- 'vs-review': 'vs. / Review',
- recommendation: 'Recommendation',
- 'problem-solving': 'Problem Solving',
- other: 'Other',
-};
-
-function StatCard({
- icon: Icon,
- label,
- value,
- className,
-}: {
- icon: React.ElementType;
- label: string;
- value: React.ReactNode;
- className?: string;
-}) {
- return (
- <div className={cn('flex items-center gap-3 rounded-lg border p-3', className)}>
- <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
- <div>
- <p className="text-xs text-muted-foreground">{label}</p>
- <p className="text-sm font-medium">{value}</p>
- </div>
- </div>
- );
-}
+import { OpportunityDetail } from '@/components/content/opportunity-detail';
export default function ContentDetailPage() {
- const t = useTranslations('content');
const params = useParams();
- const id = params.id as string;
-
- const [opportunity, setOpportunity] = useState<ContentOpportunity | null>(null);
- const [loading, setLoading] = useState(true);
- const [sending, setSending] = useState(false);
- const [generatingBrief, setGeneratingBrief] = useState(false);
- const [brief, setBrief] = useState<ContentBrief | null>(null);
- const [quota, setQuota] = useState<BriefQuota | null>(null);
- const [fanoutQueries, setFanoutQueries] = useState<FanoutSubQuery[]>([]);
-
- useEffect(() => {
- setLoading(true);
- getOpportunity(id)
- .then((opp) => {
- setOpportunity(opp);
- if (opp.brief) setBrief(opp.brief);
- // A cluster opportunity shows its whole basket instead (#857).
- if (opp.brandId && opp.promptId && !opp.clusterId) {
- getPromptFanout(opp.brandId, opp.promptId)
- .then((d) => setFanoutQueries(d.subQueries))
- .catch(() => setFanoutQueries([]));
- }
- })
- .catch((err) => {
- console.error('Failed to load opportunity:', err);
- toast.error(t('loadOpportunityError'));
- })
- .finally(() => setLoading(false));
-
- // Quota is informational — don't block the page if it fails.
- getBriefQuota()
- .then(setQuota)
- .catch(() => setQuota(null));
- }, [id, t]);
-
- const handleSend = async () => {
- setSending(true);
- try {
- const result = await sendToWebhook(id);
- if (result.success === false) {
- toast.error(result.error);
- } else {
- toast.success(t('sentToWorkflow'));
- const updated = await getOpportunity(id);
- setOpportunity(updated);
- }
- } catch (err) {
- console.error('Send failed:', err);
- toast.error(t('sendError'));
- } finally {
- setSending(false);
- }
- };
-
- const handleReviewed = async () => {
- try {
- await updateOpportunityStatus(id, 'reviewed');
- setOpportunity(await getOpportunity(id));
- } catch {
- toast.error(t('reviewedError'));
- }
- };
-
- const handleDismiss = async () => {
- try {
- await updateOpportunityStatus(id, 'dismissed');
- const updated = await getOpportunity(id);
- setOpportunity(updated);
- toast.success(t('dismissedToast'), {
- action: {
- label: t('undo'),
- onClick: async () => {
- try {
- await updateOpportunityStatus(id, 'new');
- const restored = await getOpportunity(id);
- setOpportunity(restored);
- } catch {
- toast.error(t('undoFailed'));
- }
- },
- },
- });
- } catch {
- toast.error(t('dismissError'));
- }
- };
-
- // Action Center (#857): the whole opportunity, or one asset by its key.
- const [sendingAction, setSendingAction] = useState<string | null>(null);
- const handleSendToActionCenter = async (assetKey?: string) => {
- setSendingAction(assetKey ?? 'all');
- try {
- const result = await sendOpportunityToActionCenter(id, assetKey);
- if ('error' in result) {
- toast.error(result.error);
- return;
- }
- toast.success(result.created ? t('sentToActionCenter') : t('alreadyInActionCenter'));
- setOpportunity(await getOpportunity(id));
- } catch {
- toast.error(t('sendToActionCenterError'));
- } finally {
- setSendingAction(null);
- }
- };
-
- const handleRestore = async () => {
- try {
- await updateOpportunityStatus(id, 'new');
- setOpportunity(await getOpportunity(id));
- toast.success(t('restoredToast'));
- } catch {
- toast.error(t('restoreError'));
- }
- };
-
- const handleGenerateBrief = async () => {
- setGeneratingBrief(true);
- try {
- const result = await generateBrief(id);
- setBrief(result.brief);
- if (result.quota) setQuota(result.quota);
- toast.success(t('briefGeneratedToast'));
- } catch (err) {
- console.error('Brief generation failed:', err);
- toast.error(err instanceof Error ? err.message : t('briefGenerateError'));
- // Refresh the counter — the failure may have been a quota rejection.
- getBriefQuota()
- .then(setQuota)
- .catch(() => {});
- } finally {
- setGeneratingBrief(false);
- }
- };
-
- if (loading) {
- return (
- <div className="flex items-center justify-center min-h-[400px]">
- <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
- </div>
- );
- }
-
- if (!opportunity) {
- return (
- <div className="flex items-center justify-center min-h-[400px]">
- <p className="text-muted-foreground">Opportunity not found.</p>
- </div>
- );
- }
-
- const sd = opportunity.sourceData;
- const canSendToActionCenter = !['dismissed', 'archived', 'done'].includes(opportunity.status);
- const quotaLimited = quota !== null && quota.limit !== -1;
- const quotaExhausted = quotaLimited && quota.remaining <= 0;
-
- return (
- <div className="space-y-6">
- <div className="flex items-center gap-4">
- <Link href="/dashboard/content">
- <Button variant="ghost" size="icon" aria-label="Go back to content list">
- <ArrowLeft className="h-4 w-4" />
- </Button>
- </Link>
- <div className="flex-1">
- <h1 className="text-xl font-bold tracking-tight">{opportunity.title}</h1>
- {opportunity.description && (
- <p className="text-sm text-muted-foreground mt-1">{opportunity.description}</p>
- )}
- </div>
- <div className="flex items-center gap-2">
- {opportunity.clusterId &&
- (sd.actions?.all ? (
- <Link href={`/dashboard/action-center/actions?action=${sd.actions.all}`}>
- <Button variant="outline" size="sm" className="gap-2">
- <Target className="h-4 w-4" />
- {t('openInActionCenter')}
- </Button>
- </Link>
- ) : (
- canSendToActionCenter &&
- !Object.keys(sd.actions ?? {}).length && (
- <Button
- variant="outline"
- size="sm"
- onClick={() => handleSendToActionCenter()}
- disabled={sendingAction !== null}
- className="gap-2"
- >
- {sendingAction === 'all' ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Target className="h-4 w-4" />
- )}
- {t('sendToActionCenter')}
- </Button>
- )
- ))}
- {opportunity.status === 'archived' && (
- <Button variant="outline" size="sm" onClick={handleRestore} className="gap-2">
- <RotateCcw className="h-4 w-4" />
- {t('restore')}
- </Button>
- )}
- {opportunity.status === 'new' && (
- <Button variant="outline" size="sm" onClick={handleReviewed} className="gap-2">
- <CheckCheck className="h-4 w-4" />
- {t('markReviewed')}
- </Button>
- )}
- {opportunity.status === 'new' && (
- <>
- <Button
- variant="outline"
- size="sm"
- onClick={handleDismiss}
- className="gap-2 text-muted-foreground"
- >
- <X className="h-4 w-4" />
- {t('dismiss')}
- </Button>
- <Button size="sm" onClick={handleSend} disabled={sending} className="gap-2">
- {sending ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Send className="h-4 w-4" />
- )}
- {sending ? t('sending') : t('sendToWorkflow')}
- </Button>
- </>
- )}
- </div>
- </div>
-
- {sd.reopened && ['new', 'reviewed'].includes(opportunity.status) && (
- <div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
- <p className="font-medium text-amber-700 dark:text-amber-400">{t('newSignal')}</p>
- <p className="mt-0.5 text-xs text-muted-foreground">
- {sd.reopened.reason === 'score_rose'
- ? t('newSignalScoreRose', {
- from: Math.round(sd.reopened.previousScore),
- to: Math.round(sd.reopened.score),
- })
- : t('newSignalGainLost', {
- after: Math.round((sd.reopened.visibilityAfter ?? 0) * 10) / 10,
- now: Math.round(sd.reopened.visibility * 10) / 10,
- })}
- </p>
- </div>
- )}
-
- <div className="flex items-center gap-2">
- <Badge variant="outline" className="text-xs">
- {t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}
- </Badge>
- <Badge variant="outline" className={cn('text-xs', IMPACT_COLORS[opportunity.impact])}>
- {t(`impact.${opportunity.impact}` as 'impact.high' | 'impact.medium' | 'impact.low')}
- </Badge>
- <Badge variant="outline" className={cn('text-xs', STATUS_COLORS[opportunity.status])}>
- {t(`status.${opportunity.status}` as `status.${typeof opportunity.status}`)}
- </Badge>
- <Badge variant="outline" className="text-xs tabular-nums">
- Score: {Math.round(opportunity.opportunityScore)}
- </Badge>
- <span className="text-xs text-muted-foreground ml-auto flex items-center gap-1.5">
- <Clock className="h-3.5 w-3.5" />
- {new Date(opportunity.createdAt).toLocaleDateString(undefined, {
- day: 'numeric',
- month: 'short',
- year: 'numeric',
- })}
- </span>
- </div>
-
- {opportunity.clusterId && (
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <div className="space-y-4 lg:col-span-2">
- {opportunity.decision && (
- <TargetPagesCard decision={opportunity.decision} sourceData={sd} />
- )}
- <AssetsCard
- sourceData={sd}
- onSend={canSendToActionCenter ? handleSendToActionCenter : undefined}
- sendingKey={sendingAction}
- />
- <OpportunityBasketCard opportunityId={opportunity.id} />
- </div>
- <div className="space-y-4">
- {(Object.keys(sd.actions ?? {}).length > 0 || (sd.pastActions ?? []).length > 0) && (
- <OpportunityResultsCard
- actionIds={[...(sd.pastActions ?? []), ...Object.values(sd.actions ?? {})]}
- />
- )}
- <ScoreBreakdown sourceData={sd} />
- </div>
- </div>
- )}
-
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">{t('detail.sourceData')}</CardTitle>
- </CardHeader>
- <CardContent className="space-y-3">
- {sd.promptText && !opportunity.clusterId && (
- <StatCard icon={Search} label={t('detail.relatedPrompt')} value={sd.promptText} />
- )}
-
- <div className="grid grid-cols-2 gap-3">
- {sd.estAiVolume !== undefined && (
- <StatCard
- icon={TrendingUp}
- label={t('detail.estAiVolume')}
- value={`~${sd.estAiVolume.toLocaleString()}/mo`}
- />
- )}
- {sd.visibilityScore !== undefined && (
- <StatCard
- icon={Eye}
- label={t('detail.visibility')}
- value={`${Math.round(sd.visibilityScore)}%`}
- />
- )}
- {sd.competitorGap !== undefined && (
- <StatCard
- icon={Users}
- label={t('detail.competitorGap')}
- value={`${sd.competitorGap > 0 ? '+' : ''}${Math.round(sd.competitorGap)}%`}
- />
- )}
- {sd.topCompetitorVisibility !== undefined && (
- <StatCard
- icon={Users}
- label={t('detail.topCompetitor')}
- value={`${Math.round(sd.topCompetitorVisibility)}%`}
- />
- )}
- {sd.intent && (
- <StatCard
- icon={Tag}
- label={t('detail.intent')}
- value={INTENT_LABELS[sd.intent] || sd.intent}
- />
- )}
- </div>
-
- {sd.keywords && sd.keywords.length > 0 && (
- <div>
- <p className="text-xs text-muted-foreground mb-1.5">{t('detail.keywords')}</p>
- <div className="flex flex-wrap gap-1">
- {sd.keywords.map((kw) => (
- <Badge key={kw} variant="outline" className="text-xs">
- {kw}
- </Badge>
- ))}
- </div>
- </div>
- )}
-
- {fanoutQueries.length > 0 && (
- <div>
- <p className="text-xs text-muted-foreground mb-1.5">Observed fan-out queries</p>
- <div className="flex flex-wrap gap-1">
- {fanoutQueries.map((sq) => (
- <Badge
- key={sq.query}
- variant="outline"
- className="text-xs border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400 gap-1"
- title={`Searched ${sq.timesSearched}× by answer engines`}
- >
- <Search className="h-2.5 w-2.5 shrink-0" />
- {sq.query}
- <span className="opacity-60 tabular-nums">×{sq.timesSearched}</span>
- </Badge>
- ))}
- </div>
- </div>
- )}
-
- {sd.competitorsCited && sd.competitorsCited.length > 0 && (
- <div>
- <p className="text-xs text-muted-foreground mb-1.5">
- {t('detail.competitorsCited')}
- </p>
- <div className="flex flex-wrap gap-1">
- {sd.competitorsCited.map((comp) => (
- <Badge
- key={comp}
- variant="outline"
- className="text-xs border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400"
- >
- {comp}
- </Badge>
- ))}
- </div>
- </div>
- )}
- </CardContent>
- </Card>
-
- {brief ? (
- <Card>
- <CardHeader className="pb-3">
- <div className="flex items-center gap-2">
- <FileText className="h-4 w-4 text-primary" />
- <CardTitle className="text-sm font-medium">Content Brief</CardTitle>
- </div>
- </CardHeader>
- <CardContent className="space-y-4">
- <div>
- <h3 className="text-base font-semibold">{brief.suggestedTitle}</h3>
- <div className="flex items-center gap-2 mt-1.5">
- <Badge variant="outline" className="text-xs">
- {brief.contentType.replace(/-/g, ' ')}
- </Badge>
- <Badge variant="outline" className="text-xs tabular-nums">
- ~{brief.targetWordCount.toLocaleString()} words
- </Badge>
- </div>
- </div>
-
- <div>
- <div className="flex items-center gap-2 mb-1.5">
- <Target className="h-3.5 w-3.5 text-muted-foreground" />
- <p className="text-xs font-medium">Keywords</p>
- </div>
- <div className="flex flex-wrap gap-1">
- {brief.targetKeywords.map((kw) => (
- <Badge
- key={kw}
- variant="outline"
- className="text-xs border-primary/30 bg-primary/5"
- >
- {kw}
- </Badge>
- ))}
- </div>
- </div>
-
- <div className="rounded-lg border border-primary/20 bg-primary/5 p-2.5">
- <p className="text-xs text-muted-foreground mb-0.5">CTA</p>
- <p className="text-xs font-medium">{brief.callToAction}</p>
- </div>
- </CardContent>
- </Card>
- ) : (
- <Card>
- <CardContent className="flex flex-col items-center justify-center py-10 text-center">
- {quotaExhausted ? (
- <>
- <Crown className="h-10 w-10 text-amber-500/60 mb-3" />
- <h3 className="text-sm font-medium mb-1">Monthly Brief Limit Reached</h3>
- <p className="text-xs text-muted-foreground mb-4 max-w-sm">
- You&apos;ve used all {quota.limit} content briefs included in your plan this
- month. Upgrade for a higher limit, or wait until the 1st when your quota resets.
- </p>
- <Link href="/dashboard/settings?tab=billing">
- <Button className="gap-2">
- <Crown className="h-4 w-4" />
- Upgrade Plan
- </Button>
- </Link>
- </>
- ) : (
- <>
- <Sparkles className="h-10 w-10 text-muted-foreground/40 mb-3" />
- <h3 className="text-sm font-medium mb-1">No Content Brief Yet</h3>
- <p className="text-xs text-muted-foreground mb-4 max-w-sm">
- Generate an AI-powered content brief with a suggested title, outline, target
- keywords, and competitor insights.
- </p>
- <Button
- onClick={handleGenerateBrief}
- disabled={generatingBrief}
- className="gap-2"
- >
- {generatingBrief ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Sparkles className="h-4 w-4" />
- )}
- {generatingBrief ? 'Generating...' : 'Generate Content Brief'}
- </Button>
- {quotaLimited && (
- <p className="text-xs text-muted-foreground mt-3 tabular-nums">
- {quota.remaining}/{quota.limit} briefs remaining this month
- </p>
- )}
- </>
- )}
- </CardContent>
- </Card>
- )}
- </div>
-
- {/* Full Brief Detail (shown when brief exists) */}
- {brief && (
- <Card>
- <CardHeader className="pb-3">
- <div className="flex items-center gap-2">
- <ListOrdered className="h-4 w-4 text-primary" />
- <CardTitle className="text-sm font-medium">Brief Outline</CardTitle>
- </div>
- </CardHeader>
- <CardContent className="space-y-5">
- <div className="space-y-3">
- {brief.outline.map((section, idx) => (
- <div key={idx} className="rounded-lg border bg-muted/30 p-3">
- <p className="text-sm font-medium mb-1.5">
- {idx + 1}. {section.heading}
- </p>
- <ul className="space-y-1 ml-4">
- {section.keyPoints.map((point, pIdx) => (
- <li key={pIdx} className="text-xs text-muted-foreground list-disc">
- {point}
- </li>
- ))}
- </ul>
- </div>
- ))}
- </div>
-
- <div>
- <div className="flex items-center gap-2 mb-2">
- <Users className="h-4 w-4 text-muted-foreground" />
- <p className="text-sm font-medium">Competitor Insights</p>
- </div>
- <p className="text-sm text-muted-foreground leading-relaxed">
- {brief.competitorInsights}
- </p>
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- );
+ return <OpportunityDetail id={params.id as string} />;
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index 98d856d23..3a03d1865 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -78,6 +78,8 @@ import type { ContentOpportunity, ContentOpportunityStatus } from '@/types';
import { toast } from 'sonner';
import { Link } from '@/i18n/navigation';
import { WebhookSettingsDialog } from './_webhook-settings';
+import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';
+import { OpportunityDetail } from '@/components/content/opportunity-detail';
import { PAGE_SIZE, TablePager, usePagination } from '@/components/table-pager';
const GENERATION_STORAGE_KEY = 'aeo:content-generation';
@@ -296,11 +298,26 @@ export default function ContentPage() {
return () => clearTimeout(timer);
}, [search]);
+ // The open opportunity lives in the URL (?opportunity=<id>), like the
+ // Action Center's drawers: a refresh or a shared link reopens it, and
+ // opening one never navigates away from the filtered list.
+ const [openOpportunityId, setOpenOpportunityId] = useState<string | null>(null);
+
useEffect(() => {
- setPromptFilter(new URLSearchParams(window.location.search).get('prompt') ?? '');
+ const params = new URLSearchParams(window.location.search);
+ setPromptFilter(params.get('prompt') ?? '');
+ setOpenOpportunityId(params.get('opportunity'));
setUrlRead(true);
}, []);
+ const selectOpportunity = useCallback((opportunityId: string | null) => {
+ setOpenOpportunityId(opportunityId);
+ const url = new URL(window.location.href);
+ if (opportunityId) url.searchParams.set('opportunity', opportunityId);
+ else url.searchParams.delete('opportunity');
+ window.history.replaceState(window.history.state, '', url);
+ }, []);
+
const selectPrompt = useCallback((promptId: string) => {
setPromptFilter(promptId);
const url = new URL(window.location.href);
@@ -723,52 +740,6 @@ export default function ContentPage() {
className="pl-8 h-8 text-xs"
/>
</div>
- <Select value={statusFilter} onValueChange={(v) => v && setStatusFilter(v)}>
- <SelectTrigger className="h-8 w-[130px] text-xs">
- <SelectValue>
- {(value) =>
- value === 'all' ? t('filters.allStatuses') : t(`status.${value}`)
- }
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">{t('filters.allStatuses')}</SelectItem>
- <SelectItem value="new">{t('status.new')}</SelectItem>
- <SelectItem value="reviewed">{t('status.reviewed')}</SelectItem>
- <SelectItem value="sent">{t('status.sent')}</SelectItem>
- <SelectItem value="in_progress">{t('status.in_progress')}</SelectItem>
- <SelectItem value="done">{t('status.done')}</SelectItem>
- <SelectItem value="dismissed">{t('status.dismissed')}</SelectItem>
- <SelectItem value="archived">{t('status.archived')}</SelectItem>
- </SelectContent>
- </Select>
- <Select value={impactFilter} onValueChange={(v) => v && setImpactFilter(v)}>
- <SelectTrigger className="h-8 w-[120px] text-xs">
- <SelectValue>
- {(value) =>
- value === 'all' ? t('filters.allImpacts') : t(`impact.${value}`)
- }
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">{t('filters.allImpacts')}</SelectItem>
- <SelectItem value="high">{t('impact.high')}</SelectItem>
- <SelectItem value="medium">{t('impact.medium')}</SelectItem>
- <SelectItem value="low">{t('impact.low')}</SelectItem>
- </SelectContent>
- </Select>
- <Select value={typeFilter} onValueChange={(v) => v && setTypeFilter(v)}>
- <SelectTrigger className="h-8 w-[110px] text-xs">
- <SelectValue>
- {(value) => (value === 'all' ? t('filters.allTypes') : t(`type.${value}`))}
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">{t('filters.allTypes')}</SelectItem>
- <SelectItem value="owned">{t('type.owned')}</SelectItem>
- <SelectItem value="earned">{t('type.earned')}</SelectItem>
- </SelectContent>
- </Select>
{(topicOptions.length >= 2 || topicFilter !== '') && (
<Select
items={[
@@ -841,6 +812,64 @@ export default function ContentPage() {
</ComboboxContent>
</Combobox>
)}
+ <Select value={typeFilter} onValueChange={(v) => v && setTypeFilter(v)}>
+ <SelectTrigger className="h-8 w-[110px] text-xs">
+ <SelectValue>
+ {(value) => (value === 'all' ? t('filters.allTypes') : t(`type.${value}`))}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent
+ align="start"
+ alignItemWithTrigger={false}
+ className="w-auto min-w-(--anchor-width)"
+ >
+ <SelectItem value="all">{t('filters.allTypes')}</SelectItem>
+ {(['owned', 'earned'] as const).map((type) => (
+ <SelectItem key={type} value={type}>
+ <span className="flex flex-col">
+ <span>{t(`type.${type}`)}</span>
+ <span className="text-[11px] text-muted-foreground">
+ {t(`typeHint.${type}`)}
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={impactFilter} onValueChange={(v) => v && setImpactFilter(v)}>
+ <SelectTrigger className="h-8 w-[120px] text-xs">
+ <SelectValue>
+ {(value) =>
+ value === 'all' ? t('filters.allImpacts') : t(`impact.${value}`)
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t('filters.allImpacts')}</SelectItem>
+ <SelectItem value="high">{t('impact.high')}</SelectItem>
+ <SelectItem value="medium">{t('impact.medium')}</SelectItem>
+ <SelectItem value="low">{t('impact.low')}</SelectItem>
+ </SelectContent>
+ </Select>
+ <Select value={statusFilter} onValueChange={(v) => v && setStatusFilter(v)}>
+ <SelectTrigger className="h-8 w-[130px] text-xs">
+ <SelectValue>
+ {(value) =>
+ value === 'all' ? t('filters.allStatuses') : t(`status.${value}`)
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t('filters.allStatuses')}</SelectItem>
+ <SelectItem value="new">{t('status.new')}</SelectItem>
+ <SelectItem value="reviewed">{t('status.reviewed')}</SelectItem>
+ <SelectItem value="sent">{t('status.sent')}</SelectItem>
+ <SelectItem value="in_progress">{t('status.in_progress')}</SelectItem>
+ <SelectItem value="done">{t('status.done')}</SelectItem>
+ <SelectItem value="dismissed">{t('status.dismissed')}</SelectItem>
+ <SelectItem value="archived">{t('status.archived')}</SelectItem>
+ </SelectContent>
+ </Select>
</div>
</div>
</CardHeader>
@@ -992,9 +1021,10 @@ export default function ContentPage() {
/>
</TableCell>
<TableCell className="pl-6 max-w-0">
- <Link
- href={`/dashboard/content/${opp.id}`}
- className="block hover:underline"
+ <button
+ type="button"
+ onClick={() => selectOpportunity(opp.id)}
+ className="block w-full text-left hover:underline"
>
<p className="text-sm font-medium line-clamp-1">
{opp.sourceData?.reopened && opp.status === 'new' && (
@@ -1012,11 +1042,17 @@ export default function ContentPage() {
{opp.description}
</p>
)}
- </Link>
+ </button>
</TableCell>
<TableCell className="text-center">
<div className="flex flex-col items-center gap-1">
- <Badge variant="outline" className="text-xs">
+ <Badge
+ variant="outline"
+ className="text-xs"
+ title={t(
+ `typeHint.${opp.type}` as 'typeHint.owned' | 'typeHint.earned',
+ )}
+ >
{t(`type.${opp.type}` as 'type.owned' | 'type.earned')}
</Badge>
{opp.decision && (
@@ -1081,12 +1117,18 @@ export default function ContentPage() {
</Button>
</>
)}
- <Link href={`/dashboard/content/${opp.id}`}>
+ {/* The full page, in a new tab so the list stays put. */}
+ <Link
+ href={`/dashboard/content/${opp.id}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
- aria-label={t('viewDetails')}
+ aria-label={t('openInNewTab')}
+ title={t('openInNewTab')}
>
<ExternalLink className="h-3 w-3" />
</Button>
@@ -1121,6 +1163,27 @@ export default function ContentPage() {
</>
)}
+ <Sheet
+ open={openOpportunityId !== null}
+ onOpenChange={(open) => {
+ if (!open) selectOpportunity(null);
+ }}
+ >
+ <SheetContent className="flex flex-col gap-0 p-0 data-[side=right]:w-full data-[side=right]:sm:max-w-4xl">
+ <SheetTitle className="sr-only">{t('viewDetails')}</SheetTitle>
+ <div className="flex-1 overflow-y-auto p-6">
+ {openOpportunityId && (
+ <OpportunityDetail
+ key={openOpportunityId}
+ id={openOpportunityId}
+ inDrawer
+ onChanged={() => loadData(true)}
+ />
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+
<WebhookSettingsDialog
open={webhookOpen}
onOpenChange={setWebhookOpen}
diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsx
new file mode 100644
index 000000000..d7271f994
--- /dev/null
+++ b/web/src/components/content/opportunity-detail.tsx
@@ -0,0 +1,665 @@
+'use client';
+
+import { useState, useEffect } from 'react';
+import { useTranslations } from 'next-intl';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ ArrowLeft,
+ Send,
+ Loader2,
+ TrendingUp,
+ Eye,
+ Users,
+ Search,
+ Tag,
+ Clock,
+ X,
+ Sparkles,
+ FileText,
+ Target,
+ ListOrdered,
+ Crown,
+ RotateCcw,
+ CheckCheck,
+} from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { Link } from '@/i18n/navigation';
+import {
+ getOpportunity,
+ updateOpportunityStatus,
+ sendToWebhook,
+ generateBrief,
+ getBriefQuota,
+ sendOpportunityToActionCenter,
+ type BriefQuota,
+} from '@/lib/actions/content';
+import type { ContentBrief, ContentOpportunity } from '@/types';
+import { getPromptFanout, type FanoutSubQuery } from '@/lib/actions/fanout';
+import {
+ AssetsCard,
+ OpportunityResultsCard,
+ OpportunityBasketCard,
+ ScoreBreakdown,
+ TargetPagesCard,
+} from '@/components/content/opportunity-basket';
+import { toast } from 'sonner';
+
+const IMPACT_COLORS: Record<string, string> = {
+ high: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
+ medium: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ low: 'border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-400',
+};
+
+const STATUS_COLORS: Record<string, string> = {
+ new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
+ reviewed: 'border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400',
+ sent: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+ in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',
+ done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ dismissed: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400',
+ archived: 'border-zinc-500/30 bg-zinc-500/5 text-zinc-500 dark:text-zinc-400',
+};
+
+const INTENT_LABELS: Record<string, string> = {
+ comparison: 'Comparison',
+ 'how-to': 'How-to',
+ 'what-is': 'What is',
+ 'best-top': 'Best / Top',
+ 'vs-review': 'vs. / Review',
+ recommendation: 'Recommendation',
+ 'problem-solving': 'Problem Solving',
+ other: 'Other',
+};
+
+function StatCard({
+ icon: Icon,
+ label,
+ value,
+ className,
+}: {
+ icon: React.ElementType;
+ label: string;
+ value: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <div className={cn('flex items-center gap-3 rounded-lg border p-3', className)}>
+ <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
+ <div>
+ <p className="text-xs text-muted-foreground">{label}</p>
+ <p className="text-sm font-medium">{value}</p>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A content opportunity in full: its decision, assets, basket, brief and
+ * actions. Rendered as its own page (/dashboard/content/[id]) and inside the
+ * list's drawer, so reviewing one never loses the list's filters.
+ */
+export function OpportunityDetail({
+ id,
+ inDrawer = false,
+ onChanged,
+}: {
+ id: string;
+ /** In the list's drawer: no back link, and the layout follows the drawer's width. */
+ inDrawer?: boolean;
+ /** Called after any change to the opportunity, so the list can refresh. */
+ onChanged?: () => void;
+}) {
+ const t = useTranslations('content');
+
+ const [opportunity, setOpportunity] = useState<ContentOpportunity | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [sending, setSending] = useState(false);
+ const [generatingBrief, setGeneratingBrief] = useState(false);
+ const [brief, setBrief] = useState<ContentBrief | null>(null);
+ const [quota, setQuota] = useState<BriefQuota | null>(null);
+ const [fanoutQueries, setFanoutQueries] = useState<FanoutSubQuery[]>([]);
+
+ useEffect(() => {
+ setLoading(true);
+ getOpportunity(id)
+ .then((opp) => {
+ setOpportunity(opp);
+ if (opp.brief) setBrief(opp.brief);
+ // A cluster opportunity shows its whole basket instead (#857).
+ if (opp.brandId && opp.promptId && !opp.clusterId) {
+ getPromptFanout(opp.brandId, opp.promptId)
+ .then((d) => setFanoutQueries(d.subQueries))
+ .catch(() => setFanoutQueries([]));
+ }
+ })
+ .catch((err) => {
+ console.error('Failed to load opportunity:', err);
+ toast.error(t('loadOpportunityError'));
+ })
+ .finally(() => setLoading(false));
+
+ // Quota is informational — don't block the page if it fails.
+ getBriefQuota()
+ .then(setQuota)
+ .catch(() => setQuota(null));
+ }, [id, t]);
+
+ const handleSend = async () => {
+ setSending(true);
+ try {
+ const result = await sendToWebhook(id);
+ if (result.success === false) {
+ toast.error(result.error);
+ } else {
+ toast.success(t('sentToWorkflow'));
+ const updated = await getOpportunity(id);
+ setOpportunity(updated);
+ onChanged?.();
+ }
+ } catch (err) {
+ console.error('Send failed:', err);
+ toast.error(t('sendError'));
+ } finally {
+ setSending(false);
+ }
+ };
+
+ const handleReviewed = async () => {
+ try {
+ await updateOpportunityStatus(id, 'reviewed');
+ setOpportunity(await getOpportunity(id));
+ onChanged?.();
+ } catch {
+ toast.error(t('reviewedError'));
+ }
+ };
+
+ const handleDismiss = async () => {
+ try {
+ await updateOpportunityStatus(id, 'dismissed');
+ const updated = await getOpportunity(id);
+ setOpportunity(updated);
+ onChanged?.();
+ toast.success(t('dismissedToast'), {
+ action: {
+ label: t('undo'),
+ onClick: async () => {
+ try {
+ await updateOpportunityStatus(id, 'new');
+ const restored = await getOpportunity(id);
+ setOpportunity(restored);
+ onChanged?.();
+ } catch {
+ toast.error(t('undoFailed'));
+ }
+ },
+ },
+ });
+ } catch {
+ toast.error(t('dismissError'));
+ }
+ };
+
+ // Action Center (#857): the whole opportunity, or one asset by its key.
+ const [sendingAction, setSendingAction] = useState<string | null>(null);
+ const handleSendToActionCenter = async (assetKey?: string) => {
+ setSendingAction(assetKey ?? 'all');
+ try {
+ const result = await sendOpportunityToActionCenter(id, assetKey);
+ if ('error' in result) {
+ toast.error(result.error);
+ return;
+ }
+ toast.success(result.created ? t('sentToActionCenter') : t('alreadyInActionCenter'));
+ setOpportunity(await getOpportunity(id));
+ onChanged?.();
+ } catch {
+ toast.error(t('sendToActionCenterError'));
+ } finally {
+ setSendingAction(null);
+ }
+ };
+
+ const handleRestore = async () => {
+ try {
+ await updateOpportunityStatus(id, 'new');
+ setOpportunity(await getOpportunity(id));
+ onChanged?.();
+ toast.success(t('restoredToast'));
+ } catch {
+ toast.error(t('restoreError'));
+ }
+ };
+
+ const handleGenerateBrief = async () => {
+ setGeneratingBrief(true);
+ try {
+ const result = await generateBrief(id);
+ setBrief(result.brief);
+ if (result.quota) setQuota(result.quota);
+ onChanged?.();
+ toast.success(t('briefGeneratedToast'));
+ } catch (err) {
+ console.error('Brief generation failed:', err);
+ toast.error(err instanceof Error ? err.message : t('briefGenerateError'));
+ // Refresh the counter — the failure may have been a quota rejection.
+ getBriefQuota()
+ .then(setQuota)
+ .catch(() => {});
+ } finally {
+ setGeneratingBrief(false);
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center min-h-[400px]">
+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+
+ if (!opportunity) {
+ return (
+ <div className="flex items-center justify-center min-h-[400px]">
+ <p className="text-muted-foreground">Opportunity not found.</p>
+ </div>
+ );
+ }
+
+ const sd = opportunity.sourceData;
+ const canSendToActionCenter = !['dismissed', 'archived', 'done'].includes(opportunity.status);
+ const quotaLimited = quota !== null && quota.limit !== -1;
+ const quotaExhausted = quotaLimited && quota.remaining <= 0;
+
+ return (
+ // A container, so the layout follows the space it is given — the page's
+ // full width or the drawer's — rather than the viewport.
+ <div className="@container space-y-6">
+ <div className="flex flex-wrap items-center gap-4">
+ {!inDrawer && (
+ <Link href="/dashboard/content">
+ <Button variant="ghost" size="icon" aria-label="Go back to content list">
+ <ArrowLeft className="h-4 w-4" />
+ </Button>
+ </Link>
+ )}
+ <div className="min-w-0 flex-1">
+ <h1 className="text-xl font-bold tracking-tight">{opportunity.title}</h1>
+ {opportunity.description && (
+ <p className="text-sm text-muted-foreground mt-1">{opportunity.description}</p>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {opportunity.clusterId &&
+ (sd.actions?.all ? (
+ <Link href={`/dashboard/action-center/actions?action=${sd.actions.all}`}>
+ <Button variant="outline" size="sm" className="gap-2">
+ <Target className="h-4 w-4" />
+ {t('openInActionCenter')}
+ </Button>
+ </Link>
+ ) : (
+ canSendToActionCenter &&
+ !Object.keys(sd.actions ?? {}).length && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => handleSendToActionCenter()}
+ disabled={sendingAction !== null}
+ className="gap-2"
+ >
+ {sendingAction === 'all' ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Target className="h-4 w-4" />
+ )}
+ {t('sendToActionCenter')}
+ </Button>
+ )
+ ))}
+ {opportunity.status === 'archived' && (
+ <Button variant="outline" size="sm" onClick={handleRestore} className="gap-2">
+ <RotateCcw className="h-4 w-4" />
+ {t('restore')}
+ </Button>
+ )}
+ {opportunity.status === 'new' && (
+ <Button variant="outline" size="sm" onClick={handleReviewed} className="gap-2">
+ <CheckCheck className="h-4 w-4" />
+ {t('markReviewed')}
+ </Button>
+ )}
+ {opportunity.status === 'new' && (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleDismiss}
+ className="gap-2 text-muted-foreground"
+ >
+ <X className="h-4 w-4" />
+ {t('dismiss')}
+ </Button>
+ <Button size="sm" onClick={handleSend} disabled={sending} className="gap-2">
+ {sending ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Send className="h-4 w-4" />
+ )}
+ {sending ? t('sending') : t('sendToWorkflow')}
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+
+ {sd.reopened && ['new', 'reviewed'].includes(opportunity.status) && (
+ <div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
+ <p className="font-medium text-amber-700 dark:text-amber-400">{t('newSignal')}</p>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {sd.reopened.reason === 'score_rose'
+ ? t('newSignalScoreRose', {
+ from: Math.round(sd.reopened.previousScore),
+ to: Math.round(sd.reopened.score),
+ })
+ : t('newSignalGainLost', {
+ after: Math.round((sd.reopened.visibilityAfter ?? 0) * 10) / 10,
+ now: Math.round(sd.reopened.visibility * 10) / 10,
+ })}
+ </p>
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge
+ variant="outline"
+ className="text-xs"
+ title={t(`typeHint.${opportunity.type}` as 'typeHint.owned' | 'typeHint.earned')}
+ >
+ {t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}
+ </Badge>
+ <Badge variant="outline" className={cn('text-xs', IMPACT_COLORS[opportunity.impact])}>
+ {t(`impact.${opportunity.impact}` as 'impact.high' | 'impact.medium' | 'impact.low')}
+ </Badge>
+ <Badge variant="outline" className={cn('text-xs', STATUS_COLORS[opportunity.status])}>
+ {t(`status.${opportunity.status}` as `status.${typeof opportunity.status}`)}
+ </Badge>
+ <Badge variant="outline" className="text-xs tabular-nums">
+ Score: {Math.round(opportunity.opportunityScore)}
+ </Badge>
+ <span className="text-xs text-muted-foreground ml-auto flex items-center gap-1.5">
+ <Clock className="h-3.5 w-3.5" />
+ {new Date(opportunity.createdAt).toLocaleDateString(undefined, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ })}
+ </span>
+ </div>
+
+ {opportunity.clusterId && (
+ <div className="grid grid-cols-1 gap-4 @5xl:grid-cols-3">
+ <div className="space-y-4 @5xl:col-span-2">
+ {opportunity.decision && (
+ <TargetPagesCard decision={opportunity.decision} sourceData={sd} />
+ )}
+ <AssetsCard
+ sourceData={sd}
+ onSend={canSendToActionCenter ? handleSendToActionCenter : undefined}
+ sendingKey={sendingAction}
+ />
+ <OpportunityBasketCard opportunityId={opportunity.id} />
+ </div>
+ <div className="space-y-4">
+ {(Object.keys(sd.actions ?? {}).length > 0 || (sd.pastActions ?? []).length > 0) && (
+ <OpportunityResultsCard
+ actionIds={[...(sd.pastActions ?? []), ...Object.values(sd.actions ?? {})]}
+ />
+ )}
+ <ScoreBreakdown sourceData={sd} />
+ </div>
+ </div>
+ )}
+
+ <div className="grid grid-cols-1 gap-4 @3xl:grid-cols-2">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">{t('detail.sourceData')}</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-3">
+ {sd.promptText && !opportunity.clusterId && (
+ <StatCard icon={Search} label={t('detail.relatedPrompt')} value={sd.promptText} />
+ )}
+
+ <div className="grid grid-cols-2 gap-3">
+ {sd.estAiVolume !== undefined && (
+ <StatCard
+ icon={TrendingUp}
+ label={t('detail.estAiVolume')}
+ value={`~${sd.estAiVolume.toLocaleString()}/mo`}
+ />
+ )}
+ {sd.visibilityScore !== undefined && (
+ <StatCard
+ icon={Eye}
+ label={t('detail.visibility')}
+ value={`${Math.round(sd.visibilityScore)}%`}
+ />
+ )}
+ {sd.competitorGap !== undefined && (
+ <StatCard
+ icon={Users}
+ label={t('detail.competitorGap')}
+ value={`${sd.competitorGap > 0 ? '+' : ''}${Math.round(sd.competitorGap)}%`}
+ />
+ )}
+ {sd.topCompetitorVisibility !== undefined && (
+ <StatCard
+ icon={Users}
+ label={t('detail.topCompetitor')}
+ value={`${Math.round(sd.topCompetitorVisibility)}%`}
+ />
+ )}
+ {sd.intent && (
+ <StatCard
+ icon={Tag}
+ label={t('detail.intent')}
+ value={INTENT_LABELS[sd.intent] || sd.intent}
+ />
+ )}
+ </div>
+
+ {sd.keywords && sd.keywords.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">{t('detail.keywords')}</p>
+ <div className="flex flex-wrap gap-1">
+ {sd.keywords.map((kw) => (
+ <Badge key={kw} variant="outline" className="text-xs">
+ {kw}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {fanoutQueries.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">Observed fan-out queries</p>
+ <div className="flex flex-wrap gap-1">
+ {fanoutQueries.map((sq) => (
+ <Badge
+ key={sq.query}
+ variant="outline"
+ className="text-xs border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400 gap-1"
+ title={`Searched ${sq.timesSearched}× by answer engines`}
+ >
+ <Search className="h-2.5 w-2.5 shrink-0" />
+ {sq.query}
+ <span className="opacity-60 tabular-nums">×{sq.timesSearched}</span>
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {sd.competitorsCited && sd.competitorsCited.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">
+ {t('detail.competitorsCited')}
+ </p>
+ <div className="flex flex-wrap gap-1">
+ {sd.competitorsCited.map((comp) => (
+ <Badge
+ key={comp}
+ variant="outline"
+ className="text-xs border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400"
+ >
+ {comp}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {brief ? (
+ <Card>
+ <CardHeader className="pb-3">
+ <div className="flex items-center gap-2">
+ <FileText className="h-4 w-4 text-primary" />
+ <CardTitle className="text-sm font-medium">Content Brief</CardTitle>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div>
+ <h3 className="text-base font-semibold">{brief.suggestedTitle}</h3>
+ <div className="flex items-center gap-2 mt-1.5">
+ <Badge variant="outline" className="text-xs">
+ {brief.contentType.replace(/-/g, ' ')}
+ </Badge>
+ <Badge variant="outline" className="text-xs tabular-nums">
+ ~{brief.targetWordCount.toLocaleString()} words
+ </Badge>
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center gap-2 mb-1.5">
+ <Target className="h-3.5 w-3.5 text-muted-foreground" />
+ <p className="text-xs font-medium">Keywords</p>
+ </div>
+ <div className="flex flex-wrap gap-1">
+ {brief.targetKeywords.map((kw) => (
+ <Badge
+ key={kw}
+ variant="outline"
+ className="text-xs border-primary/30 bg-primary/5"
+ >
+ {kw}
+ </Badge>
+ ))}
+ </div>
+ </div>
+
+ <div className="rounded-lg border border-primary/20 bg-primary/5 p-2.5">
+ <p className="text-xs text-muted-foreground mb-0.5">CTA</p>
+ <p className="text-xs font-medium">{brief.callToAction}</p>
+ </div>
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <CardContent className="flex flex-col items-center justify-center py-10 text-center">
+ {quotaExhausted ? (
+ <>
+ <Crown className="h-10 w-10 text-amber-500/60 mb-3" />
+ <h3 className="text-sm font-medium mb-1">Monthly Brief Limit Reached</h3>
+ <p className="text-xs text-muted-foreground mb-4 max-w-sm">
+ You&apos;ve used all {quota.limit} content briefs included in your plan this
+ month. Upgrade for a higher limit, or wait until the 1st when your quota resets.
+ </p>
+ <Link href="/dashboard/settings?tab=billing">
+ <Button className="gap-2">
+ <Crown className="h-4 w-4" />
+ Upgrade Plan
+ </Button>
+ </Link>
+ </>
+ ) : (
+ <>
+ <Sparkles className="h-10 w-10 text-muted-foreground/40 mb-3" />
+ <h3 className="text-sm font-medium mb-1">No Content Brief Yet</h3>
+ <p className="text-xs text-muted-foreground mb-4 max-w-sm">
+ Generate an AI-powered content brief with a suggested title, outline, target
+ keywords, and competitor insights.
+ </p>
+ <Button
+ onClick={handleGenerateBrief}
+ disabled={generatingBrief}
+ className="gap-2"
+ >
+ {generatingBrief ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Sparkles className="h-4 w-4" />
+ )}
+ {generatingBrief ? 'Generating...' : 'Generate Content Brief'}
+ </Button>
+ {quotaLimited && (
+ <p className="text-xs text-muted-foreground mt-3 tabular-nums">
+ {quota.remaining}/{quota.limit} briefs remaining this month
+ </p>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ )}
+ </div>
+
+ {/* Full Brief Detail (shown when brief exists) */}
+ {brief && (
+ <Card>
+ <CardHeader className="pb-3">
+ <div className="flex items-center gap-2">
+ <ListOrdered className="h-4 w-4 text-primary" />
+ <CardTitle className="text-sm font-medium">Brief Outline</CardTitle>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-5">
+ <div className="space-y-3">
+ {brief.outline.map((section, idx) => (
+ <div key={idx} className="rounded-lg border bg-muted/30 p-3">
+ <p className="text-sm font-medium mb-1.5">
+ {idx + 1}. {section.heading}
+ </p>
+ <ul className="space-y-1 ml-4">
+ {section.keyPoints.map((point, pIdx) => (
+ <li key={pIdx} className="text-xs text-muted-foreground list-disc">
+ {point}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <Users className="h-4 w-4 text-muted-foreground" />
+ <p className="text-sm font-medium">Competitor Insights</p>
+ </div>
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ {brief.competitorInsights}
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+}