sanity-plugin-seo-copilot 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1165 @@
1
+ import { useState, useEffect, useCallback, useRef } from "react";
2
+ import { useKeywordAnalysis } from "../hooks/useKeywordAnalysis";
3
+ import { useConfig } from "./ConfigContext";
4
+ import { KeywordBadge } from "./KeywordBadge";
5
+ import { PlacementIndicators } from "./PlacementIndicators";
6
+ import { SeedKeywordInput } from "./SeedKeywordInput";
7
+ import { FeedbackButton } from "./FeedbackButton";
8
+ import { LoadingBars } from "./SEOCopilotPanel";
9
+ import { MJH_GOLD, MJH_GOLD_DARK, MJH_BLUE } from "./styles";
10
+ import type { DeepAnalysis, AEORecommendations, PrimaryKeywordCandidate, DocumentFields } from "../lib/types";
11
+
12
+ const AEO_PURPLE = "#7C3AED";
13
+
14
+ interface KeywordPanelProps {
15
+ text: string;
16
+ publication?: string;
17
+ seedKeywords?: string[];
18
+ onSeedsChange?: (seeds: string[]) => void;
19
+ onSelectPrimary?: (term: string) => void;
20
+ documentFields?: DocumentFields;
21
+ // When provided, use these instead of calling useKeywordAnalysis internally
22
+ externalAnalysis?: {
23
+ analysis: import("../lib/types").SEOAnalysis | null;
24
+ isLoading: boolean;
25
+ error: string | null;
26
+ deepAnalysis: import("../lib/types").DeepAnalysis | null;
27
+ isDeepLoading: boolean;
28
+ runDeepAnalysis: () => void;
29
+ refreshVolumes?: () => void;
30
+ aeoContentChanged?: boolean;
31
+ };
32
+ }
33
+
34
+ interface SuggestedKeyword {
35
+ term: string;
36
+ volume: number;
37
+ inContent: boolean;
38
+ reason?: string;
39
+ placement?: import("../lib/types").KeywordPlacement;
40
+ }
41
+
42
+ function SectionHeader({ label, iconColor, actionButton }: { label: string; iconColor: string; actionButton?: React.ReactNode }) {
43
+ return (
44
+ <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }}>
45
+ <div style={{ width: 7, height: 7, borderRadius: "50%", background: iconColor, flexShrink: 0 }} />
46
+ <span style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8", fontWeight: 600, flex: 1 }}>
47
+ {label}
48
+ </span>
49
+ {actionButton}
50
+ </div>
51
+ );
52
+ }
53
+
54
+ const cardStyle = {
55
+ borderRadius: 14,
56
+ background: "#ffffff",
57
+ boxShadow: "0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.03)",
58
+ padding: "14px",
59
+ };
60
+
61
+ function BulletItem({ text }: { text: string }) {
62
+ return (
63
+ <div style={{ display: "flex", gap: 8, alignItems: "flex-start", padding: "2px 0" }}>
64
+ <div style={{ width: 6, height: 6, borderRadius: "50%", marginTop: 6, background: MJH_GOLD, flexShrink: 0 }} />
65
+ <span style={{ fontSize: 12, color: "#4b5563", lineHeight: 1.6 }}>{text}</span>
66
+ </div>
67
+ );
68
+ }
69
+
70
+ interface KeywordHelpSuggestion {
71
+ type: "change" | "add";
72
+ original?: string;
73
+ revised?: string;
74
+ sentence?: string;
75
+ where?: string;
76
+ }
77
+
78
+ function abbrevVol(v: number | null | undefined): string {
79
+ if (v == null) return "";
80
+ if (v === 0) return "N/A";
81
+ if (v >= 10000) return Math.round(v / 1000) + "K";
82
+ if (v >= 1000) return (v / 1000).toFixed(1) + "K";
83
+ return String(v);
84
+ }
85
+
86
+ function placementCount(p?: import("../lib/types").KeywordPlacement): number {
87
+ if (!p) return 0;
88
+ return [p.inBody, p.inTitle, p.inMetaDescription, p.inImages, p.inUrl].filter(Boolean).length;
89
+ }
90
+
91
+ type PlacementKey = "inBody" | "inTitle" | "inMetaDescription" | "inImages" | "inUrl" | "none";
92
+
93
+ /** Merge supporting + missing into one list, filter out 0-volume, sort by placement count desc */
94
+ function buildSuggestedKeywords(
95
+ supporting: { term: string; volume: number | null; inContent: boolean; placement?: import("../lib/types").KeywordPlacement }[],
96
+ missing: { term: string; volume: number | null; reason: string; placement?: import("../lib/types").KeywordPlacement }[],
97
+ documentText: string
98
+ ): SuggestedKeyword[] {
99
+ const merged: SuggestedKeyword[] = [];
100
+ const lowerText = documentText.toLowerCase();
101
+
102
+ for (const kw of supporting) {
103
+ const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
104
+ merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: kw.placement });
105
+ }
106
+
107
+ for (const kw of missing) {
108
+ const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
109
+ merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: kw.placement });
110
+ }
111
+
112
+ // Default sort: most placements first, then volume desc within same placement count
113
+ merged.sort((a, b) => {
114
+ const pDiff = placementCount(b.placement) - placementCount(a.placement);
115
+ if (pDiff !== 0) return pDiff;
116
+ return b.volume - a.volume;
117
+ });
118
+ return merged;
119
+ }
120
+
121
+ function LightbulbButton({ onClick, isLoading }: { onClick: () => void; isLoading: boolean }) {
122
+ const [hovered, setHovered] = useState(false);
123
+
124
+ return (
125
+ <span
126
+ onClick={(e) => { e.stopPropagation(); onClick(); }}
127
+ onMouseEnter={() => setHovered(true)}
128
+ onMouseLeave={() => setHovered(false)}
129
+ style={{
130
+ position: "relative",
131
+ cursor: isLoading ? "wait" : "pointer",
132
+ fontSize: 14,
133
+ lineHeight: 1,
134
+ opacity: isLoading ? 0.5 : 1,
135
+ flexShrink: 0,
136
+ display: "inline-flex",
137
+ alignItems: "center",
138
+ }}
139
+ title="How to use this keyword"
140
+ >
141
+ {isLoading ? (
142
+ <LoadingBars size="xs" color={MJH_GOLD} />
143
+ ) : (
144
+ "💡"
145
+ )}
146
+ {hovered && !isLoading && (
147
+ <span style={{
148
+ position: "absolute",
149
+ bottom: "100%",
150
+ left: "50%",
151
+ transform: "translateX(-50%)",
152
+ marginBottom: 4,
153
+ padding: "2px 6px",
154
+ borderRadius: 4,
155
+ background: "#1f2937",
156
+ color: "#ffffff",
157
+ fontSize: 10,
158
+ whiteSpace: "nowrap",
159
+ pointerEvents: "none",
160
+ zIndex: 10,
161
+ }}>
162
+ How to use
163
+ </span>
164
+ )}
165
+ </span>
166
+ );
167
+ }
168
+
169
+ /** Highlights all occurrences of `keyword` in `text` with a yellow background */
170
+ function HighlightKeyword({ text, keyword }: { text: string; keyword: string }) {
171
+ if (!keyword || !text) return <>{text}</>;
172
+ const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "gi");
173
+ const parts = text.split(regex);
174
+ return (
175
+ <>
176
+ {parts.map((part, i) =>
177
+ regex.test(part) ? (
178
+ <span key={i} style={{ background: "#FEF08A", fontWeight: 600, borderRadius: 2, padding: "0 1px" }}>{part}</span>
179
+ ) : (
180
+ <span key={i}>{part}</span>
181
+ )
182
+ )}
183
+ </>
184
+ );
185
+ }
186
+
187
+ function KeywordHelpDisplay({ suggestions, onRegenerate, isRegenerating, term, publication }: {
188
+ suggestions: KeywordHelpSuggestion[];
189
+ onRegenerate: () => void;
190
+ isRegenerating: boolean;
191
+ term: string;
192
+ publication?: string;
193
+ }) {
194
+ return (
195
+ <div style={{ paddingLeft: 8, paddingTop: 4, paddingBottom: 4, display: "flex", flexDirection: "column", gap: 6 }}>
196
+ {suggestions.map((s, i) => (
197
+ <div key={i} style={{ fontSize: 11, lineHeight: 1.5, padding: "6px 8px", background: "rgba(0,93,172,0.05)", borderRadius: 6, borderLeft: `2px solid ${MJH_BLUE}` }}>
198
+ <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
199
+ <div style={{ flex: 1 }}>
200
+ {s.type === "change" ? (
201
+ <>
202
+ <div style={{ color: "#9ca3af", fontWeight: 600, fontSize: 10, textTransform: "uppercase", marginBottom: 2 }}>Change</div>
203
+ <div style={{ color: "#991b1b", textDecoration: "line-through", marginBottom: 2 }}>{s.original}</div>
204
+ <div style={{ color: "#166534" }}><HighlightKeyword text={s.revised || ""} keyword={term} /></div>
205
+ </>
206
+ ) : (
207
+ <>
208
+ <div style={{ color: "#9ca3af", fontWeight: 600, fontSize: 10, textTransform: "uppercase", marginBottom: 2 }}>Add{s.where ? ` - ${s.where}` : ""}</div>
209
+ <div style={{ color: "#374151" }}><HighlightKeyword text={s.sentence || ""} keyword={term} /></div>
210
+ </>
211
+ )}
212
+ </div>
213
+ <FeedbackButton
214
+ suggestionType="keyword_help"
215
+ suggestionText={`${term}: ${s.type === "change" ? s.revised : s.sentence}`}
216
+ publication={publication}
217
+ />
218
+ </div>
219
+ </div>
220
+ ))}
221
+ {/* Regenerate button */}
222
+ <button
223
+ onClick={onRegenerate}
224
+ disabled={isRegenerating}
225
+ style={{
226
+ display: "flex",
227
+ alignItems: "center",
228
+ gap: 4,
229
+ padding: "4px 8px",
230
+ fontSize: 10,
231
+ color: isRegenerating ? "#9ca3af" : MJH_BLUE,
232
+ background: "none",
233
+ border: "none",
234
+ cursor: isRegenerating ? "wait" : "pointer",
235
+ alignSelf: "flex-start",
236
+ transition: "color 150ms",
237
+ }}
238
+ title="Regenerate suggestions"
239
+ >
240
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style={{ animation: isRegenerating ? "spin 1s linear infinite" : "none" }}>
241
+ <path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H4.598a.75.75 0 00-.75.75v3.634a.75.75 0 001.5 0v-2.033l.312.311a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm-10.624-2.85a5.5 5.5 0 019.201-2.466l.312.311h-2.433a.75.75 0 000 1.5h3.634a.75.75 0 00.75-.75V3.535a.75.75 0 00-1.5 0v2.033l-.312-.311A7 7 0 002.628 8.395a.75.75 0 001.449.39z" clipRule="evenodd" />
242
+ </svg>
243
+ {isRegenerating ? "Regenerating..." : "Regenerate"}
244
+ </button>
245
+ </div>
246
+ );
247
+ }
248
+
249
+ function PencilButton({ onClick, active }: { onClick: () => void; active: boolean }) {
250
+ return (
251
+ <button
252
+ onClick={onClick}
253
+ style={{
254
+ background: "none",
255
+ border: "none",
256
+ cursor: "pointer",
257
+ padding: 2,
258
+ display: "flex",
259
+ alignItems: "center",
260
+ color: active ? MJH_GOLD : "#9ca3af",
261
+ transition: "color 150ms",
262
+ flexShrink: 0,
263
+ }}
264
+ title="Add custom keyword"
265
+ >
266
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor">
267
+ <path d="M2.695 14.763l-1.262 3.154a.5.5 0 00.65.65l3.155-1.262a4 4 0 001.343-.885L17.5 5.5a2.121 2.121 0 00-3-3L3.58 13.42a4 4 0 00-.885 1.343z" />
268
+ </svg>
269
+ </button>
270
+ );
271
+ }
272
+
273
+ function PrimaryKeywordSelector({
274
+ candidates,
275
+ selectedTerm,
276
+ onSelect,
277
+ publication,
278
+ documentId,
279
+ }: {
280
+ candidates: PrimaryKeywordCandidate[];
281
+ selectedTerm: string;
282
+ onSelect: (term: string) => void;
283
+ publication?: string;
284
+ documentId?: string;
285
+ }) {
286
+ const [customInputOpen, setCustomInputOpen] = useState(false);
287
+ const [customValue, setCustomValue] = useState("");
288
+
289
+ const handleCustomSubmit = () => {
290
+ const trimmed = customValue.trim();
291
+ if (trimmed) {
292
+ onSelect(trimmed);
293
+ setCustomValue("");
294
+ setCustomInputOpen(false);
295
+ }
296
+ };
297
+
298
+ return (
299
+ <div style={cardStyle}>
300
+ <SectionHeader
301
+ label="Primary Keyword"
302
+ iconColor="#16a34a"
303
+ actionButton={
304
+ <PencilButton onClick={() => setCustomInputOpen(!customInputOpen)} active={customInputOpen} />
305
+ }
306
+ />
307
+
308
+ {customInputOpen && (
309
+ <div style={{ marginBottom: 8, display: "flex", gap: 6 }}>
310
+ <input
311
+ type="text"
312
+ value={customValue}
313
+ onChange={(e) => setCustomValue(e.target.value)}
314
+ onKeyDown={(e) => { if (e.key === "Enter") handleCustomSubmit(); }}
315
+ placeholder="Type a custom primary keyword"
316
+ autoFocus
317
+ style={{
318
+ flex: 1,
319
+ padding: "5px 8px",
320
+ fontSize: 12,
321
+ borderRadius: 8,
322
+ border: "1px solid #e5e7eb",
323
+ outline: "none",
324
+ fontFamily: "inherit",
325
+ }}
326
+ />
327
+ <button
328
+ onClick={handleCustomSubmit}
329
+ disabled={!customValue.trim()}
330
+ style={{
331
+ padding: "5px 10px",
332
+ fontSize: 11,
333
+ fontWeight: 600,
334
+ borderRadius: 6,
335
+ border: "none",
336
+ background: customValue.trim() ? MJH_GOLD : "#e5e7eb",
337
+ color: customValue.trim() ? "#ffffff" : "#9ca3af",
338
+ cursor: customValue.trim() ? "pointer" : "not-allowed",
339
+ }}
340
+ >
341
+ Set
342
+ </button>
343
+ </div>
344
+ )}
345
+
346
+ <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
347
+ {candidates.map((candidate) => {
348
+ const isSelected = candidate.term === selectedTerm;
349
+ return (
350
+ <div
351
+ key={candidate.term}
352
+ onClick={() => onSelect(candidate.term)}
353
+ style={{
354
+ display: "flex",
355
+ alignItems: "center",
356
+ gap: 8,
357
+ padding: "6px 8px",
358
+ borderRadius: 8,
359
+ cursor: "pointer",
360
+ background: isSelected ? "rgba(22,163,74,0.06)" : "transparent",
361
+ border: isSelected ? "1px solid rgba(22,163,74,0.2)" : "1px solid transparent",
362
+ transition: "all 150ms",
363
+ }}
364
+ >
365
+ {/* Radio dot */}
366
+ <div style={{
367
+ width: 14,
368
+ height: 14,
369
+ borderRadius: "50%",
370
+ border: isSelected ? "none" : "2px solid #d1d5db",
371
+ background: isSelected ? "#16a34a" : "transparent",
372
+ flexShrink: 0,
373
+ display: "flex",
374
+ alignItems: "center",
375
+ justifyContent: "center",
376
+ }}>
377
+ {isSelected && (
378
+ <div style={{ width: 6, height: 6, borderRadius: "50%", background: "#ffffff" }} />
379
+ )}
380
+ </div>
381
+
382
+ <div style={{ flex: 1, minWidth: 0 }}>
383
+ <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
384
+ <span style={{
385
+ fontSize: 12,
386
+ fontWeight: isSelected ? 600 : 400,
387
+ color: isSelected ? "#166534" : "#374151",
388
+ }}>
389
+ {candidate.term}
390
+ </span>
391
+ {candidate.volume != null && (
392
+ <span style={{ fontSize: 11, color: "#9ca3af" }}>{abbrevVol(candidate.volume)}/mo</span>
393
+ )}
394
+ <span style={{ fontSize: 10, color: "#9ca3af" }}>
395
+ {Math.round(candidate.confidence * 100)}% confidence
396
+ </span>
397
+ </div>
398
+ {candidate.placement && (
399
+ <div style={{ marginTop: 3 }}>
400
+ <PlacementIndicators placement={candidate.placement} />
401
+ </div>
402
+ )}
403
+ </div>
404
+
405
+ </div>
406
+ );
407
+ })}
408
+ </div>
409
+ </div>
410
+ );
411
+ }
412
+
413
+ const PLACEMENT_FILTERS: { key: PlacementKey; label: string; letter: string }[] = [
414
+ { key: "inBody", label: "Body", letter: "B" },
415
+ { key: "inTitle", label: "Title", letter: "T" },
416
+ { key: "inMetaDescription", label: "Description", letter: "D" },
417
+ { key: "inImages", label: "Images", letter: "I" },
418
+ { key: "inUrl", label: "URL", letter: "U" },
419
+ ];
420
+
421
+ const INITIAL_SHOW = 8;
422
+
423
+ function computePlacementClient(term: string, content: string, fields?: DocumentFields): import("../lib/types").KeywordPlacement {
424
+ const lower = term.toLowerCase();
425
+ return {
426
+ inBody: content.toLowerCase().includes(lower),
427
+ inTitle: fields?.title?.toLowerCase().includes(lower) ?? false,
428
+ inMetaDescription: fields?.metaDescription?.toLowerCase().includes(lower) ?? false,
429
+ inImages: fields?.imageNames?.some((name: string) => name.toLowerCase().includes(lower)) ?? false,
430
+ inUrl: fields?.slug?.toLowerCase().includes(lower) ?? false,
431
+ };
432
+ }
433
+
434
+ function SuggestedKeywordsCard({
435
+ keywords,
436
+ text,
437
+ apiUrl,
438
+ publication,
439
+ documentFields,
440
+ refreshVolumes,
441
+ isVolumesLoading,
442
+ }: {
443
+ keywords: SuggestedKeyword[];
444
+ text: string;
445
+ apiUrl: string;
446
+ publication?: string;
447
+ documentFields?: DocumentFields;
448
+ refreshVolumes?: () => void;
449
+ isVolumesLoading?: boolean;
450
+ }) {
451
+ const [helpData, setHelpData] = useState<Record<string, KeywordHelpSuggestion[]>>({});
452
+ const [loadingTerm, setLoadingTerm] = useState<string | null>(null);
453
+ const [regeneratingTerm, setRegeneratingTerm] = useState<string | null>(null);
454
+ const [manualInputOpen, setManualInputOpen] = useState(false);
455
+ const [manualInputValue, setManualInputValue] = useState("");
456
+ const [manualKeywords, setManualKeywords] = useState<string[]>([]);
457
+ const [expanded, setExpanded] = useState(false);
458
+ const [extraKeywords, setExtraKeywords] = useState<SuggestedKeyword[]>([]);
459
+ const [isGeneratingMore, setIsGeneratingMore] = useState(false);
460
+ const [sortAsc, setSortAsc] = useState(false); // false = most placements first
461
+ const [activeFilters, setActiveFilters] = useState<Set<PlacementKey>>(new Set());
462
+ const [showFilterDropdown, setShowFilterDropdown] = useState(false);
463
+
464
+ const fetchHelp = async (term: string, forceRegenerate = false) => {
465
+ if (helpData[term] && !forceRegenerate) {
466
+ const next = { ...helpData };
467
+ delete next[term];
468
+ setHelpData(next);
469
+ return;
470
+ }
471
+ if (forceRegenerate) { setRegeneratingTerm(term); } else { setLoadingTerm(term); }
472
+ try {
473
+ // Pass previous suggestions when regenerating so API avoids repeating them
474
+ const previousSuggestions = forceRegenerate && helpData[term]
475
+ ? helpData[term].map((s) => s.revised || s.sentence || "").filter(Boolean)
476
+ : undefined;
477
+ const res = await fetch(`${apiUrl}/api/seo-copilot/keyword-help`, {
478
+ method: "POST",
479
+ headers: { "Content-Type": "application/json" },
480
+ body: JSON.stringify({ keyword: term, content: text, publication, previousSuggestions }),
481
+ });
482
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
483
+ const data = await res.json();
484
+ setHelpData((prev) => ({ ...prev, [term]: data.suggestions || [] }));
485
+ } catch {
486
+ setHelpData((prev) => ({ ...prev, [term]: [{ type: "add", sentence: "Failed to generate suggestions. Try again.", where: "" }] }));
487
+ }
488
+ setLoadingTerm(null);
489
+ setRegeneratingTerm(null);
490
+ };
491
+
492
+ const [enrichingTerms, setEnrichingTerms] = useState<Set<string>>(new Set());
493
+
494
+ const handleAddManual = async () => {
495
+ const trimmed = manualInputValue.trim();
496
+ if (!trimmed) return;
497
+ // Skip if already exists
498
+ if (manualKeywords.includes(trimmed) || allKeywords.some((kw) => kw.term.toLowerCase() === trimmed.toLowerCase())) return;
499
+
500
+ setManualKeywords((prev) => [...prev, trimmed]);
501
+ setManualInputValue("");
502
+
503
+ // Immediately add to extraKeywords with placeholder data + compute placement
504
+ const placement = computePlacementClient(trimmed, text, documentFields);
505
+ const inContent = text.toLowerCase().includes(trimmed.toLowerCase());
506
+ setExtraKeywords((prev) => [...prev, { term: trimmed, volume: 0, inContent, placement }]);
507
+ setEnrichingTerms((prev) => new Set(prev).add(trimmed));
508
+
509
+ // Fetch volume from SEMrush
510
+ try {
511
+ const res = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
512
+ method: "POST",
513
+ headers: { "Content-Type": "application/json" },
514
+ body: JSON.stringify({ keywords: [trimmed] }),
515
+ });
516
+ if (res.ok) {
517
+ const data = await res.json();
518
+ const match = (data.results || []).find((r: { keyword: string }) => r.keyword.toLowerCase() === trimmed.toLowerCase());
519
+ if (match) {
520
+ setExtraKeywords((prev) => prev.map((kw) =>
521
+ kw.term.toLowerCase() === trimmed.toLowerCase()
522
+ ? { ...kw, volume: match.volume ?? 0 }
523
+ : kw
524
+ ));
525
+ }
526
+ }
527
+ } catch { /* silent */ }
528
+ setEnrichingTerms((prev) => { const next = new Set(prev); next.delete(trimmed); return next; });
529
+
530
+ // Auto-trigger lightbulb help
531
+ fetchHelp(trimmed);
532
+ };
533
+
534
+ const toggleFilter = (key: PlacementKey) => {
535
+ setActiveFilters((prev) => {
536
+ if (key === "none") {
537
+ // "None" deselects all placement filters
538
+ return prev.has("none") ? new Set() : new Set(["none"] as PlacementKey[]);
539
+ }
540
+ // Any placement filter deselects "none"
541
+ const next = new Set(prev);
542
+ next.delete("none");
543
+ if (next.has(key)) { next.delete(key); } else { next.add(key); }
544
+ return next;
545
+ });
546
+ };
547
+
548
+ // Apply filters
549
+ let filtered = keywords;
550
+ if (activeFilters.size > 0) {
551
+ const hasNoneFilter = activeFilters.has("none");
552
+ const placementFilters = [...activeFilters].filter((f) => f !== "none") as PlacementKey[];
553
+
554
+ filtered = keywords.filter((kw) => {
555
+ if (hasNoneFilter) {
556
+ // "None" = show keywords with zero placements
557
+ return placementCount(kw.placement) === 0;
558
+ }
559
+ if (placementFilters.length === 0) return true;
560
+ if (!kw.placement) return false;
561
+ for (const f of placementFilters) {
562
+ if (f === "none") continue;
563
+ if (!kw.placement[f as keyof import("../lib/types").KeywordPlacement]) return false;
564
+ }
565
+ return true;
566
+ });
567
+ }
568
+
569
+ // Apply sort
570
+ const sorted = [...filtered].sort((a, b) => {
571
+ const pA = placementCount(a.placement);
572
+ const pB = placementCount(b.placement);
573
+ if (sortAsc) {
574
+ if (pA !== pB) return pA - pB;
575
+ return a.volume - b.volume;
576
+ }
577
+ if (pA !== pB) return pB - pA;
578
+ return b.volume - a.volume;
579
+ });
580
+
581
+ // Merge extra generated keywords into the list
582
+ const allKeywords = [...sorted, ...extraKeywords.filter((ek) => !sorted.some((s) => s.term.toLowerCase() === ek.term.toLowerCase()))];
583
+ const visible = expanded ? allKeywords : allKeywords.slice(0, INITIAL_SHOW);
584
+ const hiddenCount = allKeywords.length - INITIAL_SHOW;
585
+ const missingCount = keywords.filter((kw) => !kw.inContent).length;
586
+
587
+ const generateMoreKeywords = async () => {
588
+ setIsGeneratingMore(true);
589
+ try {
590
+ const existingTerms = allKeywords.map((kw) => kw.term);
591
+ const res = await fetch(`${apiUrl}/api/seo-copilot/more-keywords`, {
592
+ method: "POST",
593
+ headers: { "Content-Type": "application/json" },
594
+ body: JSON.stringify({ content: text, existingKeywords: existingTerms, publication }),
595
+ });
596
+ if (res.ok) {
597
+ const data = await res.json();
598
+ const newKws: SuggestedKeyword[] = (data.keywords || []).map((kw: { term: string; volume: number | null; inContent: boolean }) => ({
599
+ term: kw.term,
600
+ volume: kw.volume ?? 0,
601
+ inContent: kw.inContent,
602
+ }));
603
+ setExtraKeywords((prev) => [...prev, ...newKws]);
604
+ }
605
+ } catch { /* silent */ }
606
+ setIsGeneratingMore(false);
607
+ };
608
+
609
+ return (
610
+ <div style={cardStyle}>
611
+ {/* Header row with count, sort, filter, pencil */}
612
+ <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
613
+ <div style={{ width: 6, height: 6, borderRadius: "50%", background: MJH_BLUE, flexShrink: 0 }} />
614
+ <span style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em", color: "#9ca3af", fontWeight: 600, flex: 1 }}>
615
+ Supporting Keywords
616
+ </span>
617
+ {/* Refresh volumes */}
618
+ {refreshVolumes && (
619
+ <button
620
+ onClick={refreshVolumes}
621
+ disabled={isVolumesLoading}
622
+ style={{ background: "none", border: "none", cursor: isVolumesLoading ? "wait" : "pointer", padding: 2, display: "flex", color: isVolumesLoading ? "#d1d5db" : "#9ca3af", fontSize: 10 }}
623
+ title="Refresh keyword volumes"
624
+ >
625
+ {isVolumesLoading ? (
626
+ <LoadingBars size="xs" color="#9ca3af" />
627
+ ) : (
628
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style={{ transition: "transform 150ms" }}>
629
+ <path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H4.598a.75.75 0 00-.75.75v3.634a.75.75 0 001.5 0v-2.033l.312.311a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm-10.624-2.85a5.5 5.5 0 019.201-2.466l.312.311h-2.433a.75.75 0 000 1.5h3.634a.75.75 0 00.75-.75V3.535a.75.75 0 00-1.5 0v2.033l-.312-.311A7 7 0 002.628 8.395a.75.75 0 001.449.39z" clipRule="evenodd" />
630
+ </svg>
631
+ )}
632
+ </button>
633
+ )}
634
+ {/* Sort toggle */}
635
+ <button
636
+ onClick={() => setSortAsc(!sortAsc)}
637
+ style={{ background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#9ca3af", fontSize: 10 }}
638
+ title={sortAsc ? "Sort: least placements first" : "Sort: most placements first"}
639
+ >
640
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style={{ transform: sortAsc ? "rotate(180deg)" : "none", transition: "transform 150ms" }}>
641
+ <path fillRule="evenodd" d="M10 3a.75.75 0 01.55.24l3.25 3.5a.75.75 0 11-1.1 1.02L10 4.852 7.3 7.76a.75.75 0 01-1.1-1.02l3.25-3.5A.75.75 0 0110 3zm-3.76 9.2a.75.75 0 011.06.04l2.7 2.908 2.7-2.908a.75.75 0 111.1 1.02l-3.25 3.5a.75.75 0 01-1.1 0l-3.25-3.5a.75.75 0 01.04-1.06z" clipRule="evenodd" />
642
+ </svg>
643
+ </button>
644
+ {/* Filter dropdown */}
645
+ <div style={{ position: "relative" }}>
646
+ <button
647
+ onClick={() => setShowFilterDropdown(!showFilterDropdown)}
648
+ style={{
649
+ background: activeFilters.size > 0 ? "rgba(0,93,172,0.1)" : "none",
650
+ border: "none", cursor: "pointer", padding: "2px 4px", display: "flex", alignItems: "center", gap: 2,
651
+ color: activeFilters.size > 0 ? MJH_BLUE : "#9ca3af", borderRadius: 4, fontSize: 10,
652
+ }}
653
+ title="Filter by placement"
654
+ >
655
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor">
656
+ <path fillRule="evenodd" d="M2.628 1.601C5.028 1.206 7.49 1 10 1s4.973.206 7.372.601a.75.75 0 01.628.74v2.288a2.25 2.25 0 01-.659 1.59l-4.682 4.683a2.25 2.25 0 00-.659 1.59v3.037c0 .684-.31 1.33-.844 1.757l-1.937 1.55A.75.75 0 018 18.25v-5.757a2.25 2.25 0 00-.659-1.591L2.659 6.22A2.25 2.25 0 012 4.629V2.34a.75.75 0 01.628-.74z" clipRule="evenodd" />
657
+ </svg>
658
+ {activeFilters.size > 0 && <span>{activeFilters.size}</span>}
659
+ </button>
660
+ {showFilterDropdown && (
661
+ <div style={{
662
+ position: "absolute", top: "100%", right: 0, marginTop: 4, width: 150,
663
+ background: "#ffffff", borderRadius: 8, boxShadow: "0 4px 12px rgba(0,0,0,0.12)",
664
+ border: "1px solid #e5e7eb", zIndex: 50, padding: "4px 0",
665
+ }}>
666
+ {PLACEMENT_FILTERS.map(({ key, label, letter }) => (
667
+ <button
668
+ key={key}
669
+ onClick={() => toggleFilter(key)}
670
+ style={{
671
+ width: "100%", display: "flex", alignItems: "center", gap: 8,
672
+ padding: "5px 10px", background: "none", border: "none", cursor: "pointer",
673
+ fontSize: 11, color: "#374151", textAlign: "left",
674
+ }}
675
+ >
676
+ <div style={{
677
+ width: 14, height: 14, borderRadius: 3, border: "1.5px solid " + (activeFilters.has(key) ? MJH_BLUE : "#d1d5db"),
678
+ background: activeFilters.has(key) ? MJH_BLUE : "transparent",
679
+ display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
680
+ }}>
681
+ {activeFilters.has(key) && (
682
+ <svg width="8" height="8" viewBox="0 0 12 12" fill="white"><path d="M10 3L4.5 8.5 2 6" stroke="white" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
683
+ )}
684
+ </div>
685
+ <span style={{ fontWeight: 600, color: "#9ca3af", width: 14 }}>{letter}</span>
686
+ <span>{label}</span>
687
+ </button>
688
+ ))}
689
+ {/* "None" option - show keywords with no placements */}
690
+ <button
691
+ onClick={() => toggleFilter("none")}
692
+ style={{
693
+ width: "100%", display: "flex", alignItems: "center", gap: 8,
694
+ padding: "5px 10px", background: "none", border: "none", cursor: "pointer",
695
+ fontSize: 11, color: "#374151", textAlign: "left",
696
+ borderTop: "1px solid #f1f5f9",
697
+ }}
698
+ >
699
+ <div style={{
700
+ width: 14, height: 14, borderRadius: 3, border: "1.5px solid " + (activeFilters.has("none") ? MJH_BLUE : "#d1d5db"),
701
+ background: activeFilters.has("none") ? MJH_BLUE : "transparent",
702
+ display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
703
+ }}>
704
+ {activeFilters.has("none") && (
705
+ <svg width="8" height="8" viewBox="0 0 12 12" fill="white"><path d="M10 3L4.5 8.5 2 6" stroke="white" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
706
+ )}
707
+ </div>
708
+ <span style={{ fontWeight: 600, color: "#9ca3af", width: 14 }}>-</span>
709
+ <span>None (missing all)</span>
710
+ </button>
711
+ {activeFilters.size > 0 && (
712
+ <button
713
+ onClick={() => { setActiveFilters(new Set()); setShowFilterDropdown(false); }}
714
+ style={{
715
+ width: "100%", padding: "5px 10px", background: "none", border: "none",
716
+ borderTop: "1px solid #f1f5f9", cursor: "pointer", fontSize: 10, color: "#dc2626", textAlign: "center",
717
+ }}
718
+ >
719
+ Clear filters
720
+ </button>
721
+ )}
722
+ </div>
723
+ )}
724
+ </div>
725
+ <PencilButton onClick={() => setManualInputOpen(!manualInputOpen)} active={manualInputOpen} />
726
+ </div>
727
+
728
+ {/* Manual keyword input */}
729
+ {manualInputOpen && (
730
+ <div style={{ marginBottom: 8, display: "flex", gap: 6 }}>
731
+ <input
732
+ type="text"
733
+ value={manualInputValue}
734
+ onChange={(e) => setManualInputValue(e.target.value)}
735
+ onKeyDown={(e) => { if (e.key === "Enter") handleAddManual(); }}
736
+ placeholder="Add a keyword manually"
737
+ autoFocus
738
+ style={{ flex: 1, padding: "5px 8px", fontSize: 12, borderRadius: 8, border: "1px solid #e5e7eb", outline: "none", fontFamily: "inherit" }}
739
+ />
740
+ <button
741
+ onClick={handleAddManual}
742
+ disabled={!manualInputValue.trim()}
743
+ style={{
744
+ padding: "5px 10px", fontSize: 11, fontWeight: 600, borderRadius: 6, border: "none",
745
+ background: manualInputValue.trim() ? MJH_BLUE : "#e5e7eb",
746
+ color: manualInputValue.trim() ? "#ffffff" : "#9ca3af",
747
+ cursor: manualInputValue.trim() ? "pointer" : "not-allowed",
748
+ }}
749
+ >
750
+ Add
751
+ </button>
752
+ </div>
753
+ )}
754
+
755
+ {/* Keyword rows - flat with status dot */}
756
+ <div>
757
+ {visible.map((kw, i) => (
758
+ <div key={kw.term}>
759
+ <div style={{
760
+ display: "flex", alignItems: "center", gap: 8,
761
+ padding: "5px 0",
762
+ borderBottom: i < visible.length - 1 ? "1px solid #f3f4f6" : "none",
763
+ minHeight: 28,
764
+ }}>
765
+ {/* Status dot - LEFT */}
766
+ <div style={{
767
+ width: 8, height: 8, borderRadius: "50%", flexShrink: 0,
768
+ background: kw.inContent ? "#16a34a" : "#d1d5db",
769
+ }} />
770
+ {/* Term */}
771
+ <span style={{ fontSize: 12, fontWeight: 500, flexGrow: 1, color: kw.inContent ? "#9ca3af" : "#374151" }}>
772
+ {kw.term}
773
+ </span>
774
+ {/* Loading indicator for enriching manual keywords */}
775
+ {enrichingTerms.has(kw.term) && <LoadingBars size="xs" color="#9ca3af" />}
776
+ {/* Abbreviated volume */}
777
+ {!enrichingTerms.has(kw.term) && kw.volume != null && (
778
+ <span style={{ fontSize: 10, color: "#d1d5db", flexShrink: 0 }}>{abbrevVol(kw.volume)}</span>
779
+ )}
780
+ {/* Placement indicators */}
781
+ {kw.placement && <PlacementIndicators placement={kw.placement} />}
782
+ {/* Lightbulb for missing */}
783
+ {!kw.inContent && (
784
+ <LightbulbButton onClick={() => fetchHelp(kw.term)} isLoading={loadingTerm === kw.term} />
785
+ )}
786
+ </div>
787
+ {/* Keyword help */}
788
+ {helpData[kw.term] && (
789
+ <KeywordHelpDisplay
790
+ suggestions={helpData[kw.term]}
791
+ onRegenerate={() => fetchHelp(kw.term, true)}
792
+ isRegenerating={regeneratingTerm === kw.term}
793
+ term={kw.term}
794
+ publication={publication}
795
+ />
796
+ )}
797
+ </div>
798
+ ))}
799
+
800
+ </div>
801
+
802
+ {/* Show more (first click reveals hidden), then Generate more (subsequent clicks call API) */}
803
+ {!expanded && hiddenCount > 0 && (
804
+ <button
805
+ onClick={() => setExpanded(true)}
806
+ style={{
807
+ marginTop: 6, width: "100%", padding: "4px 0", background: "none", border: "none",
808
+ cursor: "pointer", fontSize: 10, color: "#9ca3af", display: "flex", alignItems: "center",
809
+ justifyContent: "center", gap: 4,
810
+ }}
811
+ >
812
+ <svg width="10" height="10" viewBox="0 0 20 20" fill="#9ca3af">
813
+ <path fillRule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clipRule="evenodd" />
814
+ </svg>
815
+ Show more
816
+ </button>
817
+ )}
818
+ {expanded && (
819
+ <button
820
+ onClick={generateMoreKeywords}
821
+ disabled={isGeneratingMore}
822
+ style={{
823
+ marginTop: 6, width: "100%", padding: "5px 0", background: "none", border: "none",
824
+ cursor: isGeneratingMore ? "wait" : "pointer", fontSize: 10,
825
+ color: isGeneratingMore ? "#9ca3af" : MJH_BLUE,
826
+ display: "flex", alignItems: "center", justifyContent: "center", gap: 4, fontWeight: 500,
827
+ }}
828
+ >
829
+ {isGeneratingMore ? (
830
+ <>
831
+ <LoadingBars size="xs" color={MJH_BLUE} />
832
+ Generating...
833
+ </>
834
+ ) : (
835
+ <>
836
+ <svg width="10" height="10" viewBox="0 0 20 20" fill={MJH_BLUE}>
837
+ <path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H4.598a.75.75 0 00-.75.75v3.634a.75.75 0 001.5 0v-2.033l.312.311a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm-10.624-2.85a5.5 5.5 0 019.201-2.466l.312.311h-2.433a.75.75 0 000 1.5h3.634a.75.75 0 00.75-.75V3.535a.75.75 0 00-1.5 0v2.033l-.312-.311A7 7 0 002.628 8.395a.75.75 0 001.449.39z" clipRule="evenodd" />
838
+ </svg>
839
+ Generate more
840
+ </>
841
+ )}
842
+ </button>
843
+ )}
844
+ </div>
845
+ );
846
+ }
847
+
848
+
849
+ export function KeywordPanel({
850
+ text,
851
+ publication,
852
+ seedKeywords = [],
853
+ onSeedsChange,
854
+ onSelectPrimary,
855
+ documentFields,
856
+ externalAnalysis,
857
+ }: KeywordPanelProps) {
858
+ const { apiUrl } = useConfig();
859
+ const internalAnalysis = useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFields);
860
+ const activeAnalysis = externalAnalysis || internalAnalysis;
861
+ const { analysis, isLoading, error, deepAnalysis, isDeepLoading, runDeepAnalysis } = activeAnalysis;
862
+ const isVolumesLoading = (activeAnalysis as { isVolumesLoading?: boolean }).isVolumesLoading ?? false;
863
+ const refreshVolumes = (activeAnalysis as { refreshVolumes?: () => void }).refreshVolumes;
864
+ const aeoContentChanged = activeAnalysis.aeoContentChanged ?? false;
865
+
866
+ // Auto-trigger AEO when analysis first loads (no button click needed)
867
+ // Auto-trigger AEO - always run deep analysis once keywords are ready
868
+ const [aeoTriggered, setAeoTriggered] = useState(false);
869
+ useEffect(() => {
870
+ // Only check V2 fields for AEO content. Ignore legacy faqItems from old cache.
871
+ const hasV2Aeo = deepAnalysis?.aeo?.questionHeadings?.length || deepAnalysis?.aeo?.faqSuggestions?.length;
872
+ if (analysis && !hasV2Aeo && !isDeepLoading && !aeoTriggered) {
873
+ setAeoTriggered(true);
874
+ // Start immediately - no delay
875
+ runDeepAnalysis();
876
+ }
877
+ }, [analysis, deepAnalysis, isDeepLoading, aeoTriggered, runDeepAnalysis]);
878
+
879
+ // Reset AEO trigger when text changes significantly
880
+ useEffect(() => {
881
+ setAeoTriggered(false);
882
+ }, [text]);
883
+
884
+ // "More FAQ suggestions" state
885
+ const [moreFaqs, setMoreFaqs] = useState<{ question: string; answer: string }[]>([]);
886
+ const [isMoreFaqsLoading, setIsMoreFaqsLoading] = useState(false);
887
+ const loadMoreFaqs = useCallback(async () => {
888
+ const aeo = deepAnalysis?.aeo;
889
+ const existingQs = [...(aeo?.faqSuggestions ?? aeo?.faqItems ?? []).map((f: { question: string }) => f.question), ...moreFaqs.map(f => f.question)];
890
+ setIsMoreFaqsLoading(true);
891
+ try {
892
+ const res = await fetch(`${apiUrl}/api/seo-copilot/more-faqs`, {
893
+ method: "POST",
894
+ headers: { "Content-Type": "application/json" },
895
+ body: JSON.stringify({ content: text, existingQuestions: existingQs, publication }),
896
+ });
897
+ if (res.ok) {
898
+ const data = await res.json();
899
+ setMoreFaqs(prev => [...prev, ...(data.faqSuggestions || [])]);
900
+ }
901
+ } catch { /* silent */ }
902
+ setIsMoreFaqsLoading(false);
903
+ }, [deepAnalysis, moreFaqs, apiUrl, text, publication]);
904
+
905
+ // Selected primary keyword term (user can override)
906
+ const defaultSelectedTerm = analysis?.primaryKeyword?.term ?? "";
907
+ const [selectedPrimaryTerm, setSelectedPrimaryTerm] = useState(defaultSelectedTerm);
908
+ const prevDefaultRef = useRef(defaultSelectedTerm);
909
+
910
+ // Auto-update selected term when analysis refreshes (unless user manually picked a different one)
911
+ useEffect(() => {
912
+ if (defaultSelectedTerm && defaultSelectedTerm !== prevDefaultRef.current) {
913
+ // Only auto-update if user's current selection was the old default (they haven't overridden)
914
+ setSelectedPrimaryTerm((prev) => prev === prevDefaultRef.current ? defaultSelectedTerm : prev);
915
+ prevDefaultRef.current = defaultSelectedTerm;
916
+ }
917
+ }, [defaultSelectedTerm]);
918
+
919
+ if ((!text || text.trim().length < 20) && (!seedKeywords || seedKeywords.length === 0)) {
920
+ return (
921
+ <div style={{ padding: 24, textAlign: "center" }}>
922
+ <div style={{ fontSize: 14, color: "#9ca3af", fontWeight: 500 }}>
923
+ Start writing to see keyword suggestions
924
+ </div>
925
+ <div style={{ fontSize: 12, color: "#d1d5db", marginTop: 4 }}>
926
+ Need at least a few sentences
927
+ </div>
928
+ </div>
929
+ );
930
+ }
931
+
932
+ if (isLoading && !analysis) {
933
+ return (
934
+ <div style={{ padding: 24, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
935
+ <LoadingBars />
936
+ <span style={{ fontSize: 12, color: "#9ca3af" }}>Analyzing content...</span>
937
+ </div>
938
+ );
939
+ }
940
+
941
+ if (error && !analysis) {
942
+ return (
943
+ <div style={{ ...cardStyle, margin: 12, background: "#fef2f2", color: "#dc2626" }}>
944
+ <span style={{ fontSize: 12 }}>Error: {error}</span>
945
+ </div>
946
+ );
947
+ }
948
+
949
+ if (!analysis) return null;
950
+
951
+ const suggestedKeywords = buildSuggestedKeywords(
952
+ analysis.supportingKeywords || [],
953
+ analysis.missingKeywords,
954
+ text
955
+ );
956
+
957
+ // Build candidates list - use primaryKeywordCandidates if available, else fallback to single primaryKeyword
958
+ const candidates: PrimaryKeywordCandidate[] = analysis.primaryKeywordCandidates && analysis.primaryKeywordCandidates.length > 0
959
+ ? analysis.primaryKeywordCandidates
960
+ : [analysis.primaryKeyword];
961
+
962
+ // Ensure selectedPrimaryTerm is in candidates, otherwise default to first
963
+ const activeTerm = candidates.find((c) => c.term === selectedPrimaryTerm)
964
+ ? selectedPrimaryTerm
965
+ : candidates[0]?.term ?? "";
966
+
967
+ return (
968
+ <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 12 }}>
969
+ {/* Seed Keywords */}
970
+ {onSeedsChange && (
971
+ <SeedKeywordInput seeds={seedKeywords} onSeedsChange={onSeedsChange} />
972
+ )}
973
+
974
+ {/* Primary Keyword Selector */}
975
+ <PrimaryKeywordSelector
976
+ candidates={candidates}
977
+ selectedTerm={activeTerm}
978
+ onSelect={(term: string) => { setSelectedPrimaryTerm(term); onSelectPrimary?.(term); }}
979
+ publication={publication}
980
+ />
981
+
982
+ {/* Supporting Keywords */}
983
+ {suggestedKeywords.length > 0 && (
984
+ <SuggestedKeywordsCard
985
+ keywords={suggestedKeywords}
986
+ text={text}
987
+ apiUrl={apiUrl}
988
+ publication={publication}
989
+ documentFields={documentFields}
990
+ refreshVolumes={refreshVolumes}
991
+ isVolumesLoading={isVolumesLoading}
992
+ />
993
+ )}
994
+
995
+ {/* AEO Section - auto-generates, no button */}
996
+ {!deepAnalysis && isDeepLoading ? (
997
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "12px 0" }}>
998
+ <LoadingBars size="xs" color={AEO_PURPLE} />
999
+ <span style={{ fontSize: 12, color: "#9ca3af" }}>Generating AEO insights...</span>
1000
+ </div>
1001
+ ) : deepAnalysis ? (
1002
+ <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
1003
+
1004
+ {/* AI Disclaimer */}
1005
+ <div style={{ padding: "6px 10px", background: "#fefce8", borderRadius: 8, border: "1px solid #fde68a" }}>
1006
+ <div style={{ fontSize: 10, color: "#92400e", lineHeight: 1.5 }}>
1007
+ Answers generated by AI may contain inaccuracies. Always verify facts, drug information, and clinical details before publishing.
1008
+ </div>
1009
+ </div>
1010
+
1011
+ {/* Intro - explains both AEO approaches */}
1012
+ {/* AEO Section Header */}
1013
+ <div style={{ ...cardStyle, padding: "8px 14px", background: "rgba(124,58,237,0.03)", borderLeft: "3px solid " + AEO_PURPLE }}>
1014
+ <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
1015
+ <div style={{ width: 7, height: 7, borderRadius: "50%", background: AEO_PURPLE, flexShrink: 0 }} />
1016
+ <span style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8", fontWeight: 600 }}>AEO Insights</span>
1017
+ </div>
1018
+ </div>
1019
+
1020
+ {!deepAnalysis.aeo && (
1021
+ <div style={{ ...cardStyle, textAlign: "center" }}>
1022
+ <span style={{ fontSize: 12, color: "#9ca3af" }}>No AEO data was returned. Try again - the analysis may have timed out.</span>
1023
+ </div>
1024
+ )}
1025
+
1026
+ {/* Section 1: Question Headline Recommendations */}
1027
+ {deepAnalysis.aeo && (deepAnalysis.aeo.questionHeadings ?? deepAnalysis.aeo.headingSuggestions ?? []).length > 0 && (
1028
+ <div style={cardStyle}>
1029
+ <SectionHeader label="Question Headline Recommendations" iconColor={AEO_PURPLE} />
1030
+ <div style={{ fontSize: 10, color: "#9ca3af", marginBottom: 8, marginTop: -4 }}>
1031
+ Rewrite your headings as questions. Google targets these for featured snippets.
1032
+ </div>
1033
+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
1034
+ {(deepAnalysis.aeo.questionHeadings?.map((qh) => ({ heading: qh.suggestedHeading, originalHeading: qh.originalHeading, rationale: qh.rationale })) ?? deepAnalysis.aeo.headingSuggestions?.map((h) => ({ heading: h.heading, originalHeading: undefined as string | undefined, rationale: h.rationale })) ?? []).map((h, i) => (
1035
+ <div key={i} style={{ padding: "8px 10px", background: "rgba(124,58,237,0.03)", borderRadius: 10, borderLeft: "3px solid " + AEO_PURPLE }}>
1036
+ <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }}>
1037
+ <div style={{ flex: 1 }}>
1038
+ {h.originalHeading && (
1039
+ <div style={{ fontSize: 11, color: "#9ca3af", textDecoration: "line-through", marginBottom: 2 }}>
1040
+ {h.originalHeading}
1041
+ </div>
1042
+ )}
1043
+ <div style={{ fontSize: 12, fontWeight: 700, color: AEO_PURPLE, lineHeight: 1.5 }}>
1044
+ {h.heading}
1045
+ </div>
1046
+ </div>
1047
+ <FeedbackButton
1048
+ suggestionType="aeo_heading"
1049
+ suggestionText={h.heading}
1050
+ publication={publication}
1051
+ />
1052
+ </div>
1053
+ <div style={{ fontSize: 10, color: "#9ca3af", marginTop: 4, fontStyle: "italic" }}>
1054
+ {h.rationale}
1055
+ </div>
1056
+ </div>
1057
+ ))}
1058
+ </div>
1059
+ </div>
1060
+ )}
1061
+
1062
+ {/* Section 2: FAQ Suggestions */}
1063
+ {(() => {
1064
+ const faqs = deepAnalysis.aeo ? [...(deepAnalysis.aeo.faqSuggestions ?? deepAnalysis.aeo.faqItems ?? []), ...moreFaqs] : [];
1065
+ return faqs.length > 0 ? (
1066
+ <div style={cardStyle}>
1067
+ <SectionHeader label="FAQ Suggestions" iconColor={AEO_PURPLE} />
1068
+ <div style={{ fontSize: 10, color: "#9ca3af", marginBottom: 8, marginTop: -4 }}>
1069
+ Add these Q&As at the bottom of your article. Answers are derived from your article content. Can be wrapped with FAQ schema markup.
1070
+ </div>
1071
+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
1072
+ {faqs.map((faq, i) => (
1073
+ <div key={i} style={{ padding: "8px 10px", background: "rgba(124,58,237,0.03)", borderRadius: 10, borderLeft: "3px solid " + AEO_PURPLE }}>
1074
+ <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }}>
1075
+ <span style={{ fontSize: 12, fontWeight: 700, color: "#1f2937", lineHeight: 1.5 }}>
1076
+ Q: {faq.question}
1077
+ </span>
1078
+ <FeedbackButton
1079
+ suggestionType="aeo_faq"
1080
+ suggestionText={faq.question}
1081
+ publication={publication}
1082
+ />
1083
+ </div>
1084
+ <div style={{ fontSize: 12, color: "#374151", lineHeight: 1.6, marginTop: 4 }}>
1085
+ <span style={{ fontWeight: 600, color: "#6b7280" }}>A: </span>{faq.answer}
1086
+ </div>
1087
+ </div>
1088
+ ))}
1089
+ </div>
1090
+ {/* More FAQ suggestions button */}
1091
+ <button
1092
+ onClick={loadMoreFaqs}
1093
+ disabled={isMoreFaqsLoading}
1094
+ style={{
1095
+ marginTop: 8,
1096
+ width: "100%",
1097
+ padding: "6px 12px",
1098
+ fontSize: 11,
1099
+ fontWeight: 600,
1100
+ color: isMoreFaqsLoading ? "#9ca3af" : AEO_PURPLE,
1101
+ background: isMoreFaqsLoading ? "#f3f4f6" : "rgba(124,58,237,0.06)",
1102
+ border: "1px solid rgba(124,58,237,0.15)",
1103
+ borderRadius: 6,
1104
+ cursor: isMoreFaqsLoading ? "wait" : "pointer",
1105
+ display: "flex",
1106
+ alignItems: "center",
1107
+ justifyContent: "center",
1108
+ gap: 6,
1109
+ transition: "all 150ms",
1110
+ }}
1111
+ >
1112
+ {isMoreFaqsLoading ? (
1113
+ <><LoadingBars size="xs" color={AEO_PURPLE} /> Generating...</>
1114
+ ) : (
1115
+ "More FAQ suggestions"
1116
+ )}
1117
+ </button>
1118
+ </div>
1119
+ ) : null;
1120
+ })()}
1121
+
1122
+ {/* Content changed notification */}
1123
+ {aeoContentChanged && (
1124
+ <div
1125
+ onClick={runDeepAnalysis}
1126
+ style={{
1127
+ padding: "8px 12px",
1128
+ background: "#fffbeb",
1129
+ border: "1px solid #fde68a",
1130
+ borderRadius: 8,
1131
+ display: "flex",
1132
+ alignItems: "center",
1133
+ justifyContent: "space-between",
1134
+ cursor: "pointer",
1135
+ }}
1136
+ >
1137
+ <span style={{ fontSize: 11, color: "#92400e" }}>
1138
+ Content has changed since this was generated.
1139
+ </span>
1140
+ <span style={{ fontSize: 11, fontWeight: 600, color: AEO_PURPLE, textDecoration: "underline" }}>
1141
+ Update
1142
+ </span>
1143
+ </div>
1144
+ )}
1145
+ </div>
1146
+ ) : null}
1147
+
1148
+ {/* Volumes loading indicator - shows while SEMrush data is being fetched */}
1149
+ {isVolumesLoading && (
1150
+ <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", padding: "4px 0" }}>
1151
+ <LoadingBars size="xs" color={MJH_GOLD} />
1152
+ <span style={{ fontSize: 10, color: "#9ca3af" }}>Checking search volumes...</span>
1153
+ </div>
1154
+ )}
1155
+
1156
+ {/* Updating indicator */}
1157
+ {isLoading && analysis && (
1158
+ <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }}>
1159
+ <LoadingBars size="xs" color="#9ca3af" />
1160
+ <span style={{ fontSize: 10, color: "#9ca3af" }}>Updating insights...</span>
1161
+ </div>
1162
+ )}
1163
+ </div>
1164
+ );
1165
+ }