sanity-plugin-seo-copilot 0.1.2 → 0.2.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.
@@ -2,12 +2,21 @@ import { useState, useRef, useCallback, useEffect, useMemo, Suspense } from "rea
2
2
  import { createPortal } from "react-dom";
3
3
  import { useDocumentContent } from "../hooks/useDocumentContent";
4
4
  import { useKeywordAnalysis } from "../hooks/useKeywordAnalysis";
5
+ import { useSEOChat } from "../hooks/useSEOChat";
5
6
  import { useConfig, ConfigProvider } from "./ConfigContext";
6
7
  import { KeywordPanel } from "./KeywordPanel";
7
8
  import { ChatPanel } from "./ChatPanel";
8
- import { INJECTED_CSS, MJH_GOLD, MJH_BLUE, MJH_SLATE } from "./styles";
9
+ import { TabBar } from "./TabBar";
10
+ import { SummaryTab } from "./tabs/SummaryTab";
11
+ import { AEOTab } from "./tabs/AEOTab";
12
+ import { LinkingTab } from "./tabs/LinkingTab";
13
+ import { MetaTab } from "./tabs/MetaTab";
14
+ import { TechnicalTab } from "./tabs/TechnicalTab";
15
+ import { INJECTED_CSS, MJH_GOLD, MJH_BLUE, MJH_SLATE, PANEL_BG, CHAT_ZONE_BG, RECS_ZONE_BG } from "./styles";
16
+ import { fetchContentSuggestions, fetchLinkingSuggestions, checkLinks } from "../lib/api";
17
+ import { usePersistentState, loadLocal, saveLocal } from "../lib/persistence";
9
18
  import type { SEOCopilotConfig } from "../index";
10
- import type { SEOAnalysis, DeepAnalysis } from "../lib/types";
19
+ import type { SEOAnalysis, DeepAnalysis, TabId, ChatMessage, ContentSuggestions, LinkingSuggestion, SummaryItem, LinkCheckResult } from "../lib/types";
11
20
 
12
21
  interface SEOCopilotPanelProps {
13
22
  config: SEOCopilotConfig;
@@ -36,8 +45,18 @@ interface PanelContentProps {
36
45
  seedKeywords: string[];
37
46
  onSeedsChange: (seeds: string[]) => void;
38
47
  text: string;
48
+ docLoading: boolean;
39
49
  documentFields: import("../lib/types").DocumentFields;
50
+ documentId?: string;
51
+ selectedPrimary?: string;
40
52
  onSelectPrimary?: (term: string) => void;
53
+ // Lifted state - survives float/dock toggle (which remounts PanelContent)
54
+ activeTab: TabId;
55
+ onActiveTabChange: (id: TabId) => void;
56
+ chatOpen: boolean;
57
+ onChatOpenChange: (open: boolean) => void;
58
+ splitPercent: number;
59
+ onSplitPercentChange: (pct: number) => void;
41
60
  externalAnalysis: {
42
61
  analysis: SEOAnalysis | null;
43
62
  isLoading: boolean;
@@ -49,38 +68,80 @@ interface PanelContentProps {
49
68
  refreshVolumes: () => void;
50
69
  aeoContentChanged: boolean;
51
70
  };
71
+ chatState: {
72
+ messages: ChatMessage[];
73
+ isStreaming: boolean;
74
+ sendMessage: (text: string) => Promise<void>;
75
+ clearChat: () => void;
76
+ };
77
+ aeoOps: {
78
+ contentSuggestions: ContentSuggestions | null;
79
+ isCSLoading: boolean;
80
+ csError: string | null;
81
+ loadContentSuggestions: () => void;
82
+ };
83
+ linkingOps: {
84
+ suggestions: LinkingSuggestion[];
85
+ isLoading: boolean;
86
+ error: string | null;
87
+ isStale: boolean;
88
+ refresh: () => void;
89
+ };
90
+ technicalOps: {
91
+ linkCheckResults: LinkCheckResult[];
92
+ isLinkCheckLoading: boolean;
93
+ linkCheckError: string | null;
94
+ hasRunLinkCheck: boolean;
95
+ onCheckLinks: () => void;
96
+ };
97
+ summaryOps: {
98
+ isAnyLoading: boolean;
99
+ onGenerateAll: () => void;
100
+ onItemClick: (item: SummaryItem) => void;
101
+ };
52
102
  }
53
103
 
54
- function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFloat, onToggleFullscreen, onClose, floatPos: _floatPos, onDragStart, seedKeywords, onSeedsChange, text, documentFields, onSelectPrimary, externalAnalysis }: PanelContentProps) {
104
+ function PanelContent({
105
+ initialPublication,
106
+ isFloating,
107
+ isFullscreen,
108
+ onToggleFloat,
109
+ onToggleFullscreen,
110
+ onClose,
111
+ floatPos: _floatPos,
112
+ onDragStart,
113
+ seedKeywords,
114
+ onSeedsChange,
115
+ text,
116
+ docLoading,
117
+ documentFields,
118
+ documentId,
119
+ selectedPrimary,
120
+ onSelectPrimary,
121
+ activeTab,
122
+ onActiveTabChange,
123
+ chatOpen,
124
+ onChatOpenChange,
125
+ splitPercent,
126
+ onSplitPercentChange,
127
+ externalAnalysis,
128
+ chatState,
129
+ aeoOps,
130
+ linkingOps,
131
+ technicalOps,
132
+ summaryOps,
133
+ }: PanelContentProps) {
55
134
  const publication = initialPublication;
56
- const [keywordsOpen, setKeywordsOpen] = useState(true);
57
- const [chatOpen, setChatOpen] = useState(true);
58
135
  const isLoading = externalAnalysis.isLoading;
59
136
  const keywordAnalysisState = externalAnalysis;
60
137
 
61
- // Build keyword panel data for the chat
62
- const keywordPanelData = useMemo(() => {
63
- const { analysis } = keywordAnalysisState;
64
- if (!analysis) return undefined;
65
- return {
66
- primaryKeyword: { term: analysis.primaryKeyword.term, volume: analysis.primaryKeyword.volume },
67
- supportingKeywords: (analysis.supportingKeywords || []).map((kw) => ({ term: kw.term, volume: kw.volume })),
68
- missingKeywords: analysis.missingKeywords.map((kw) => ({ term: kw.term, volume: kw.volume })),
69
- aeoData: keywordAnalysisState.deepAnalysis?.aeo ? {
70
- questionHeadings: (keywordAnalysisState.deepAnalysis.aeo.questionHeadings || []).map((h) => ({
71
- suggestedHeading: h.suggestedHeading,
72
- rationale: h.rationale,
73
- })),
74
- faqSuggestions: (keywordAnalysisState.deepAnalysis.aeo.faqSuggestions || []).map((f) => ({
75
- question: f.question,
76
- answer: f.answer,
77
- })),
78
- } : undefined,
79
- };
80
- }, [keywordAnalysisState.analysis, keywordAnalysisState.deepAnalysis]);
138
+ // Effective primary keyword (selected override else top candidate from analysis)
139
+ const effectivePrimary =
140
+ selectedPrimary ||
141
+ externalAnalysis.analysis?.primaryKeyword?.term ||
142
+ "";
81
143
 
82
- // Draggable divider
83
- const [splitPercent, setSplitPercent] = useState(75);
144
+ // Draggable divider between tab content and chat - splitPercent is lifted to parent for persistence
84
145
  const containerRef = useRef<HTMLDivElement>(null);
85
146
  const dragging = useRef(false);
86
147
 
@@ -95,7 +156,7 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
95
156
  if (!dragging.current || !containerRef.current) return;
96
157
  const rect = containerRef.current.getBoundingClientRect();
97
158
  const pct = ((e.clientY - rect.top) / rect.height) * 100;
98
- setSplitPercent(Math.min(85, Math.max(15, pct)));
159
+ onSplitPercentChange(Math.min(85, Math.max(15, pct)));
99
160
  };
100
161
  const onMouseUp = () => {
101
162
  dragging.current = false;
@@ -108,13 +169,32 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
108
169
  window.removeEventListener("mousemove", onMouseMove);
109
170
  window.removeEventListener("mouseup", onMouseUp);
110
171
  };
111
- }, []);
172
+ }, [onSplitPercentChange]);
112
173
 
