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,125 @@
1
+ import { useState, useRef } from "react";
2
+ import { MJH_GOLD } from "./styles";
3
+
4
+ interface SeedKeywordInputProps {
5
+ seeds: string[];
6
+ onSeedsChange: (seeds: string[]) => void;
7
+ }
8
+
9
+ function parseSeedInput(input: string): string[] {
10
+ return input
11
+ .split(/[,\n]+/)
12
+ .map((s) => s.trim())
13
+ .filter((s) => s.length > 0);
14
+ }
15
+
16
+ export function SeedKeywordInput({ seeds, onSeedsChange }: SeedKeywordInputProps) {
17
+ const [inputValue, setInputValue] = useState("");
18
+ const inputRef = useRef<HTMLTextAreaElement>(null);
19
+
20
+ const handleAdd = () => {
21
+ const parsed = parseSeedInput(inputValue);
22
+ if (parsed.length > 0) {
23
+ const combined = [...new Set([...seeds, ...parsed])];
24
+ onSeedsChange(combined);
25
+ setInputValue("");
26
+ }
27
+ };
28
+
29
+ const handleRemove = (term: string) => {
30
+ onSeedsChange(seeds.filter((s) => s !== term));
31
+ };
32
+
33
+ const handleKeyDown = (e: React.KeyboardEvent) => {
34
+ if (e.key === "Enter" && !e.shiftKey) {
35
+ e.preventDefault();
36
+ handleAdd();
37
+ }
38
+ };
39
+
40
+ return (
41
+ <div style={{
42
+ borderRadius: 14,
43
+ background: "#ffffff",
44
+ boxShadow: "0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.03)",
45
+ padding: "12px 14px",
46
+ }}>
47
+ <span style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8", fontWeight: 600 }}>
48
+ Seed Keywords
49
+ </span>
50
+
51
+ {/* Seed tags */}
52
+ {seeds.length > 0 && (
53
+ <div style={{ display: "flex", flexWrap: "wrap", gap: 5, marginTop: 8 }}>
54
+ {seeds.map((seed) => (
55
+ <span key={seed} style={{
56
+ display: "inline-flex",
57
+ alignItems: "center",
58
+ gap: 5,
59
+ padding: "3px 10px",
60
+ borderRadius: 99,
61
+ fontSize: 11.5,
62
+ fontWeight: 500,
63
+ background: `rgba(230,192,27,0.12)`,
64
+ color: "#92810F",
65
+ transition: "all 150ms",
66
+ }}>
67
+ {seed}
68
+ <button
69
+ onClick={() => handleRemove(seed)}
70
+ style={{ background: "none", border: "none", cursor: "pointer", padding: 0, fontSize: 12, color: "#8B7310", lineHeight: 1 }}
71
+ >
72
+ x
73
+ </button>
74
+ </span>
75
+ ))}
76
+ </div>
77
+ )}
78
+
79
+ {/* Input area - always visible */}
80
+ <div style={{ marginTop: 8 }}>
81
+ <textarea
82
+ ref={inputRef}
83
+ value={inputValue}
84
+ onChange={(e) => setInputValue(e.target.value)}
85
+ onKeyDown={handleKeyDown}
86
+ placeholder="Enter 2-3 word phrases for best results"
87
+ rows={2}
88
+ style={{
89
+ width: "100%",
90
+ padding: "8px 10px",
91
+ fontSize: 12.5,
92
+ borderRadius: 10,
93
+ border: "1px solid #e2e8f0",
94
+ background: "#fafbfc",
95
+ resize: "vertical",
96
+ outline: "none",
97
+ fontFamily: "inherit",
98
+ boxSizing: "border-box",
99
+ }}
100
+ />
101
+ <button
102
+ onClick={handleAdd}
103
+ disabled={!inputValue.trim()}
104
+ style={{
105
+ marginTop: 4,
106
+ padding: "4px 12px",
107
+ fontSize: 11,
108
+ fontWeight: 600,
109
+ borderRadius: 6,
110
+ border: "none",
111
+ background: inputValue.trim() ? MJH_GOLD : "#e5e7eb",
112
+ color: inputValue.trim() ? "#ffffff" : "#9ca3af",
113
+ cursor: inputValue.trim() ? "pointer" : "not-allowed",
114
+ transition: "all 150ms",
115
+ }}
116
+ >
117
+ Add
118
+ </button>
119
+ <div style={{ marginTop: 4, fontSize: 10, color: "#9ca3af" }}>
120
+ Tip: Long-tail keywords (2-3+ words) give better results than single broad terms
121
+ </div>
122
+ </div>
123
+ </div>
124
+ );
125
+ }
@@ -0,0 +1,77 @@
1
+ // Injected CSS for animations and markdown - must be added via <style> tag
2
+ export const INJECTED_CSS = `
3
+ @keyframes bar-shift-1 {
4
+ 0%, 100% { height: 8px; }
5
+ 25% { height: 14px; }
6
+ 50% { height: 6px; }
7
+ 75% { height: 12px; }
8
+ }
9
+ @keyframes bar-shift-2 {
10
+ 0%, 100% { height: 12px; }
11
+ 25% { height: 6px; }
12
+ 50% { height: 14px; }
13
+ 75% { height: 8px; }
14
+ }
15
+ @keyframes bar-shift-3 {
16
+ 0%, 100% { height: 6px; }
17
+ 25% { height: 10px; }
18
+ 50% { height: 12px; }
19
+ 75% { height: 5px; }
20
+ }
21
+ @keyframes fade-up {
22
+ from { opacity: 0; transform: translateY(6px); }
23
+ to { opacity: 1; transform: translateY(0); }
24
+ }
25
+ @keyframes spin {
26
+ from { transform: rotate(0deg); }
27
+ to { transform: rotate(360deg); }
28
+ }
29
+ @keyframes content-pulse {
30
+ 0%, 100% { opacity: 0.5; }
31
+ 50% { opacity: 1; }
32
+ }
33
+ .prose-chat { font-size: 12.5px; line-height: 1.65; color: #475569; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; }
34
+ .prose-chat h1 { font-size: 14px; font-weight: 700; color: #1e293b; margin: 10px 0 5px 0; line-height: 1.35; }
35
+ .prose-chat h2, .prose-chat h3 { font-size: 13px; font-weight: 700; color: #1e293b; margin: 10px 0 5px 0; line-height: 1.35; }
36
+ .prose-chat p { margin: 5px 0; }
37
+ .prose-chat ul, .prose-chat ol { margin: 5px 0; padding-left: 18px; }
38
+ .prose-chat li { margin: 3px 0; }
39
+ .prose-chat strong { font-weight: 600; color: #1e293b; }
40
+ .prose-chat hr { border: none; border-top: 1px solid #f1f5f9; margin: 10px 0; }
41
+ .prose-chat code { background: #f8fafc; padding: 2px 5px; border-radius: 4px; font-size: 11px; border: 1px solid #f1f5f9; }
42
+ .prose-chat a { color: #005DAC; text-decoration: none; border-bottom: 1px solid rgba(0,93,172,0.3); }
43
+ .prose-chat a:hover { border-bottom-color: #005DAC; }
44
+ .prose-chat table { width: 100%; border-collapse: separate; border-spacing: 0; margin: 8px 0; font-size: 11px; border-radius: 8px; overflow: hidden; border: 1px solid #f1f5f9; }
45
+ .prose-chat th { text-align: left; padding: 6px 10px; font-weight: 600; color: #475569; border-bottom: 1px solid #f1f5f9; background: #fafbfc; }
46
+ .prose-chat td { padding: 6px 10px; border-bottom: 1px solid #f8fafc; color: #64748b; }
47
+ .prose-chat tr:last-child td { border-bottom: none; }
48
+
49
+ /* Thin scrollbars */
50
+ .seo-copilot-panel { scrollbar-width: thin; scrollbar-color: #e5e7eb transparent; }
51
+ .seo-copilot-panel ::-webkit-scrollbar { width: 4px; }
52
+ .seo-copilot-panel ::-webkit-scrollbar-track { background: transparent; }
53
+ .seo-copilot-panel ::-webkit-scrollbar-thumb { background: #e5e7eb; border-radius: 4px; }
54
+ .seo-copilot-panel * { scrollbar-width: thin; scrollbar-color: #e5e7eb transparent; }
55
+
56
+ /* Dark mode overrides - Sanity adds data-scheme="dark" or [data-ui-color-scheme="dark"] */
57
+ @media (prefers-color-scheme: dark) {
58
+ .seo-copilot-panel { color-scheme: light; }
59
+ }
60
+ /* Force light text colors when Sanity is in dark mode - the panel bg stays white but text was washing out */
61
+ [data-scheme="dark"] .seo-copilot-panel,
62
+ [data-ui-color-scheme="dark"] .seo-copilot-panel {
63
+ color: #374151;
64
+ }
65
+ [data-scheme="dark"] .seo-copilot-panel *,
66
+ [data-ui-color-scheme="dark"] .seo-copilot-panel * {
67
+ color-scheme: light;
68
+ }
69
+ `;
70
+
71
+ // Brand colors
72
+ export const MJH_GOLD = "#E6C01B";
73
+ export const MJH_GOLD_DARK = "#C9A716";
74
+ export const MJH_BLUE = "#005DAC";
75
+ export const MJH_SLATE = "#4D596A";
76
+ export const USER_BLUE = "#DFF4FD";
77
+ export const USER_BLUE_BORDER = "#B8E3F9";
@@ -0,0 +1,99 @@
1
+ import { useState, useEffect, useRef } from "react";
2
+ import { useDocumentPane } from "sanity/structure";
3
+ import type { DocumentFields } from "../lib/types";
4
+
5
+ interface PortableTextSpan {
6
+ _type: string;
7
+ text?: string;
8
+ children?: PortableTextSpan[];
9
+ }
10
+
11
+ interface PortableTextBlock {
12
+ _type: string;
13
+ style?: string;
14
+ children?: PortableTextSpan[];
15
+ text?: string;
16
+ }
17
+
18
+ function extractText(blocks: unknown): string {
19
+ if (!blocks || !Array.isArray(blocks)) return "";
20
+ const parts: string[] = [];
21
+ for (const block of blocks as PortableTextBlock[]) {
22
+ if (block._type === "block" && block.children) {
23
+ const blockText = block.children.map((child) => child.text || "").join("");
24
+ if (blockText) parts.push(blockText);
25
+ } else if (typeof block === "string") {
26
+ parts.push(block);
27
+ }
28
+ }
29
+ return parts.join("\n");
30
+ }
31
+
32
+ function extractHeadings(blocks: unknown): string[] {
33
+ if (!blocks || !Array.isArray(blocks)) return [];
34
+ const headings: string[] = [];
35
+ for (const block of blocks as PortableTextBlock[]) {
36
+ if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
37
+ const text = block.children.map((child) => child.text || "").join("");
38
+ if (text) headings.push(text);
39
+ }
40
+ }
41
+ return headings;
42
+ }
43
+
44
+ function extractImageNames(value: Record<string, unknown>): string[] {
45
+ const names: string[] = [];
46
+ const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
47
+ for (const field of imageFields) {
48
+ const img = value[field] as Record<string, unknown> | undefined;
49
+ if (img) {
50
+ if (img.alt && typeof img.alt === "string") names.push(img.alt);
51
+ if (img.asset && typeof img.asset === "object") {
52
+ const asset = img.asset as Record<string, unknown>;
53
+ if (asset.originalFilename && typeof asset.originalFilename === "string") {
54
+ names.push(asset.originalFilename);
55
+ }
56
+ }
57
+ }
58
+ }
59
+ return names;
60
+ }
61
+
62
+ export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined } {
63
+ const { value, ready } = useDocumentPane();
64
+ const documentId = (value?._id as string | undefined) || undefined;
65
+ const title = value?.title as string | undefined;
66
+ const body = value?.body;
67
+ const [debouncedText, setDebouncedText] = useState("");
68
+ const [isLoading, setIsLoading] = useState(!ready);
69
+ const [documentFields, setDocumentFields] = useState<DocumentFields>({});
70
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
71
+
72
+ useEffect(() => {
73
+ const bodyText = extractText(body);
74
+ const fullText = [title, bodyText].filter(Boolean).join("\n\n");
75
+
76
+ const val = value as Record<string, unknown> | undefined;
77
+ const fields: DocumentFields = {
78
+ title: title || undefined,
79
+ metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
80
+ slug: (val?.slug as { current?: string })?.current || undefined,
81
+ imageNames: val ? extractImageNames(val) : [],
82
+ headings: extractHeadings(body),
83
+ contentCategory: (val?.contentCategory || val?.category) as string | undefined,
84
+ contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
85
+ };
86
+
87
+ if (timerRef.current) clearTimeout(timerRef.current);
88
+
89
+ timerRef.current = setTimeout(() => {
90
+ setDebouncedText(fullText);
91
+ setDocumentFields(fields);
92
+ setIsLoading(false);
93
+ }, 2000);
94
+
95
+ return () => { if (timerRef.current) clearTimeout(timerRef.current); };
96
+ }, [title, body, value]);
97
+
98
+ return { text: debouncedText, isLoading, documentFields, documentId };
99
+ }
@@ -0,0 +1,225 @@
1
+ import { useState, useEffect, useCallback, useRef } from "react";
2
+ import { fetchAnalysis, lookupKeywords } from "../lib/api";
3
+ import type { SEOAnalysis, DeepAnalysis, DocumentFields } from "../lib/types";
4
+
5
+ function mergeVolumes(
6
+ analysis: SEOAnalysis,
7
+ volumeMap: Map<string, { volume: number; cpc: number; competition: number }>
8
+ ): SEOAnalysis {
9
+ const updated = { ...analysis };
10
+
11
+ // Merge volumes into all primaryKeywordCandidates
12
+ if (updated.primaryKeywordCandidates && updated.primaryKeywordCandidates.length > 0) {
13
+ updated.primaryKeywordCandidates = updated.primaryKeywordCandidates.map((candidate) => {
14
+ const data = volumeMap.get(candidate.term.toLowerCase());
15
+ return data ? { ...candidate, volume: data.volume, cpc: data.cpc, competition: data.competition } : candidate;
16
+ });
17
+ }
18
+
19
+ // Also update legacy primaryKeyword
20
+ const primaryData = volumeMap.get(updated.primaryKeyword.term.toLowerCase());
21
+ if (primaryData) {
22
+ updated.primaryKeyword = {
23
+ ...updated.primaryKeyword,
24
+ volume: primaryData.volume,
25
+ cpc: primaryData.cpc,
26
+ competition: primaryData.competition,
27
+ };
28
+ }
29
+
30
+ updated.supportingKeywords = updated.supportingKeywords.map((kw) => {
31
+ const data = volumeMap.get(kw.term.toLowerCase());
32
+ return data ? { ...kw, volume: data.volume } : kw;
33
+ });
34
+
35
+ updated.missingKeywords = updated.missingKeywords.map((kw) => {
36
+ const data = volumeMap.get(kw.term.toLowerCase());
37
+ return data ? { ...kw, volume: data.volume } : kw;
38
+ });
39
+
40
+ return updated;
41
+ }
42
+
43
+ export function useKeywordAnalysis(
44
+ text: string,
45
+ apiUrl: string,
46
+ publication?: string,
47
+ seedKeywords?: string[],
48
+ documentFields?: DocumentFields,
49
+ focusPrimary?: string,
50
+ documentId?: string
51
+ ) {
52
+ // Restore cached results from sessionStorage on mount (survives inspector close/reopen)
53
+ const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
54
+ const loadCached = (): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
55
+ try {
56
+ if (typeof window !== "undefined" && sessionStorage.getItem("seo-copilot-cache")) {
57
+ sessionStorage.removeItem("seo-copilot-cache");
58
+ }
59
+ const raw = typeof window !== "undefined" ? sessionStorage.getItem(cacheKey) : null;
60
+ if (raw) return JSON.parse(raw);
61
+ } catch { /* ignore */ }
62
+ return { analysis: null, deepAnalysis: null, seeds: [] };
63
+ };
64
+ const cached = useRef(loadCached());
65
+
66
+ const [analysis, setAnalysisRaw] = useState<SEOAnalysis | null>(cached.current.analysis);
67
+ const [isLoading, setIsLoading] = useState(false);
68
+ const [isVolumesLoading, setIsVolumesLoading] = useState(false);
69
+ const [error, setError] = useState<string | null>(null);
70
+
71
+ const [deepAnalysis, setDeepAnalysisRaw] = useState<DeepAnalysis | null>(cached.current.deepAnalysis);
72
+ const [isDeepLoading, setIsDeepLoading] = useState(false);
73
+ const [aeoTextSnapshot, setAeoTextSnapshot] = useState<string>("");
74
+ const [aeoContentChanged, setAeoContentChanged] = useState(false);
75
+
76
+ const setAnalysis = useCallback((val: SEOAnalysis | null) => {
77
+ setAnalysisRaw(val);
78
+ try {
79
+ const prev = loadCached();
80
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: val }));
81
+ } catch { /* ignore */ }
82
+ }, [cacheKey]);
83
+ const setDeepAnalysis = useCallback((val: DeepAnalysis | null) => {
84
+ setDeepAnalysisRaw(val);
85
+ try {
86
+ const prev = loadCached();
87
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
88
+ } catch { /* ignore */ }
89
+ }, [cacheKey]);
90
+
91
+ // focusPrimary is a LIGHT signal - not merged into seeds (too heavy).
92
+ // Seeds heavily weight. focusPrimary just slightly nudges.
93
+ const effectiveSeeds = seedKeywords;
94
+
95
+ // Track if content changed since AEO was generated
96
+ useEffect(() => {
97
+ if (deepAnalysis && aeoTextSnapshot && text !== aeoTextSnapshot) {
98
+ setAeoContentChanged(true);
99
+ }
100
+ }, [text, deepAnalysis, aeoTextSnapshot]);
101
+
102
+ // Track whether initial volume lookup has been done for this analysis
103
+ const volumesLoadedRef = useRef(false);
104
+ const lastAnalysisRef = useRef<SEOAnalysis | null>(null);
105
+ const prevSeedsRef = useRef(effectiveSeeds?.join(",") || "");
106
+ const prevFocusRef = useRef(focusPrimary || "");
107
+
108
+ // Reset volume tracking when seeds or primary keyword change (these are explicit user actions)
109
+ const currentSeedsKey = effectiveSeeds?.join(",") || "";
110
+ const currentFocusKey = focusPrimary || "";
111
+ if (currentSeedsKey !== prevSeedsRef.current || currentFocusKey !== prevFocusRef.current) {
112
+ volumesLoadedRef.current = false;
113
+ prevSeedsRef.current = currentSeedsKey;
114
+ prevFocusRef.current = currentFocusKey;
115
+ }
116
+
117
+ // Real-time analysis: Claude suggests keywords (no volume lookups on content changes)
118
+ useEffect(() => {
119
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
120
+ setAnalysis(null);
121
+ volumesLoadedRef.current = false;
122
+ return;
123
+ }
124
+
125
+ let cancelled = false;
126
+ setIsLoading(true);
127
+ setError(null);
128
+
129
+ fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary)
130
+ .then((result) => {
131
+ if (cancelled) return;
132
+ const analysisResult = result as SEOAnalysis;
133
+ lastAnalysisRef.current = analysisResult;
134
+
135
+ // Show keywords immediately without volumes
136
+ setAnalysis(analysisResult);
137
+ setIsLoading(false);
138
+
139
+ // Only auto-lookup volumes on FIRST analysis (initial load)
140
+ // Subsequent content changes show keywords without re-looking up volumes
141
+ if (!volumesLoadedRef.current) {
142
+ volumesLoadedRef.current = true;
143
+ doVolumeLookup(analysisResult, cancelled);
144
+ }
145
+ })
146
+ .catch((err) => {
147
+ if (!cancelled) {
148
+ setError(err.message);
149
+ setIsLoading(false);
150
+ }
151
+ });
152
+
153
+ return () => {
154
+ cancelled = true;
155
+ };
156
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
157
+
158
+ // Volume lookup helper - reused by auto-lookup and manual refresh
159
+ const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, cancelled?: boolean) => {
160
+ setIsVolumesLoading(true);
161
+
162
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
163
+ const allTerms = [
164
+ ...new Set([
165
+ ...candidateTerms,
166
+ analysisResult.primaryKeyword.term,
167
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
168
+ ...analysisResult.missingKeywords.map((kw) => kw.term),
169
+ ]),
170
+ ];
171
+
172
+ lookupKeywords(apiUrl, allTerms)
173
+ .then(({ results }) => {
174
+ if (cancelled) return;
175
+ const volumeMap = new Map(
176
+ results.map((r) => [r.keyword.toLowerCase(), r])
177
+ );
178
+ setAnalysis(mergeVolumes(analysisResult, volumeMap));
179
+ setIsVolumesLoading(false);
180
+ })
181
+ .catch(() => {
182
+ if (!cancelled) {
183
+ setIsVolumesLoading(false);
184
+ }
185
+ });
186
+ }, [apiUrl]);
187
+
188
+ // Manual refresh volumes - called by UI actions (seed change, primary change, refresh button)
189
+ const refreshVolumes = useCallback(() => {
190
+ const current = lastAnalysisRef.current || analysis;
191
+ if (!current) return;
192
+ doVolumeLookup(current);
193
+ }, [analysis, doVolumeLookup]);
194
+
195
+ const runDeepAnalysis = useCallback(() => {
196
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) return;
197
+
198
+ setIsDeepLoading(true);
199
+ setError(null);
200
+ setAeoContentChanged(false);
201
+ setAeoTextSnapshot(text);
202
+
203
+ fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary)
204
+ .then((result) => {
205
+ setDeepAnalysis(result as DeepAnalysis);
206
+ setIsDeepLoading(false);
207
+ })
208
+ .catch((err) => {
209
+ setError(err.message);
210
+ setIsDeepLoading(false);
211
+ });
212
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
213
+
214
+ return {
215
+ analysis,
216
+ isLoading,
217
+ isVolumesLoading,
218
+ error,
219
+ deepAnalysis,
220
+ isDeepLoading,
221
+ runDeepAnalysis,
222
+ refreshVolumes,
223
+ aeoContentChanged,
224
+ };
225
+ }
@@ -0,0 +1,169 @@
1
+ import { useState, useCallback, useEffect, useRef } from "react";
2
+ import { fetchChatStream, loadChatHistory, saveChatHistory } from "../lib/api";
3
+ import type { ChatMessage } from "../lib/types";
4
+
5
+ interface KeywordPanelData {
6
+ primaryKeyword?: { term: string; volume: number | null };
7
+ supportingKeywords?: { term: string; volume: number | null }[];
8
+ secondaryKeywords?: { term: string; volume: number | null }[];
9
+ missingKeywords?: { term: string; volume: number | null }[];
10
+ contentScore?: number;
11
+ aeoData?: {
12
+ questionHeadings: { suggestedHeading: string; rationale: string }[];
13
+ faqSuggestions: { question: string; answer: string }[];
14
+ };
15
+ }
16
+
17
+ function getUserId(): string {
18
+ const key = "seo-copilot-user-id";
19
+ try {
20
+ let id = localStorage.getItem(key);
21
+ if (!id) {
22
+ id = `user-${Math.random().toString(36).slice(2)}-${Date.now()}`;
23
+ localStorage.setItem(key, id);
24
+ }
25
+ return id;
26
+ } catch {
27
+ return "anonymous";
28
+ }
29
+ }
30
+
31
+ export function useSEOChat(
32
+ apiUrl: string,
33
+ documentText: string,
34
+ publication?: string,
35
+ keywordPanelData?: KeywordPanelData,
36
+ documentId?: string
37
+ ) {
38
+ // Chat messages cached in sessionStorage for persistence across close/reopen
39
+ const chatCacheKey = documentId ? `seo-copilot-chat-${documentId}` : "seo-copilot-chat-default";
40
+ const [messages, setMessagesRaw] = useState<ChatMessage[]>(() => {
41
+ try {
42
+ const cached = typeof window !== "undefined" ? sessionStorage.getItem(chatCacheKey) : null;
43
+ return cached ? JSON.parse(cached) : [];
44
+ } catch { return []; }
45
+ });
46
+ const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
47
+ setMessagesRaw((prev) => {
48
+ const next = typeof msgs === "function" ? msgs(prev) : msgs;
49
+ try { sessionStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
50
+ return next;
51
+ });
52
+ }, [chatCacheKey]);
53
+
54
+ const [isStreaming, setIsStreaming] = useState(false);
55
+ const [historyLoaded, setHistoryLoaded] = useState(false);
56
+ const userId = useRef(getUserId());
57
+ const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
58
+
59
+ // Also try to load from server-side chat history on mount
60
+ useEffect(() => {
61
+ if (!documentId || historyLoaded) return;
62
+ let cancelled = false;
63
+ loadChatHistory(apiUrl, userId.current, documentId).then((loaded) => {
64
+ if (!cancelled && loaded.length > 0 && messages.length === 0) {
65
+ setMessages(loaded);
66
+ }
67
+ if (!cancelled) setHistoryLoaded(true);
68
+ });
69
+ return () => { cancelled = true; };
70
+ }, [apiUrl, documentId, historyLoaded]);
71
+
72
+ // Debounced save to server (best-effort, sessionStorage is the primary)
73
+ const scheduleSave = useCallback((msgs: ChatMessage[]) => {
74
+ if (!documentId) return;
75
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
76
+ saveTimerRef.current = setTimeout(() => {
77
+ saveChatHistory(apiUrl, userId.current, documentId, msgs, publication);
78
+ }, 800);
79
+ }, [apiUrl, documentId, publication]);
80
+
81
+ const sendMessage = useCallback(
82
+ async (text: string) => {
83
+ const userMessage: ChatMessage = { role: "user", content: text };
84
+ const updatedMessages = [...messages, userMessage];
85
+ setMessages(updatedMessages);
86
+ setIsStreaming(true);
87
+
88
+ try {
89
+ const stream = await fetchChatStream(
90
+ apiUrl,
91
+ updatedMessages,
92
+ documentText,
93
+ publication,
94
+ keywordPanelData
95
+ );
96
+
97
+ if (!stream) {
98
+ setIsStreaming(false);
99
+ return;
100
+ }
101
+
102
+ const reader = stream.getReader();
103
+ const decoder = new TextDecoder();
104
+ let assistantContent = "";
105
+
106
+ // Add empty assistant message that we'll update
107
+ setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
108
+
109
+ while (true) {
110
+ const { done, value } = await reader.read();
111
+ if (done) break;
112
+
113
+ const chunk = decoder.decode(value, { stream: true });
114
+ const lines = chunk.split("\n");
115
+
116
+ for (const line of lines) {
117
+ if (line.startsWith("data: ")) {
118
+ const data = line.slice(6);
119
+ if (data === "[DONE]") continue;
120
+
121
+ try {
122
+ const parsed = JSON.parse(data);
123
+ if (parsed.text) {
124
+ assistantContent += parsed.text;
125
+ setMessages((prev) => {
126
+ const updated = [...prev];
127
+ updated[updated.length - 1] = {
128
+ role: "assistant",
129
+ content: assistantContent,
130
+ };
131
+ return updated;
132
+ });
133
+ }
134
+ } catch {
135
+ // Skip malformed JSON chunks
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ // Save history after stream completes
142
+ const finalMessages: ChatMessage[] = [
143
+ ...updatedMessages,
144
+ { role: "assistant", content: assistantContent },
145
+ ];
146
+ scheduleSave(finalMessages);
147
+ } catch (err) {
148
+ const errorMsg = err instanceof Error ? err.message : "Chat failed";
149
+ setMessages((prev) => [
150
+ ...prev,
151
+ { role: "assistant", content: `Error: ${errorMsg}` },
152
+ ]);
153
+ }
154
+
155
+ setIsStreaming(false);
156
+ },
157
+ [messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
158
+ );
159
+
160
+ const clearChat = useCallback(() => {
161
+ setMessages([]);
162
+ // Save empty history to backend
163
+ if (documentId) {
164
+ saveChatHistory(apiUrl, userId.current, documentId, [], publication);
165
+ }
166
+ }, [apiUrl, documentId, publication]);
167
+
168
+ return { messages, isStreaming, sendMessage, clearChat };
169
+ }