113
- // Header cursor: grab when floating (draggable), default otherwise
114
174
  const headerCursor = isFloating ? "grab" : "default";
115
175
 
176
+ const tabDefs = [
177
+ { id: "summary" as TabId, label: "Summary", isHub: true, loading: summaryOps.isAnyLoading },
178
+ { id: "keywords" as TabId, label: "Keywords", loading: keywordAnalysisState.isLoading || keywordAnalysisState.isVolumesLoading },
179
+ { id: "aeo" as TabId, label: "AEO/GEO", loading: keywordAnalysisState.isDeepLoading },
180
+ { id: "linking" as TabId, label: "Linking", beta: true, loading: linkingOps.isLoading },
181
+ { id: "meta" as TabId, label: "Meta", beta: true },
182
+ { id: "technical" as TabId, label: "Other Recs", beta: true, loading: technicalOps.isLinkCheckLoading },
183
+ ];
184
+
116
185
  return (
117
- <div className="seo-copilot-panel" style={{ height: "100%", display: "flex", flexDirection: "column", background: "#FBFAF7", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif", opacity: 1 }}>
186
+ <div
187
+ className="seo-copilot-panel"
188
+ style={{
189
+ height: "100%",
190
+ display: "flex",
191
+ flexDirection: "column",
192
+ // backgroundColor (longhand) so the sheen background-image in INJECTED_CSS isn't reset
193
+ backgroundColor: PANEL_BG,
194
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",
195
+ opacity: 1,
196
+ }}
197
+ >
118
198
  <style dangerouslySetInnerHTML={{ __html: INJECTED_CSS }} />
119
199
 
120
200
  {/* Header */}
@@ -126,7 +206,7 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
126
206
  alignItems: "center",
127
207
  justifyContent: "space-between",
128
208
  padding: "14px 16px",
129
- background: "linear-gradient(180deg, #FFFFFF 0%, #FBFAF7 100%)",
209
+ background: `linear-gradient(180deg, #FFFFFF 0%, ${PANEL_BG} 100%)`,
130
210
  boxShadow: "0 1px 0 rgba(0,0,0,0.04)",
131
211
  zIndex: 10,
132
212
  cursor: headerCursor,
@@ -134,19 +214,20 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
134
214
  flexShrink: 0,
135
215
  }}
136
216
  >
137
- {/* Logo - vertically centered in header */}
138
217
  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
139
218
  <LogoIcon />
140
219
  <span style={{ fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }}>
141
220
  <span style={{ color: MJH_GOLD }}>SEO</span>
142
221
  <span style={{ color: MJH_SLATE }}> copilot</span>
143
222
  </span>
144
- </div>
223
+ </div>
145
224
  <div style={{ display: "flex", alignItems: "center", gap: isFloating ? 4 : 6 }}>
146
- {/* When floating: labeled action buttons */}
147
225
  {isFloating && onToggleFullscreen && (
148
226
  <button
149
- onClick={(e) => { e.stopPropagation(); onToggleFullscreen(); }}
227
+ onClick={(e) => {
228
+ e.stopPropagation();
229
+ onToggleFullscreen();
230
+ }}
150
231
  onMouseDown={(e) => e.stopPropagation()}
151
232
  style={{
152
233
  background: isFullscreen ? "rgba(230,192,27,0.15)" : "rgba(0,0,0,0.04)",
@@ -182,7 +263,10 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
182
263
  )}
183
264
  {isFloating && onToggleFloat && (
184
265
  <button
185
- onClick={(e) => { e.stopPropagation(); onToggleFloat(); }}
266
+ onClick={(e) => {
267
+ e.stopPropagation();
268
+ onToggleFloat();
269
+ }}
186
270
  onMouseDown={(e) => e.stopPropagation()}
187
271
  style={{
188
272
  background: "rgba(0,93,172,0.08)",
@@ -200,15 +284,21 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
200
284
  }}
201
285
  >
202
286
  <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor">
203
- <path fillRule="evenodd" d="M4.25 2A2.25 2.25 0 002 4.25v11.5A2.25 2.25 0 004.25 18h11.5A2.25 2.25 0 0018 15.75V4.25A2.25 2.25 0 0015.75 2H4.25zM3.5 4.25a.75.75 0 01.75-.75h11.5a.75.75 0 01.75.75v11.5a.75.75 0 01-.75.75H4.25a.75.75 0 01-.75-.75V4.25z" clipRule="evenodd" />
287
+ <path
288
+ fillRule="evenodd"
289
+ d="M4.25 2A2.25 2.25 0 002 4.25v11.5A2.25 2.25 0 004.25 18h11.5A2.25 2.25 0 0018 15.75V4.25A2.25 2.25 0 0015.75 2H4.25zM3.5 4.25a.75.75 0 01.75-.75h11.5a.75.75 0 01.75.75v11.5a.75.75 0 01-.75.75H4.25a.75.75 0 01-.75-.75V4.25z"
290
+ clipRule="evenodd"
291
+ />
204
292
  </svg>
205
293
  Dock
206
294
  </button>
207
295
  )}
208
- {/* When docked: small icon buttons */}
209
296
  {!isFloating && onToggleFloat && (
210
297
  <button
211
- onClick={(e) => { e.stopPropagation(); onToggleFloat(); }}
298
+ onClick={(e) => {
299
+ e.stopPropagation();
300
+ onToggleFloat();
301
+ }}
212
302
  onMouseDown={(e) => e.stopPropagation()}
213
303
  style={{
214
304
  background: "none",
@@ -229,12 +319,22 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
229
319
  </button>
230
320
  )}
231
321
  {isLoading && (
232
- <div style={{ width: 8, height: 8, borderRadius: "50%", background: MJH_GOLD, animation: "content-pulse 2s ease-in-out infinite" }} />
322
+ <div
323
+ style={{
324
+ width: 8,
325
+ height: 8,
326
+ borderRadius: "50%",
327
+ background: MJH_GOLD,
328
+ animation: "content-pulse 2s ease-in-out infinite",
329
+ }}
330
+ />
233
331
  )}
234
- {/* Close button - always visible */}
235
332
  {onClose && (
236
333
  <button
237
- onClick={(e) => { e.stopPropagation(); onClose(); }}
334
+ onClick={(e) => {
335
+ e.stopPropagation();
336
+ onClose();
337
+ }}
238
338
  onMouseDown={(e) => e.stopPropagation()}
239
339
  style={{
240
340
  background: "none",
@@ -254,55 +354,131 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
254
354
  </button>
255
355
  )}
256
356
  </div>
257
- {/* Tagline - absolute positioned, not affecting vertical centering */}
258
- <div style={{
259
- position: "absolute",
260
- bottom: 3,
261
- left: 38,
262
- fontSize: 9,
263
- color: "#b0b8c4",
264
- fontWeight: 400,
265
- fontStyle: "italic",
266
- letterSpacing: "0.02em",
267
- }}>
357
+ <div
358
+ style={{
359
+ position: "absolute",
360
+ bottom: 3,
361
+ left: 38,
362
+ fontSize: 9,
363
+ color: "rgba(0,0,0,0.42)",
364
+ fontWeight: 400,
365
+ fontStyle: "italic",
366
+ letterSpacing: "0.02em",
367
+ }}
368
+ >
268
369
  More eyes on your expertise
269
370
  </div>
270
371
  </div>
271
372
 
272
- {/* Split View */}
373
+ {/* Tab Bar */}
374
+ <TabBar tabs={tabDefs} activeTab={activeTab} onTabChange={onActiveTabChange} />
375
+
376
+ {/* Universal AI disclaimer - lives once at the panel level so every tab
377
+ inherits it. Subtle muted strip; the editor sees it on every screen. */}
378
+ <div
379
+ style={{
380
+ padding: "5px 12px",
381
+ fontSize: 10,
382
+ color: "#6b7280",
383
+ lineHeight: 1.4,
384
+ textAlign: "center",
385
+ background: "rgba(255,255,255,0.45)",
386
+ borderBottom: "1px solid rgba(0,0,0,0.06)",
387
+ flexShrink: 0,
388
+ }}
389
+ >
390
+ Recommendations are generated by AI. Verify details before publishing.
391
+ </div>
392
+
393
+ {/* Tab content + chat split */}
273
394
  <div ref={containerRef} style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
274
- {/* Keywords Section */}
275
- <div style={{ height: keywordsOpen ? (chatOpen ? `${splitPercent}%` : "100%") : "auto", overflow: keywordsOpen ? "auto" : "hidden", flexShrink: keywordsOpen ? undefined : 0 }}>
276
- <button
277
- onClick={() => setKeywordsOpen(!keywordsOpen)}
278
- style={{ width: "100%", padding: "4px 12px", display: "flex", alignItems: "center", justifyContent: "space-between", background: "transparent", border: "none", borderBottom: "1px solid rgba(0,0,0,0.06)", cursor: "pointer" }}
279
- >
280
- <span style={{ display: "flex", alignItems: "center", gap: 6, flex: 1 }}>
281
- <span style={{ fontSize: 10, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", color: "#9ca3af" }}>Keywords & AEO Insights</span>
282
- {(keywordAnalysisState.isLoading || keywordAnalysisState.isVolumesLoading || keywordAnalysisState.isDeepLoading) && (
283
- <LoadingBars size="xs" color="#9ca3af" />
284
- )}
285
- </span>
286
- <svg width="12" height="12" viewBox="0 0 20 20" fill="#9ca3af" style={{ transform: keywordsOpen ? "rotate(0deg)" : "rotate(-90deg)", transition: "transform 200ms" }}>
287
- <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" />
288
- </svg>
289
- </button>
290
- {/* Always mounted to preserve state; hidden when collapsed. key=publication forces reload on brand change */}
291
- <div style={{ display: keywordsOpen ? "block" : "none" }}>
395
+ {/* Tab content area (the "recommendations" zone) - all tabs mounted, hidden
396
+ when inactive to preserve state. Carries the warm gold zone gradient that
397
+ mirrors the chat's blue gradient below (gold = analysis, blue = chat). */}
398
+ <div
399
+ style={{
400
+ height: chatOpen ? `${splitPercent}%` : undefined,
401
+ flex: chatOpen ? undefined : 1,
402
+ overflow: "auto",
403
+ minHeight: 0,
404
+ background: RECS_ZONE_BG,
405
+ }}
406
+ >
407
+ <div style={{ display: activeTab === "keywords" ? "block" : "none" }}>
408
+ {/* key forces full remount when document changes so all internal state resets cleanly */}
292
409
  <KeywordPanel
410
+ key={documentId || "default"}
293
411
  text={text}
294
412
  publication={publication}
295
413
  seedKeywords={seedKeywords}
296
414
  onSeedsChange={onSeedsChange}
297
415
  onSelectPrimary={onSelectPrimary}
298
416
  documentFields={documentFields}
417
+ documentId={documentId}
299
418
  externalAnalysis={keywordAnalysisState}
300
419
  />
301
420
  </div>
421
+ <div style={{ display: activeTab === "summary" ? "block" : "none" }}>
422
+ <SummaryTab
423
+ text={text}
424
+ analysis={keywordAnalysisState.analysis}
425
+ deepAnalysis={keywordAnalysisState.deepAnalysis}
426
+ documentFields={documentFields}
427
+ linkingSuggestions={linkingOps.suggestions}
428
+ linkCheckResults={technicalOps.linkCheckResults}
429
+ isAnyLoading={summaryOps.isAnyLoading}
430
+ onGenerateAll={summaryOps.onGenerateAll}
431
+ onItemClick={summaryOps.onItemClick}
432
+ />
433
+ </div>
434
+ <div style={{ display: activeTab === "aeo" ? "block" : "none" }}>
435
+ <AEOTab
436
+ text={text}
437
+ deepAnalysis={keywordAnalysisState.deepAnalysis}
438
+ isDeepLoading={keywordAnalysisState.isDeepLoading}
439
+ primaryKeyword={effectivePrimary}
440
+ publication={publication}
441
+ runDeepAnalysis={keywordAnalysisState.runDeepAnalysis}
442
+ aeoContentChanged={keywordAnalysisState.aeoContentChanged}
443
+ headings={documentFields?.headings}
444
+ contentSuggestions={aeoOps.contentSuggestions}
445
+ isCSLoading={aeoOps.isCSLoading}
446
+ csError={aeoOps.csError}
447
+ loadContentSuggestions={aeoOps.loadContentSuggestions}
448
+ />
449
+ </div>
450
+ <div style={{ display: activeTab === "linking" ? "block" : "none" }}>
451
+ <LinkingTab
452
+ analysis={keywordAnalysisState.analysis}
453
+ suggestions={linkingOps.suggestions}
454
+ isLoading={linkingOps.isLoading}
455
+ error={linkingOps.error}
456
+ isStale={linkingOps.isStale}
457
+ onRefresh={linkingOps.refresh}
458
+ documentId={documentId}
459
+ publication={publication}
460
+ text={text}
461
+ />
462
+ </div>
463
+ <div style={{ display: activeTab === "meta" ? "block" : "none" }}>
464
+ <MetaTab documentFields={documentFields} primaryKeyword={effectivePrimary} isLoading={docLoading} />
465
+ </div>
466
+ <div style={{ display: activeTab === "technical" ? "block" : "none" }}>
467
+ <TechnicalTab
468
+ text={text}
469
+ documentFields={documentFields}
470
+ isLoading={docLoading}
471
+ linkCheckResults={technicalOps.linkCheckResults}
472
+ isLinkCheckLoading={technicalOps.isLinkCheckLoading}
473
+ linkCheckError={technicalOps.linkCheckError}
474
+ hasRunLinkCheck={technicalOps.hasRunLinkCheck}
475
+ onCheckLinks={technicalOps.onCheckLinks}
476
+ />
477
+ </div>
302
478
  </div>
303
479
 
304
- {/* Draggable Divider - only when both open */}
305
- {keywordsOpen && chatOpen && (
480
+ {/* Draggable Divider */}
481
+ {chatOpen && (
306
482
  <div
307
483
  onMouseDown={onMouseDown}
308
484
  style={{
@@ -319,118 +495,418 @@ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFl
319
495
  </div>
320
496
  )}
321
497
 
322
- {/* Chat Section - fills entire panel when keywords collapsed */}
323
- <div style={{
324
- flex: chatOpen && !keywordsOpen ? 1 : undefined,
325
- height: chatOpen ? (keywordsOpen ? `${100 - splitPercent}%` : undefined) : "auto",
326
- overflow: "hidden",
327
- display: "flex",
328
- flexDirection: "column",
329
- flexShrink: chatOpen ? undefined : 0,
330
- minHeight: 0,
331
- }}>
498
+ {/* Persistent Chat zone - same component, always mounted; hidden when
499
+ collapsed. The blue zone gradient lives HERE (on the wrapper) so the
500
+ collapse/expand toggle bar, the messages, and the composer all read as
501
+ one continuous blue zone - the toggle is part of the chat, not the gold
502
+ panel. (ChatPanel itself is transparent and frosts over this.) */}
503
+ <div
504
+ style={{
505
+ height: chatOpen ? `${100 - splitPercent}%` : "auto",
506
+ overflow: "hidden",
507
+ display: "flex",
508
+ flexDirection: "column",
509
+ flexShrink: chatOpen ? undefined : 0,
510
+ minHeight: 0,
511
+ background: CHAT_ZONE_BG,
512
+ }}
513
+ >
332
514
  <button
333
- onClick={() => setChatOpen(!chatOpen)}
334
- style={{ width: "100%", padding: "4px 12px", display: "flex", alignItems: "center", justifyContent: "space-between", background: "transparent", border: "none", borderBottom: "1px solid rgba(0,0,0,0.06)", cursor: "pointer" }}
515
+ onClick={() => onChatOpenChange(!chatOpen)}
516
+ style={{
517
+ width: "100%",
518
+ padding: "4px 12px",
519
+ display: "flex",
520
+ alignItems: "center",
521
+ justifyContent: "space-between",
522
+ background: "transparent",
523
+ border: "none",
524
+ // The toggle is the top edge of the blue glass chat zone: a soft
525
+ // white rim reads as glass (not a hard black seam), and the inner
526
+ // divider when open stays whisper-light so toggle->messages flows.
527
+ borderTop: "1px solid rgba(255,255,255,0.55)",
528
+ borderBottom: chatOpen ? "1px solid rgba(255,255,255,0.45)" : "none",
529
+ cursor: "pointer",
530
+ flexShrink: 0,
531
+ }}
335
532
  >
336
- <span style={{ fontSize: 10, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", color: "#9ca3af" }}>Chat</span>
337
- <svg width="12" height="12" viewBox="0 0 20 20" fill="#9ca3af" style={{ transform: chatOpen ? "rotate(0deg)" : "rotate(-90deg)", transition: "transform 200ms" }}>
338
- <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" />
533
+ <span
534
+ style={{
535
+ fontSize: 10,
536
+ fontWeight: 700,
537
+ textTransform: "uppercase",
538
+ letterSpacing: "0.05em",
539
+ color: "rgba(0,0,0,0.55)",
540
+ }}
541
+ >
542
+ Chat
543
+ </span>
544
+ <svg
545
+ width="12"
546
+ height="12"
547
+ viewBox="0 0 20 20"
548
+ fill="rgba(0,0,0,0.55)"
549
+ style={{ transform: chatOpen ? "rotate(0deg)" : "rotate(-90deg)", transition: "transform 200ms" }}
550
+ >
551
+ <path
552
+ fillRule="evenodd"
553
+ 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"
554
+ clipRule="evenodd"
555
+ />
339
556
  </svg>
340
557
  </button>
341
- {/* Always mounted to preserve chat state; hidden when collapsed. key=publication forces reload on brand change */}
342
- <div style={{ flex: chatOpen ? 1 : 0, overflow: "hidden", display: chatOpen ? "flex" : "none", flexDirection: "column", minHeight: 0 }}>
343
- <ChatPanel text={text} publication={publication} keywordPanelData={keywordPanelData} />
558
+ <div
559
+ style={{
560
+ flex: chatOpen ? 1 : 0,
561
+ overflow: "hidden",
562
+ display: chatOpen ? "flex" : "none",
563
+ flexDirection: "column",
564
+ minHeight: 0,
565
+ }}
566
+ >
567
+ <ChatPanel
568
+ messages={chatState.messages}
569
+ isStreaming={chatState.isStreaming}
570
+ sendMessage={chatState.sendMessage}
571
+ clearChat={chatState.clearChat}
572
+ documentId={documentId}
573
+ />
344
574
  </div>
345
575
  </div>
346
576
  </div>
577
+
347
578
  </div>
348
579
  );
349
580
  }
350
581
 
351
582
  // Inner component that hosts lifted state and renders PanelContent.
352
- // By keeping this wrapper stable in the React tree, PanelContent never remounts on float toggle.
353
583
  function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClose?: () => void }) {
354
- const [isFloating, setIsFloating] = useState(false);
355
- const [isFullscreen, setIsFullscreen] = useState(false);
356
- const [floatPos, setFloatPos] = useState({ x: typeof window !== "undefined" ? window.innerWidth - 420 : 400, y: 80 });
357
- const [floatSize, setFloatSize] = useState({ width: 380, height: typeof window !== "undefined" ? Math.round(window.innerHeight * 0.8) : 600 });
584
+ // Float / dock state - persisted globally so the user's preferred mode survives reloads.
585
+ const [isFloating, setIsFloating] = usePersistentState<boolean>("seo-copilot-ui-floating", false);
586
+ const [isFullscreen, setIsFullscreen] = usePersistentState<boolean>("seo-copilot-ui-fullscreen", false);
587
+ const [floatPos, setFloatPos] = usePersistentState<{ x: number; y: number }>(
588
+ "seo-copilot-ui-float-pos",
589
+ { x: typeof window !== "undefined" ? window.innerWidth - 420 : 400, y: 80 }
590
+ );
591
+ const [floatSize, setFloatSize] = usePersistentState<{ width: number; height: number }>(
592
+ "seo-copilot-ui-float-size",
593
+ { width: 380, height: typeof window !== "undefined" ? Math.round(window.innerHeight * 0.8) : 600 }
594
+ );
358
595
  const dragOffset = useRef<{ dx: number; dy: number } | null>(null);
359
596
  const resizeStart = useRef<{ startX: number; startY: number; startW: number; startH: number } | null>(null);
360
597
 
361
598
  const { text, isLoading: docLoading, documentFields, documentId } = useDocumentContent();
362
599
  const { apiUrl } = useConfig();
363
600
 
364
- // Lifted state - survives float/dock toggles. Seeds cached per-document in sessionStorage.
365
601
  const seedCacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
366
- const [seedKeywords, setSeedKeywordsRaw] = useState<string[]>(() => {
367
- try { const c = sessionStorage.getItem(seedCacheKey); if (c) return JSON.parse(c).seeds || []; } catch {} return [];
368
- });
369
- const setSeedKeywords = useCallback((seeds: string[]) => {
370
- setSeedKeywordsRaw(seeds);
371
- try { const c = JSON.parse(sessionStorage.getItem(seedCacheKey) || "{}"); sessionStorage.setItem(seedCacheKey, JSON.stringify({ ...c, seeds })); } catch {}
602
+ const loadSeedsFromCache = useCallback((): string[] => {
603
+ try {
604
+ const c = localStorage.getItem(seedCacheKey);
605
+ if (c) return JSON.parse(c).seeds || [];
606
+ } catch {}
607
+ return [];
372
608
  }, [seedCacheKey]);
373
- const [selectedPrimary, setSelectedPrimary] = useState<string | undefined>();
609
+ const [seedKeywords, setSeedKeywordsRaw] = useState<string[]>(loadSeedsFromCache);
610
+ const setSeedKeywords = useCallback(
611
+ (seeds: string[]) => {
612
+ setSeedKeywordsRaw(seeds);
613
+ try {
614
+ const c = JSON.parse(localStorage.getItem(seedCacheKey) || "{}");
615
+ localStorage.setItem(seedCacheKey, JSON.stringify({ ...c, seeds }));
616
+ } catch {}
617
+ },
618
+ [seedCacheKey]
619
+ );
620
+
621
+ // Per-doc state - persisted under doc-scoped keys so a return to the doc restores everything
622
+ const selectedPrimaryKey = documentId ? `seo-copilot-primary-${documentId}` : "seo-copilot-primary-default";
623
+ const [selectedPrimary, setSelectedPrimary] = usePersistentState<string | undefined>(selectedPrimaryKey, undefined);
624
+
625
+ // Reload seed cache when documentId changes (Sanity may reuse the inspector instance)
626
+ const seedsInitializedRef = useRef(false);
627
+ useEffect(() => {
628
+ if (!seedsInitializedRef.current) {
629
+ seedsInitializedRef.current = true;
630
+ return;
631
+ }
632
+ setSeedKeywordsRaw(loadSeedsFromCache());
633
+ }, [documentId, loadSeedsFromCache]);
634
+
635
+ // activeTab is intentionally NOT persisted - every fresh panel mount starts on
636
+ // Keywords, the workflow entry point. (Float / dock toggle keeps the same component
637
+ // instance, so the user's tab choice survives that without needing localStorage.)
638
+ const [activeTab, setActiveTab] = useState<TabId>("keywords");
639
+ // Chat is a collapsible bottom drawer - collapsed by default so tab content gets the
640
+ // full panel height. (Key bumped to -v35 so the old default-open value is dropped.)
641
+ const [chatOpen, setChatOpen] = usePersistentState<boolean>("seo-copilot-ui-chat-open-v35", false);
642
+ const [splitPercent, setSplitPercent] = usePersistentState<number>("seo-copilot-ui-split", 70);
643
+
374
644
  const keywordAnalysisState = useKeywordAnalysis(text, apiUrl, config.publication, seedKeywords, documentFields, selectedPrimary, documentId);
375
645
 
376
- const handleDragStart = useCallback((e: React.MouseEvent) => {
377
- dragOffset.current = {
378
- dx: e.clientX - floatPos.x,
379
- dy: e.clientY - floatPos.y,
380
- };
646
+ // Effective primary (matches PanelContent's resolution)
647
+ const effectivePrimary = selectedPrimary || keywordAnalysisState.analysis?.primaryKeyword?.term || "";
381
648
 
382
- const onMouseMove = (ev: MouseEvent) => {
383
- if (!dragOffset.current) return;
384
- setFloatPos({
385
- x: ev.clientX - dragOffset.current.dx,
386
- y: ev.clientY - dragOffset.current.dy,
387
- });
388
- };
389
- const onMouseUp = () => {
390
- dragOffset.current = null;
391
- window.removeEventListener("mousemove", onMouseMove);
392
- window.removeEventListener("mouseup", onMouseUp);
393
- document.body.style.cursor = "";
394
- document.body.style.userSelect = "";
649
+ // Build keyword panel data (consumed by chat). Lifted here so chat hook lives at top level.
650
+ const keywordPanelData = useMemo(() => {
651
+ const analysis = keywordAnalysisState.analysis;
652
+ if (!analysis) return undefined;
653
+ return {
654
+ primaryKeyword: { term: analysis.primaryKeyword.term, volume: analysis.primaryKeyword.volume },
655
+ supportingKeywords: (analysis.supportingKeywords || []).map((kw) => ({ term: kw.term, volume: kw.volume })),
656
+ missingKeywords: analysis.missingKeywords.map((kw) => ({ term: kw.term, volume: kw.volume })),
657
+ aeoData: keywordAnalysisState.deepAnalysis?.aeo
658
+ ? {
659
+ questionHeadings: (keywordAnalysisState.deepAnalysis.aeo.questionHeadings || []).map((h) => ({
660
+ suggestedHeading: h.suggestedHeading,
661
+ rationale: h.rationale,
662
+ })),
663
+ }
664
+ : undefined,
395
665
  };
396
- document.body.style.cursor = "grabbing";
397
- document.body.style.userSelect = "none";
398
- window.addEventListener("mousemove", onMouseMove);
399
- window.addEventListener("mouseup", onMouseUp);
400
- }, [floatPos]);
666
+ }, [keywordAnalysisState.analysis, keywordAnalysisState.deepAnalysis]);
401
667
 
402
- const handleResizeStart = useCallback((e: React.MouseEvent) => {
403
- e.preventDefault();
404
- e.stopPropagation();
405
- resizeStart.current = { startX: e.clientX, startY: e.clientY, startW: floatSize.width, startH: floatSize.height };
406
- document.body.style.cursor = "nwse-resize";
407
- document.body.style.userSelect = "none";
408
- const onMouseMove = (ev: MouseEvent) => {
409
- if (!resizeStart.current) return;
410
- const newW = Math.max(320, resizeStart.current.startW + (ev.clientX - resizeStart.current.startX));
411
- const newH = Math.max(300, resizeStart.current.startH + (ev.clientY - resizeStart.current.startY));
412
- setFloatSize({ width: newW, height: newH });
413
- };
414
- const onMouseUp = () => {
415
- resizeStart.current = null;
416
- document.body.style.cursor = "";
417
- document.body.style.userSelect = "";
418
- window.removeEventListener("mousemove", onMouseMove);
419
- window.removeEventListener("mouseup", onMouseUp);
420
- };
421
- window.addEventListener("mousemove", onMouseMove);
422
- window.addEventListener("mouseup", onMouseUp);
423
- }, [floatSize]);
668
+ // Chat hook lifted here so in-flight streams survive PanelContent remount (undock)
669
+ const chatHookState = useSEOChat(apiUrl, text, config.publication, keywordPanelData, documentId);
670
+
671
+ // AEO content suggestions - lifted to SEOCopilotInner so in-flight requests survive undock,
672
+ // and PERSISTED per-doc so generated suggestions come back after reload.
673
+ // (FAQ output removed 2026-05 after Google sunset FAQ rich results.)
674
+ const contentSuggestionsKey = documentId ? `seo-copilot-content-suggestions-${documentId}` : "seo-copilot-content-suggestions-default";
675
+ const [contentSuggestions, setContentSuggestions] = usePersistentState<ContentSuggestions | null>(contentSuggestionsKey, null);
676
+ const [isCSLoading, setIsCSLoading] = useState(false);
677
+ const [csError, setCsError] = useState<string | null>(null);
678
+ const aeoOpVersionRef = useRef(0);
679
+ // Only reset *transient* state on doc change. Persisted state is reloaded automatically
680
+ // by usePersistentState when its key changes.
681
+ const didInitAeoRef = useRef(false);
682
+ useEffect(() => {
683
+ if (!didInitAeoRef.current) {
684
+ didInitAeoRef.current = true;
685
+ return;
686
+ }
687
+ aeoOpVersionRef.current += 1;
688
+ setIsCSLoading(false);
689
+ setCsError(null);
690
+ }, [documentId]);
691
+
692
+ const loadContentSuggestions = useCallback(async () => {
693
+ const myVersion = aeoOpVersionRef.current;
694
+ setIsCSLoading(true);
695
+ setCsError(null);
696
+ try {
697
+ const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, config.publication);
698
+ if (aeoOpVersionRef.current !== myVersion) return;
699
+ if (
700
+ data.keyTakeaways.length === 0 &&
701
+ data.infographicOpportunities.length === 0 &&
702
+ data.bulletListItems.length === 0
703
+ ) {
704
+ setCsError("No suggestions returned. Try again with more content.");
705
+ } else {
706
+ setContentSuggestions(data);
707
+ }
708
+ } catch {
709
+ if (aeoOpVersionRef.current !== myVersion) return;
710
+ setCsError("Could not generate content suggestions. Try again.");
711
+ }
712
+ if (aeoOpVersionRef.current !== myVersion) return;
713
+ setIsCSLoading(false);
714
+ }, [apiUrl, text, effectivePrimary, config.publication]);
715
+
716
+ // Smart Linking - lifted state, persisted per-doc so suggestions survive remount.
717
+ // Auto-runs when keywords stabilize; user can also refresh manually.
718
+ const linkingKey = documentId ? `seo-copilot-linking-${documentId}` : "seo-copilot-linking-default";
719
+ const [linkingSuggestions, setLinkingSuggestions] = usePersistentState<LinkingSuggestion[]>(linkingKey, []);
720
+ const [isLinkingLoading, setIsLinkingLoading] = useState(false);
721
+ const [linkingError, setLinkingError] = useState<string | null>(null);
722
+ // The article text at the moment we last fetched - used to flag stale suggestions.
723
+ const [linkingFetchedText, setLinkingFetchedText] = useState("");
724
+ const linkingVersionRef = useRef(0);
725
+ const didInitLinkingRef = useRef(false);
726
+ // Tracks the keyword signature we last fetched for, so the auto-fetch effect can skip
727
+ // re-fetching when persisted suggestions already cover the current doc. Declared here
728
+ // (not next to the effect) so the doc-change reset below can clear it.
729
+ const lastLinkingFetchKey = useRef<string>("");
730
+ useEffect(() => {
731
+ if (!didInitLinkingRef.current) {
732
+ didInitLinkingRef.current = true;
733
+ return;
734
+ }
735
+ linkingVersionRef.current += 1;
736
+ setIsLinkingLoading(false);
737
+ setLinkingError(null);
738
+ // Clear the fetch key so the auto-fetch effect re-evaluates for the new document
739
+ // and correctly skips when that doc already has persisted suggestions.
740
+ lastLinkingFetchKey.current = "";
741
+ }, [documentId]);
742
+
743
+ const supportingKeywordsForLinking = useMemo(() => {
744
+ return (keywordAnalysisState.analysis?.supportingKeywords || [])
745
+ .map((kw) => kw.term)
746
+ .filter(Boolean)
747
+ .slice(0, 5);
748
+ }, [keywordAnalysisState.analysis]);
749
+
750
+ const refreshLinkingSuggestions = useCallback(async () => {
751
+ if (!text || text.trim().length < 50) return;
752
+ if (!effectivePrimary) return;
753
+ const myVersion = linkingVersionRef.current;
754
+ setIsLinkingLoading(true);
755
+ setLinkingError(null);
756
+ try {
757
+ const suggestions = await fetchLinkingSuggestions(
758
+ apiUrl,
759
+ text,
760
+ effectivePrimary,
761
+ supportingKeywordsForLinking,
762
+ documentId,
763
+ config.publication
764
+ );
765
+ if (linkingVersionRef.current !== myVersion) return;
766
+ setLinkingSuggestions(suggestions);
767
+ setLinkingFetchedText(text);
768
+ } catch {
769
+ if (linkingVersionRef.current !== myVersion) return;
770
+ setLinkingError("Could not fetch linking suggestions. Try again.");
771
+ }
772
+ if (linkingVersionRef.current !== myVersion) return;
773
+ setIsLinkingLoading(false);
774
+ }, [apiUrl, text, effectivePrimary, supportingKeywordsForLinking, documentId, config.publication]);
775
+
776
+ // Stale = the article changed materially since we last fetched suggestions.
777
+ const isLinkingStale = useMemo(() => {
778
+ if (!linkingFetchedText || linkingSuggestions.length === 0) return false;
779
+ if (Math.abs(text.length - linkingFetchedText.length) > 150) return true;
780
+ return text.slice(0, 300) !== linkingFetchedText.slice(0, 300);
781
+ }, [text, linkingFetchedText, linkingSuggestions.length]);
782
+
783
+ // Auto-fetch when primary keyword first resolves (and content is present)
784
+ useEffect(() => {
785
+ if (!text || text.trim().length < 50 || !effectivePrimary) return;
786
+ const fetchKey = `${documentId || "_"}|${effectivePrimary}|${supportingKeywordsForLinking.join(",")}`;
787
+ if (fetchKey === lastLinkingFetchKey.current) return;
788
+ if (linkingSuggestions.length > 0 && lastLinkingFetchKey.current === "") {
789
+ // We have persisted suggestions for this doc - skip auto-fetch on remount.
790
+ lastLinkingFetchKey.current = fetchKey;
791
+ return;
792
+ }
793
+ lastLinkingFetchKey.current = fetchKey;
794
+ refreshLinkingSuggestions();
795
+ // eslint-disable-next-line react-hooks/exhaustive-deps
796
+ }, [effectivePrimary, supportingKeywordsForLinking.join("|"), documentId]);
797
+
798
+ // ---- Link-check state (Technical tab) ----------------------------------
799
+ // Lifted here so the editor's check results survive tab switches and undock.
800
+ // Persisted per-document so opening the same article tomorrow shows the last run.
801
+ const linkCheckKey = documentId ? `seo-copilot-link-check-${documentId}` : "seo-copilot-link-check-default";
802
+ const [linkCheckResults, setLinkCheckResults] = usePersistentState<LinkCheckResult[]>(linkCheckKey, []);
803
+ const [hasRunLinkCheck, setHasRunLinkCheck] = usePersistentState<boolean>(`${linkCheckKey}-ran`, false);
804
+ const [isLinkCheckLoading, setIsLinkCheckLoading] = useState(false);
805
+ const [linkCheckError, setLinkCheckError] = useState<string | null>(null);
806
+ const linkCheckVersionRef = useRef(0);
807
+ const didInitLinkCheckRef = useRef(false);
808
+ useEffect(() => {
809
+ if (!didInitLinkCheckRef.current) {
810
+ didInitLinkCheckRef.current = true;
811
+ return;
812
+ }
813
+ linkCheckVersionRef.current += 1;
814
+ setIsLinkCheckLoading(false);
815
+ setLinkCheckError(null);
816
+ }, [documentId]);
817
+
818
+ const runLinkCheck = useCallback(async () => {
819
+ const urls = documentFields?.bodyLinks || [];
820
+ if (urls.length === 0) {
821
+ setHasRunLinkCheck(true);
822
+ setLinkCheckResults([]);
823
+ return;
824
+ }
825
+ const myVersion = linkCheckVersionRef.current;
826
+ setIsLinkCheckLoading(true);
827
+ setLinkCheckError(null);
828
+ try {
829
+ const results = await checkLinks(apiUrl, urls);
830
+ if (linkCheckVersionRef.current !== myVersion) return;
831
+ if (results.length === 0) {
832
+ setLinkCheckError("Could not reach the link checker. Try again.");
833
+ } else {
834
+ setLinkCheckResults(results);
835
+ setHasRunLinkCheck(true);
836
+ }
837
+ } catch {
838
+ if (linkCheckVersionRef.current !== myVersion) return;
839
+ setLinkCheckError("Link check failed. Try again.");
840
+ }
841
+ if (linkCheckVersionRef.current !== myVersion) return;
842
+ setIsLinkCheckLoading(false);
843
+ }, [apiUrl, documentFields?.bodyLinks, setHasRunLinkCheck, setLinkCheckResults]);
844
+
845
+ const handleDragStart = useCallback(
846
+ (e: React.MouseEvent) => {
847
+ dragOffset.current = {
848
+ dx: e.clientX - floatPos.x,
849
+ dy: e.clientY - floatPos.y,
850
+ };
851
+
852
+ const onMouseMove = (ev: MouseEvent) => {
853
+ if (!dragOffset.current) return;
854
+ setFloatPos({
855
+ x: ev.clientX - dragOffset.current.dx,
856
+ y: ev.clientY - dragOffset.current.dy,
857
+ });
858
+ };
859
+ const onMouseUp = () => {
860
+ dragOffset.current = null;
861
+ window.removeEventListener("mousemove", onMouseMove);
862
+ window.removeEventListener("mouseup", onMouseUp);
863
+ document.body.style.cursor = "";
864
+ document.body.style.userSelect = "";
865
+ };
866
+ document.body.style.cursor = "grabbing";
867
+ document.body.style.userSelect = "none";
868
+ window.addEventListener("mousemove", onMouseMove);
869
+ window.addEventListener("mouseup", onMouseUp);
870
+ },
871
+ [floatPos]
872
+ );
873
+
874
+ const handleResizeStart = useCallback(
875
+ (e: React.MouseEvent) => {
876
+ e.preventDefault();
877
+ e.stopPropagation();
878
+ resizeStart.current = { startX: e.clientX, startY: e.clientY, startW: floatSize.width, startH: floatSize.height };
879
+ document.body.style.cursor = "nwse-resize";
880
+ document.body.style.userSelect = "none";
881
+ const onMouseMove = (ev: MouseEvent) => {
882
+ if (!resizeStart.current) return;
883
+ const newW = Math.max(320, resizeStart.current.startW + (ev.clientX - resizeStart.current.startX));
884
+ const newH = Math.max(300, resizeStart.current.startH + (ev.clientY - resizeStart.current.startY));
885
+ setFloatSize({ width: newW, height: newH });
886
+ };
887
+ const onMouseUp = () => {
888
+ resizeStart.current = null;
889
+ document.body.style.cursor = "";
890
+ document.body.style.userSelect = "";
891
+ window.removeEventListener("mousemove", onMouseMove);
892
+ window.removeEventListener("mouseup", onMouseUp);
893
+ };
894
+ window.addEventListener("mousemove", onMouseMove);
895
+ window.addEventListener("mouseup", onMouseUp);
896
+ },
897
+ [floatSize]
898
+ );
424
899
 
425
- // Unused var appeasement
426
- void docLoading;
427
900
 
428
901
  const panelContent = (
429
902
  <PanelContent
430
903
  initialPublication={config.publication}
431
904
  isFloating={isFloating}
432
905
  isFullscreen={isFullscreen}
433
- onToggleFloat={() => { setIsFloating((v) => !v); setIsFullscreen(false); }}
906
+ onToggleFloat={() => {
907
+ setIsFloating((v) => !v);
908
+ setIsFullscreen(false);
909
+ }}
434
910
  onToggleFullscreen={() => setIsFullscreen((v) => !v)}
435
911
  onClose={onClose}
436
912
  floatPos={floatPos}
@@ -438,8 +914,17 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
438
914
  seedKeywords={seedKeywords}
439
915
  onSeedsChange={setSeedKeywords}
440
916
  text={text}
917
+ docLoading={docLoading}
441
918
  documentFields={documentFields}
919
+ documentId={documentId}
920
+ selectedPrimary={selectedPrimary}
442
921
  onSelectPrimary={setSelectedPrimary}
922
+ activeTab={activeTab}
923
+ onActiveTabChange={setActiveTab}
924
+ chatOpen={chatOpen}
925
+ onChatOpenChange={setChatOpen}
926
+ splitPercent={splitPercent}
927
+ onSplitPercentChange={setSplitPercent}
443
928
  externalAnalysis={{
444
929
  analysis: keywordAnalysisState.analysis,
445
930
  isLoading: keywordAnalysisState.isLoading,
@@ -451,12 +936,60 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
451
936
  refreshVolumes: keywordAnalysisState.refreshVolumes,
452
937
  aeoContentChanged: keywordAnalysisState.aeoContentChanged,
453
938
  }}
939
+ chatState={chatHookState}
940
+ aeoOps={{
941
+ contentSuggestions,
942
+ isCSLoading,
943
+ csError,
944
+ loadContentSuggestions,
945
+ }}
946
+ linkingOps={{
947
+ suggestions: linkingSuggestions,
948
+ isLoading: isLinkingLoading,
949
+ error: linkingError,
950
+ isStale: isLinkingStale,
951
+ refresh: refreshLinkingSuggestions,
952
+ }}
953
+ technicalOps={{
954
+ linkCheckResults,
955
+ isLinkCheckLoading,
956
+ linkCheckError,
957
+ hasRunLinkCheck,
958
+ onCheckLinks: runLinkCheck,
959
+ }}
960
+ summaryOps={{
961
+ isAnyLoading:
962
+ keywordAnalysisState.isLoading ||
963
+ keywordAnalysisState.isVolumesLoading ||
964
+ keywordAnalysisState.isDeepLoading ||
965
+ isCSLoading ||
966
+ isLinkingLoading ||
967
+ isLinkCheckLoading,
968
+ onGenerateAll: () => {
969
+ keywordAnalysisState.runDeepAnalysis();
970
+ if (text && text.trim().length >= 100) loadContentSuggestions();
971
+ if (text && text.trim().length >= 50 && effectivePrimary) refreshLinkingSuggestions();
972
+ // Also run the broken-link check so Summary picks up any 404s.
973
+ if ((documentFields?.bodyLinks || []).length > 0) runLinkCheck();
974
+ },
975
+ onItemClick: (item) => {
976
+ setActiveTab(item.jumpTo.tab);
977
+ const id = item.jumpTo.anchorId;
978
+ if (!id) return;
979
+ // The destination tab goes display:none -> block on tab switch; give React a
980
+ // beat to commit before scrolling, then flash the card so the editor sees it.
981
+ setTimeout(() => {
982
+ const el = typeof document !== "undefined" ? document.getElementById(id) : null;
983
+ if (!el) return;
984
+ el.scrollIntoView({ behavior: "smooth", block: "start" });
985
+ el.classList.add("seo-copilot-flash");
986
+ setTimeout(() => el.classList.remove("seo-copilot-flash"), 1400);
987
+ }, 80);
988
+ },
989
+ }}
454
990
  />
455
991
  );
456
992
 
457
- // When floating, render via portal to document.body to escape Sanity's
458
- // stacking contexts (transforms/will-change trap position:fixed elements).
459
- // When docked, render inline in the inspector.
460
993
  const floatingPanel = (
461
994
  <div
462
995
  style={{
@@ -470,7 +1003,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
470
1003
  overflow: "hidden",
471
1004
  boxShadow: isFullscreen ? "none" : "0 8px 32px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.10)",
472
1005
  border: isFullscreen ? "none" : "1px solid rgba(0,0,0,0.08)",
473
- background: "#FBFAF7",
1006
+ background: PANEL_BG,
474
1007
  }}
475
1008
  >
476
1009
  {panelContent}
@@ -478,8 +1011,15 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
478
1011
  <div
479
1012
  onMouseDown={handleResizeStart}
480
1013
  style={{
481
- position: "absolute", bottom: 0, right: 0, width: 16, height: 16,
482
- cursor: "nwse-resize", display: "flex", alignItems: "center", justifyContent: "center",
1014
+ position: "absolute",
1015
+ bottom: 0,
1016
+ right: 0,
1017
+ width: 16,
1018
+ height: 16,
1019
+ cursor: "nwse-resize",
1020
+ display: "flex",
1021
+ alignItems: "center",
1022
+ justifyContent: "center",
483
1023
  }}
484
1024
  >
485
1025
  <svg width="10" height="10" viewBox="0 0 10 10" fill="#9ca3af">
@@ -494,9 +1034,16 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
494
1034
  if (isFloating) {
495
1035
  return (
496
1036
  <>
497
- {/* Empty placeholder in inspector so Sanity doesn't collapse it */}
498
- <div style={{ height: "100%", background: "#FBFAF7", display: "flex", alignItems: "center", justifyContent: "center" }}>
499
- <span style={{ fontSize: 12, color: "#9ca3af" }}>SEO Copilot is floating</span>
1037
+ <div
1038
+ style={{
1039
+ height: "100%",
1040
+ background: PANEL_BG,
1041
+ display: "flex",
1042
+ alignItems: "center",
1043
+ justifyContent: "center",
1044
+ }}
1045
+ >
1046
+ <span style={{ fontSize: 12, color: "rgba(0,0,0,0.5)" }}>SEO Copilot is floating</span>
500
1047
  </div>
501
1048
  {typeof document !== "undefined" && createPortal(floatingPanel, document.body)}
502
1049
  </>
@@ -504,7 +1051,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
504
1051
  }
505
1052
 
506
1053
  return (
507
- <div style={{ height: "100%", background: "#FBFAF7", position: "relative" as const, zIndex: 1 }}>
1054
+ <div style={{ height: "100%", background: PANEL_BG, position: "relative" as const, zIndex: 1 }}>
508
1055
  {panelContent}
509
1056
  </div>
510
1057
  );
@@ -516,7 +1063,7 @@ export default function SEOCopilotPanel({ config, onClose }: SEOCopilotPanelProp
516
1063
  fallback={
517
1064
  <div style={{ padding: 16, display: "flex", alignItems: "center", gap: 12 }}>
518
1065
  <LoadingBars />
519
- <span style={{ fontSize: 12, color: "#9ca3af" }}>Loading SEO Copilot...</span>
1066
+ <span style={{ fontSize: 12, color: "#4b5563" }}>Loading SEO Copilot...</span>
520
1067
  </div>
521
1068
  }
522
1069
  >