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.
package/dist/index.mjs ADDED
@@ -0,0 +1,2671 @@
1
+ // src/index.ts
2
+ import { definePlugin } from "sanity";
3
+
4
+ // src/inspector.ts
5
+ import { createElement } from "react";
6
+
7
+ // src/components/SEOCopilotPanel.tsx
8
+ import { useState as useState9, useRef as useRef8, useCallback as useCallback4, useEffect as useEffect7, useMemo, Suspense } from "react";
9
+ import { createPortal } from "react-dom";
10
+
11
+ // src/hooks/useDocumentContent.ts
12
+ import { useState, useEffect, useRef } from "react";
13
+ import { useDocumentPane } from "sanity/structure";
14
+ function extractText(blocks) {
15
+ if (!blocks || !Array.isArray(blocks)) return "";
16
+ const parts = [];
17
+ for (const block of blocks) {
18
+ if (block._type === "block" && block.children) {
19
+ const blockText = block.children.map((child) => child.text || "").join("");
20
+ if (blockText) parts.push(blockText);
21
+ } else if (typeof block === "string") {
22
+ parts.push(block);
23
+ }
24
+ }
25
+ return parts.join("\n");
26
+ }
27
+ function extractHeadings(blocks) {
28
+ if (!blocks || !Array.isArray(blocks)) return [];
29
+ const headings = [];
30
+ for (const block of blocks) {
31
+ if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
32
+ const text = block.children.map((child) => child.text || "").join("");
33
+ if (text) headings.push(text);
34
+ }
35
+ }
36
+ return headings;
37
+ }
38
+ function extractImageNames(value) {
39
+ const names = [];
40
+ const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
41
+ for (const field of imageFields) {
42
+ const img = value[field];
43
+ if (img) {
44
+ if (img.alt && typeof img.alt === "string") names.push(img.alt);
45
+ if (img.asset && typeof img.asset === "object") {
46
+ const asset = img.asset;
47
+ if (asset.originalFilename && typeof asset.originalFilename === "string") {
48
+ names.push(asset.originalFilename);
49
+ }
50
+ }
51
+ }
52
+ }
53
+ return names;
54
+ }
55
+ function useDocumentContent() {
56
+ const { value, ready } = useDocumentPane();
57
+ const documentId = value?._id || void 0;
58
+ const title = value?.title;
59
+ const body = value?.body;
60
+ const [debouncedText, setDebouncedText] = useState("");
61
+ const [isLoading, setIsLoading] = useState(!ready);
62
+ const [documentFields, setDocumentFields] = useState({});
63
+ const timerRef = useRef(null);
64
+ useEffect(() => {
65
+ const bodyText = extractText(body);
66
+ const fullText = [title, bodyText].filter(Boolean).join("\n\n");
67
+ const val = value;
68
+ const fields = {
69
+ title: title || void 0,
70
+ metaDescription: val?.metaDescription || val?.summary || val?.description || val?.seoDescription,
71
+ slug: val?.slug?.current || void 0,
72
+ imageNames: val ? extractImageNames(val) : [],
73
+ headings: extractHeadings(body),
74
+ contentCategory: val?.contentCategory || val?.category,
75
+ contentPlacement: Array.isArray(val?.contentPlacement) ? val.contentPlacement : void 0
76
+ };
77
+ if (timerRef.current) clearTimeout(timerRef.current);
78
+ timerRef.current = setTimeout(() => {
79
+ setDebouncedText(fullText);
80
+ setDocumentFields(fields);
81
+ setIsLoading(false);
82
+ }, 2e3);
83
+ return () => {
84
+ if (timerRef.current) clearTimeout(timerRef.current);
85
+ };
86
+ }, [title, body, value]);
87
+ return { text: debouncedText, isLoading, documentFields, documentId };
88
+ }
89
+
90
+ // src/hooks/useKeywordAnalysis.ts
91
+ import { useState as useState2, useEffect as useEffect2, useCallback, useRef as useRef2 } from "react";
92
+
93
+ // src/lib/api.ts
94
+ function safeParseJson(text) {
95
+ try {
96
+ return JSON.parse(text);
97
+ } catch {
98
+ for (let i = text.length - 1; i >= 0; i--) {
99
+ if (text[i] === "}" || text[i] === "]") {
100
+ try {
101
+ return JSON.parse(text.substring(0, i + 1));
102
+ } catch {
103
+ continue;
104
+ }
105
+ }
106
+ }
107
+ throw new Error("Invalid JSON response from server");
108
+ }
109
+ }
110
+ async function fetchAnalysis(apiUrl, content, mode, publication, seedKeywords, documentFields, focusKeyword) {
111
+ const response = await fetch(`${apiUrl}/api/seo-copilot/analyze`, {
112
+ method: "POST",
113
+ headers: { "Content-Type": "application/json" },
114
+ body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword })
115
+ });
116
+ const text = await response.text();
117
+ if (!response.ok) {
118
+ const err = safeParseJson(text);
119
+ throw new Error(err.error || `HTTP ${response.status}`);
120
+ }
121
+ return safeParseJson(text);
122
+ }
123
+ async function fetchChatStream(apiUrl, messages, documentContext, publication, keywordPanelData) {
124
+ const response = await fetch(`${apiUrl}/api/seo-copilot/chat`, {
125
+ method: "POST",
126
+ headers: { "Content-Type": "application/json" },
127
+ body: JSON.stringify({ messages, documentContext, publication, keywordPanelData })
128
+ });
129
+ if (!response.ok) {
130
+ const err = await response.json().catch(() => ({ error: "Request failed" }));
131
+ throw new Error(err.error || `HTTP ${response.status}`);
132
+ }
133
+ return response.body;
134
+ }
135
+ async function submitFeedback(apiUrl, data) {
136
+ await fetch(`${apiUrl}/api/seo-copilot/feedback`, {
137
+ method: "POST",
138
+ headers: { "Content-Type": "application/json" },
139
+ body: JSON.stringify(data)
140
+ });
141
+ }
142
+ async function lookupKeywords(apiUrl, keywords) {
143
+ const response = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
144
+ method: "POST",
145
+ headers: { "Content-Type": "application/json" },
146
+ body: JSON.stringify({ keywords })
147
+ });
148
+ if (!response.ok) {
149
+ const err = await response.json().catch(() => ({ error: "Request failed" }));
150
+ throw new Error(err.error || `HTTP ${response.status}`);
151
+ }
152
+ return response.json();
153
+ }
154
+ async function loadChatHistory(apiUrl, userId, documentId) {
155
+ try {
156
+ const res = await fetch(
157
+ `${apiUrl}/api/seo-copilot/chat-history?userId=${encodeURIComponent(userId)}&documentId=${encodeURIComponent(documentId)}`
158
+ );
159
+ if (!res.ok) return [];
160
+ const data = await res.json();
161
+ return data.messages || [];
162
+ } catch {
163
+ return [];
164
+ }
165
+ }
166
+ async function saveChatHistory(apiUrl, userId, documentId, messages, publication) {
167
+ try {
168
+ await fetch(`${apiUrl}/api/seo-copilot/chat-history`, {
169
+ method: "POST",
170
+ headers: { "Content-Type": "application/json" },
171
+ body: JSON.stringify({ userId, documentId, messages, publication })
172
+ });
173
+ } catch {
174
+ }
175
+ }
176
+
177
+ // src/hooks/useKeywordAnalysis.ts
178
+ function mergeVolumes(analysis, volumeMap) {
179
+ const updated = { ...analysis };
180
+ if (updated.primaryKeywordCandidates && updated.primaryKeywordCandidates.length > 0) {
181
+ updated.primaryKeywordCandidates = updated.primaryKeywordCandidates.map((candidate) => {
182
+ const data = volumeMap.get(candidate.term.toLowerCase());
183
+ return data ? { ...candidate, volume: data.volume, cpc: data.cpc, competition: data.competition } : candidate;
184
+ });
185
+ }
186
+ const primaryData = volumeMap.get(updated.primaryKeyword.term.toLowerCase());
187
+ if (primaryData) {
188
+ updated.primaryKeyword = {
189
+ ...updated.primaryKeyword,
190
+ volume: primaryData.volume,
191
+ cpc: primaryData.cpc,
192
+ competition: primaryData.competition
193
+ };
194
+ }
195
+ updated.supportingKeywords = updated.supportingKeywords.map((kw) => {
196
+ const data = volumeMap.get(kw.term.toLowerCase());
197
+ return data ? { ...kw, volume: data.volume } : kw;
198
+ });
199
+ updated.missingKeywords = updated.missingKeywords.map((kw) => {
200
+ const data = volumeMap.get(kw.term.toLowerCase());
201
+ return data ? { ...kw, volume: data.volume } : kw;
202
+ });
203
+ return updated;
204
+ }
205
+ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFields, focusPrimary, documentId) {
206
+ const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
207
+ const loadCached = () => {
208
+ try {
209
+ if (typeof window !== "undefined" && sessionStorage.getItem("seo-copilot-cache")) {
210
+ sessionStorage.removeItem("seo-copilot-cache");
211
+ }
212
+ const raw = typeof window !== "undefined" ? sessionStorage.getItem(cacheKey) : null;
213
+ if (raw) return JSON.parse(raw);
214
+ } catch {
215
+ }
216
+ return { analysis: null, deepAnalysis: null, seeds: [] };
217
+ };
218
+ const cached = useRef2(loadCached());
219
+ const [analysis, setAnalysisRaw] = useState2(cached.current.analysis);
220
+ const [isLoading, setIsLoading] = useState2(false);
221
+ const [isVolumesLoading, setIsVolumesLoading] = useState2(false);
222
+ const [error, setError] = useState2(null);
223
+ const [deepAnalysis, setDeepAnalysisRaw] = useState2(cached.current.deepAnalysis);
224
+ const [isDeepLoading, setIsDeepLoading] = useState2(false);
225
+ const [aeoTextSnapshot, setAeoTextSnapshot] = useState2("");
226
+ const [aeoContentChanged, setAeoContentChanged] = useState2(false);
227
+ const setAnalysis = useCallback((val) => {
228
+ setAnalysisRaw(val);
229
+ try {
230
+ const prev = loadCached();
231
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: val }));
232
+ } catch {
233
+ }
234
+ }, [cacheKey]);
235
+ const setDeepAnalysis = useCallback((val) => {
236
+ setDeepAnalysisRaw(val);
237
+ try {
238
+ const prev = loadCached();
239
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
240
+ } catch {
241
+ }
242
+ }, [cacheKey]);
243
+ const effectiveSeeds = seedKeywords;
244
+ useEffect2(() => {
245
+ if (deepAnalysis && aeoTextSnapshot && text !== aeoTextSnapshot) {
246
+ setAeoContentChanged(true);
247
+ }
248
+ }, [text, deepAnalysis, aeoTextSnapshot]);
249
+ const volumesLoadedRef = useRef2(false);
250
+ const lastAnalysisRef = useRef2(null);
251
+ const prevSeedsRef = useRef2(effectiveSeeds?.join(",") || "");
252
+ const prevFocusRef = useRef2(focusPrimary || "");
253
+ const currentSeedsKey = effectiveSeeds?.join(",") || "";
254
+ const currentFocusKey = focusPrimary || "";
255
+ if (currentSeedsKey !== prevSeedsRef.current || currentFocusKey !== prevFocusRef.current) {
256
+ volumesLoadedRef.current = false;
257
+ prevSeedsRef.current = currentSeedsKey;
258
+ prevFocusRef.current = currentFocusKey;
259
+ }
260
+ useEffect2(() => {
261
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
262
+ setAnalysis(null);
263
+ volumesLoadedRef.current = false;
264
+ return;
265
+ }
266
+ let cancelled = false;
267
+ setIsLoading(true);
268
+ setError(null);
269
+ fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary).then((result) => {
270
+ if (cancelled) return;
271
+ const analysisResult = result;
272
+ lastAnalysisRef.current = analysisResult;
273
+ setAnalysis(analysisResult);
274
+ setIsLoading(false);
275
+ if (!volumesLoadedRef.current) {
276
+ volumesLoadedRef.current = true;
277
+ doVolumeLookup(analysisResult, cancelled);
278
+ }
279
+ }).catch((err) => {
280
+ if (!cancelled) {
281
+ setError(err.message);
282
+ setIsLoading(false);
283
+ }
284
+ });
285
+ return () => {
286
+ cancelled = true;
287
+ };
288
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
289
+ const doVolumeLookup = useCallback((analysisResult, cancelled) => {
290
+ setIsVolumesLoading(true);
291
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
292
+ const allTerms = [
293
+ .../* @__PURE__ */ new Set([
294
+ ...candidateTerms,
295
+ analysisResult.primaryKeyword.term,
296
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
297
+ ...analysisResult.missingKeywords.map((kw) => kw.term)
298
+ ])
299
+ ];
300
+ lookupKeywords(apiUrl, allTerms).then(({ results }) => {
301
+ if (cancelled) return;
302
+ const volumeMap = new Map(
303
+ results.map((r) => [r.keyword.toLowerCase(), r])
304
+ );
305
+ setAnalysis(mergeVolumes(analysisResult, volumeMap));
306
+ setIsVolumesLoading(false);
307
+ }).catch(() => {
308
+ if (!cancelled) {
309
+ setIsVolumesLoading(false);
310
+ }
311
+ });
312
+ }, [apiUrl]);
313
+ const refreshVolumes = useCallback(() => {
314
+ const current = lastAnalysisRef.current || analysis;
315
+ if (!current) return;
316
+ doVolumeLookup(current);
317
+ }, [analysis, doVolumeLookup]);
318
+ const runDeepAnalysis = useCallback(() => {
319
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) return;
320
+ setIsDeepLoading(true);
321
+ setError(null);
322
+ setAeoContentChanged(false);
323
+ setAeoTextSnapshot(text);
324
+ fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary).then((result) => {
325
+ setDeepAnalysis(result);
326
+ setIsDeepLoading(false);
327
+ }).catch((err) => {
328
+ setError(err.message);
329
+ setIsDeepLoading(false);
330
+ });
331
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
332
+ return {
333
+ analysis,
334
+ isLoading,
335
+ isVolumesLoading,
336
+ error,
337
+ deepAnalysis,
338
+ isDeepLoading,
339
+ runDeepAnalysis,
340
+ refreshVolumes,
341
+ aeoContentChanged
342
+ };
343
+ }
344
+
345
+ // src/components/ConfigContext.tsx
346
+ import { createContext, useContext } from "react";
347
+ import { jsx } from "react/jsx-runtime";
348
+ var ConfigContext = createContext({
349
+ apiUrl: "http://localhost:3000"
350
+ });
351
+ function ConfigProvider({
352
+ config,
353
+ children
354
+ }) {
355
+ return /* @__PURE__ */ jsx(ConfigContext.Provider, { value: config, children });
356
+ }
357
+ function useConfig() {
358
+ return useContext(ConfigContext);
359
+ }
360
+
361
+ // src/components/KeywordPanel.tsx
362
+ import { useState as useState6, useEffect as useEffect4, useCallback as useCallback2, useRef as useRef5 } from "react";
363
+
364
+ // src/components/PlacementIndicators.tsx
365
+ import { useState as useState3 } from "react";
366
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
367
+ var indicators = [
368
+ { key: "inBody", letter: "B", tooltip: "Keyword in body" },
369
+ { key: "inTitle", letter: "T", tooltip: "Keyword in title" },
370
+ { key: "inMetaDescription", letter: "D", tooltip: "Keyword in meta description" },
371
+ { key: "inImages", letter: "I", tooltip: "Keyword in image names" },
372
+ { key: "inUrl", letter: "U", tooltip: "Keyword in URL" }
373
+ ];
374
+ function IndicatorDot({ letter, active, tooltip }) {
375
+ const [hovered, setHovered] = useState3(false);
376
+ return /* @__PURE__ */ jsxs(
377
+ "span",
378
+ {
379
+ onMouseEnter: () => setHovered(true),
380
+ onMouseLeave: () => setHovered(false),
381
+ style: {
382
+ position: "relative",
383
+ display: "inline-flex",
384
+ alignItems: "center",
385
+ justifyContent: "center",
386
+ width: 16,
387
+ height: 16,
388
+ borderRadius: "50%",
389
+ fontSize: 8,
390
+ fontWeight: 700,
391
+ lineHeight: 1,
392
+ cursor: "default",
393
+ flexShrink: 0,
394
+ background: active ? "#16a34a" : "transparent",
395
+ color: active ? "#ffffff" : "#d1d5db",
396
+ border: active ? "none" : "1.5px solid #d1d5db",
397
+ transition: "all 150ms"
398
+ },
399
+ children: [
400
+ letter,
401
+ hovered && /* @__PURE__ */ jsx2("span", { style: {
402
+ position: "absolute",
403
+ bottom: "100%",
404
+ left: "50%",
405
+ transform: "translateX(-50%)",
406
+ marginBottom: 4,
407
+ padding: "2px 6px",
408
+ borderRadius: 4,
409
+ background: "#1f2937",
410
+ color: "#ffffff",
411
+ fontSize: 10,
412
+ whiteSpace: "nowrap",
413
+ pointerEvents: "none",
414
+ zIndex: 10
415
+ }, children: tooltip })
416
+ ]
417
+ }
418
+ );
419
+ }
420
+ function PlacementIndicators({ placement }) {
421
+ if (!placement) return null;
422
+ return /* @__PURE__ */ jsx2("div", { style: { display: "flex", alignItems: "center", gap: 2 }, children: indicators.map(({ key, letter, tooltip }) => /* @__PURE__ */ jsx2(IndicatorDot, { letter, active: placement[key], tooltip }, key)) });
423
+ }
424
+
425
+ // src/components/SeedKeywordInput.tsx
426
+ import { useState as useState4, useRef as useRef3 } from "react";
427
+
428
+ // src/components/styles.ts
429
+ var INJECTED_CSS = `
430
+ @keyframes bar-shift-1 {
431
+ 0%, 100% { height: 8px; }
432
+ 25% { height: 14px; }
433
+ 50% { height: 6px; }
434
+ 75% { height: 12px; }
435
+ }
436
+ @keyframes bar-shift-2 {
437
+ 0%, 100% { height: 12px; }
438
+ 25% { height: 6px; }
439
+ 50% { height: 14px; }
440
+ 75% { height: 8px; }
441
+ }
442
+ @keyframes bar-shift-3 {
443
+ 0%, 100% { height: 6px; }
444
+ 25% { height: 10px; }
445
+ 50% { height: 12px; }
446
+ 75% { height: 5px; }
447
+ }
448
+ @keyframes fade-up {
449
+ from { opacity: 0; transform: translateY(6px); }
450
+ to { opacity: 1; transform: translateY(0); }
451
+ }
452
+ @keyframes spin {
453
+ from { transform: rotate(0deg); }
454
+ to { transform: rotate(360deg); }
455
+ }
456
+ @keyframes content-pulse {
457
+ 0%, 100% { opacity: 0.5; }
458
+ 50% { opacity: 1; }
459
+ }
460
+ .prose-chat { font-size: 12.5px; line-height: 1.65; color: #475569; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; }
461
+ .prose-chat h1 { font-size: 14px; font-weight: 700; color: #1e293b; margin: 10px 0 5px 0; line-height: 1.35; }
462
+ .prose-chat h2, .prose-chat h3 { font-size: 13px; font-weight: 700; color: #1e293b; margin: 10px 0 5px 0; line-height: 1.35; }
463
+ .prose-chat p { margin: 5px 0; }
464
+ .prose-chat ul, .prose-chat ol { margin: 5px 0; padding-left: 18px; }
465
+ .prose-chat li { margin: 3px 0; }
466
+ .prose-chat strong { font-weight: 600; color: #1e293b; }
467
+ .prose-chat hr { border: none; border-top: 1px solid #f1f5f9; margin: 10px 0; }
468
+ .prose-chat code { background: #f8fafc; padding: 2px 5px; border-radius: 4px; font-size: 11px; border: 1px solid #f1f5f9; }
469
+ .prose-chat a { color: #005DAC; text-decoration: none; border-bottom: 1px solid rgba(0,93,172,0.3); }
470
+ .prose-chat a:hover { border-bottom-color: #005DAC; }
471
+ .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; }
472
+ .prose-chat th { text-align: left; padding: 6px 10px; font-weight: 600; color: #475569; border-bottom: 1px solid #f1f5f9; background: #fafbfc; }
473
+ .prose-chat td { padding: 6px 10px; border-bottom: 1px solid #f8fafc; color: #64748b; }
474
+ .prose-chat tr:last-child td { border-bottom: none; }
475
+
476
+ /* Thin scrollbars */
477
+ .seo-copilot-panel { scrollbar-width: thin; scrollbar-color: #e5e7eb transparent; }
478
+ .seo-copilot-panel ::-webkit-scrollbar { width: 4px; }
479
+ .seo-copilot-panel ::-webkit-scrollbar-track { background: transparent; }
480
+ .seo-copilot-panel ::-webkit-scrollbar-thumb { background: #e5e7eb; border-radius: 4px; }
481
+ .seo-copilot-panel * { scrollbar-width: thin; scrollbar-color: #e5e7eb transparent; }
482
+
483
+ /* Dark mode overrides - Sanity adds data-scheme="dark" or [data-ui-color-scheme="dark"] */
484
+ @media (prefers-color-scheme: dark) {
485
+ .seo-copilot-panel { color-scheme: light; }
486
+ }
487
+ /* Force light text colors when Sanity is in dark mode - the panel bg stays white but text was washing out */
488
+ [data-scheme="dark"] .seo-copilot-panel,
489
+ [data-ui-color-scheme="dark"] .seo-copilot-panel {
490
+ color: #374151;
491
+ }
492
+ [data-scheme="dark"] .seo-copilot-panel *,
493
+ [data-ui-color-scheme="dark"] .seo-copilot-panel * {
494
+ color-scheme: light;
495
+ }
496
+ `;
497
+ var MJH_GOLD = "#E6C01B";
498
+ var MJH_BLUE = "#005DAC";
499
+ var MJH_SLATE = "#4D596A";
500
+ var USER_BLUE = "#DFF4FD";
501
+ var USER_BLUE_BORDER = "#B8E3F9";
502
+
503
+ // src/components/SeedKeywordInput.tsx
504
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
505
+ function parseSeedInput(input) {
506
+ return input.split(/[,\n]+/).map((s) => s.trim()).filter((s) => s.length > 0);
507
+ }
508
+ function SeedKeywordInput({ seeds, onSeedsChange }) {
509
+ const [inputValue, setInputValue] = useState4("");
510
+ const inputRef = useRef3(null);
511
+ const handleAdd = () => {
512
+ const parsed = parseSeedInput(inputValue);
513
+ if (parsed.length > 0) {
514
+ const combined = [.../* @__PURE__ */ new Set([...seeds, ...parsed])];
515
+ onSeedsChange(combined);
516
+ setInputValue("");
517
+ }
518
+ };
519
+ const handleRemove = (term) => {
520
+ onSeedsChange(seeds.filter((s) => s !== term));
521
+ };
522
+ const handleKeyDown = (e) => {
523
+ if (e.key === "Enter" && !e.shiftKey) {
524
+ e.preventDefault();
525
+ handleAdd();
526
+ }
527
+ };
528
+ return /* @__PURE__ */ jsxs2("div", { style: {
529
+ borderRadius: 14,
530
+ background: "#ffffff",
531
+ boxShadow: "0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.03)",
532
+ padding: "12px 14px"
533
+ }, children: [
534
+ /* @__PURE__ */ jsx3("span", { style: { fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8", fontWeight: 600 }, children: "Seed Keywords" }),
535
+ seeds.length > 0 && /* @__PURE__ */ jsx3("div", { style: { display: "flex", flexWrap: "wrap", gap: 5, marginTop: 8 }, children: seeds.map((seed) => /* @__PURE__ */ jsxs2("span", { style: {
536
+ display: "inline-flex",
537
+ alignItems: "center",
538
+ gap: 5,
539
+ padding: "3px 10px",
540
+ borderRadius: 99,
541
+ fontSize: 11.5,
542
+ fontWeight: 500,
543
+ background: `rgba(230,192,27,0.12)`,
544
+ color: "#92810F",
545
+ transition: "all 150ms"
546
+ }, children: [
547
+ seed,
548
+ /* @__PURE__ */ jsx3(
549
+ "button",
550
+ {
551
+ onClick: () => handleRemove(seed),
552
+ style: { background: "none", border: "none", cursor: "pointer", padding: 0, fontSize: 12, color: "#8B7310", lineHeight: 1 },
553
+ children: "x"
554
+ }
555
+ )
556
+ ] }, seed)) }),
557
+ /* @__PURE__ */ jsxs2("div", { style: { marginTop: 8 }, children: [
558
+ /* @__PURE__ */ jsx3(
559
+ "textarea",
560
+ {
561
+ ref: inputRef,
562
+ value: inputValue,
563
+ onChange: (e) => setInputValue(e.target.value),
564
+ onKeyDown: handleKeyDown,
565
+ placeholder: "Enter 2-3 word phrases for best results",
566
+ rows: 2,
567
+ style: {
568
+ width: "100%",
569
+ padding: "8px 10px",
570
+ fontSize: 12.5,
571
+ borderRadius: 10,
572
+ border: "1px solid #e2e8f0",
573
+ background: "#fafbfc",
574
+ resize: "vertical",
575
+ outline: "none",
576
+ fontFamily: "inherit",
577
+ boxSizing: "border-box"
578
+ }
579
+ }
580
+ ),
581
+ /* @__PURE__ */ jsx3(
582
+ "button",
583
+ {
584
+ onClick: handleAdd,
585
+ disabled: !inputValue.trim(),
586
+ style: {
587
+ marginTop: 4,
588
+ padding: "4px 12px",
589
+ fontSize: 11,
590
+ fontWeight: 600,
591
+ borderRadius: 6,
592
+ border: "none",
593
+ background: inputValue.trim() ? MJH_GOLD : "#e5e7eb",
594
+ color: inputValue.trim() ? "#ffffff" : "#9ca3af",
595
+ cursor: inputValue.trim() ? "pointer" : "not-allowed",
596
+ transition: "all 150ms"
597
+ },
598
+ children: "Add"
599
+ }
600
+ ),
601
+ /* @__PURE__ */ jsx3("div", { style: { marginTop: 4, fontSize: 10, color: "#9ca3af" }, children: "Tip: Long-tail keywords (2-3+ words) give better results than single broad terms" })
602
+ ] })
603
+ ] });
604
+ }
605
+
606
+ // src/components/FeedbackButton.tsx
607
+ import { useState as useState5, useRef as useRef4, useEffect as useEffect3 } from "react";
608
+ import { Fragment, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
609
+ function FeedbackButton({ suggestionType, suggestionText, documentId, publication }) {
610
+ const { apiUrl } = useConfig();
611
+ const [vote, setVote] = useState5(null);
612
+ const [showReasonPopup, setShowReasonPopup] = useState5(false);
613
+ const [reason, setReason] = useState5("");
614
+ const [submitted, setSubmitted] = useState5(false);
615
+ const popupRef = useRef4(null);
616
+ const inputRef = useRef4(null);
617
+ useEffect3(() => {
618
+ if (!showReasonPopup) return;
619
+ const handler = (e) => {
620
+ if (popupRef.current && !popupRef.current.contains(e.target)) {
621
+ setShowReasonPopup(false);
622
+ }
623
+ };
624
+ document.addEventListener("mousedown", handler);
625
+ return () => document.removeEventListener("mousedown", handler);
626
+ }, [showReasonPopup]);
627
+ useEffect3(() => {
628
+ if (showReasonPopup) {
629
+ setTimeout(() => inputRef.current?.focus(), 50);
630
+ }
631
+ }, [showReasonPopup]);
632
+ const handleVote = async (v) => {
633
+ if (v === "down" && vote !== "down") {
634
+ setVote("down");
635
+ setShowReasonPopup(true);
636
+ setSubmitted(false);
637
+ try {
638
+ await submitFeedback(apiUrl, {
639
+ suggestion_type: suggestionType,
640
+ suggestion_text: suggestionText,
641
+ vote: "down",
642
+ document_id: documentId,
643
+ publication
644
+ });
645
+ } catch {
646
+ }
647
+ return;
648
+ }
649
+ const newVote = vote === v ? null : v;
650
+ setVote(newVote);
651
+ setShowReasonPopup(false);
652
+ if (newVote) {
653
+ try {
654
+ await submitFeedback(apiUrl, {
655
+ suggestion_type: suggestionType,
656
+ suggestion_text: suggestionText,
657
+ vote: newVote,
658
+ document_id: documentId,
659
+ publication
660
+ });
661
+ } catch {
662
+ }
663
+ }
664
+ };
665
+ const handleSubmitReason = async () => {
666
+ const trimmed = reason.trim();
667
+ if (trimmed) {
668
+ try {
669
+ await submitFeedback(apiUrl, {
670
+ suggestion_type: suggestionType + "_reason",
671
+ suggestion_text: suggestionText + " | REASON: " + trimmed,
672
+ vote: "down",
673
+ document_id: documentId,
674
+ publication
675
+ });
676
+ } catch {
677
+ }
678
+ }
679
+ setSubmitted(true);
680
+ setTimeout(() => {
681
+ setShowReasonPopup(false);
682
+ setReason("");
683
+ }, 1e3);
684
+ };
685
+ return /* @__PURE__ */ jsxs3("div", { style: { display: "flex", alignItems: "center", gap: 2, flexShrink: 0, position: "relative" }, children: [
686
+ /* @__PURE__ */ jsx4(
687
+ "button",
688
+ {
689
+ onClick: () => handleVote("up"),
690
+ style: {
691
+ background: "none",
692
+ border: "none",
693
+ cursor: "pointer",
694
+ padding: 1,
695
+ fontSize: 12,
696
+ color: vote === "up" ? "#16a34a" : "#d1d5db",
697
+ transition: "color 150ms",
698
+ lineHeight: 1,
699
+ display: "flex"
700
+ },
701
+ title: "Good suggestion",
702
+ children: /* @__PURE__ */ jsx4("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx4("path", { d: "M1 8.25a1.25 1.25 0 112.5 0v7.5a1.25 1.25 0 11-2.5 0v-7.5zM11 3V1.7c0-.268.14-.526.395-.607A2 2 0 0114 3c0 .995-.182 1.948-.514 2.826-.204.54.166 1.174.744 1.174h2.52c1.243 0 2.261 1.01 2.146 2.247a23.864 23.864 0 01-1.341 5.974 1.637 1.637 0 01-1.555 1.029H6.5V7.5L11 3z" }) })
703
+ }
704
+ ),
705
+ /* @__PURE__ */ jsx4(
706
+ "button",
707
+ {
708
+ onClick: () => handleVote("down"),
709
+ style: {
710
+ background: "none",
711
+ border: "none",
712
+ cursor: "pointer",
713
+ padding: 1,
714
+ fontSize: 12,
715
+ color: vote === "down" ? "#dc2626" : "#d1d5db",
716
+ transition: "color 150ms",
717
+ lineHeight: 1,
718
+ display: "flex"
719
+ },
720
+ title: "Not helpful",
721
+ children: /* @__PURE__ */ jsx4("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx4("path", { d: "M19 11.75a1.25 1.25 0 11-2.5 0v-7.5a1.25 1.25 0 112.5 0v7.5zM9 17v1.3c0 .268-.14.526-.395.607A2 2 0 016 17c0-.995.182-1.948.514-2.826.204-.54-.166-1.174-.744-1.174H3.25c-1.243 0-2.261-1.01-2.146-2.247a23.864 23.864 0 011.341-5.974A1.637 1.637 0 014 3.75h9.5V12.5L9 17z" }) })
722
+ }
723
+ ),
724
+ showReasonPopup && /* @__PURE__ */ jsx4(
725
+ "div",
726
+ {
727
+ ref: popupRef,
728
+ style: {
729
+ position: "absolute",
730
+ top: "100%",
731
+ right: 0,
732
+ marginTop: 4,
733
+ width: 220,
734
+ padding: 10,
735
+ borderRadius: 10,
736
+ background: "#ffffff",
737
+ boxShadow: "0 4px 16px rgba(0,0,0,0.15), 0 1px 4px rgba(0,0,0,0.1)",
738
+ zIndex: 100,
739
+ border: "1px solid #e5e7eb"
740
+ },
741
+ children: submitted ? /* @__PURE__ */ jsx4("div", { style: { fontSize: 11, color: "#16a34a", textAlign: "center", padding: "4px 0" }, children: "Thanks for the feedback!" }) : /* @__PURE__ */ jsxs3(Fragment, { children: [
742
+ /* @__PURE__ */ jsx4("div", { style: { fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 6 }, children: "Sorry! What went wrong?" }),
743
+ /* @__PURE__ */ jsx4(
744
+ "input",
745
+ {
746
+ ref: inputRef,
747
+ type: "text",
748
+ value: reason,
749
+ onChange: (e) => setReason(e.target.value),
750
+ onKeyDown: (e) => {
751
+ if (e.key === "Enter") handleSubmitReason();
752
+ },
753
+ placeholder: "Tell us what to improve...",
754
+ style: {
755
+ width: "100%",
756
+ padding: "5px 8px",
757
+ fontSize: 11,
758
+ borderRadius: 6,
759
+ border: "1px solid #e5e7eb",
760
+ outline: "none",
761
+ fontFamily: "inherit",
762
+ boxSizing: "border-box"
763
+ }
764
+ }
765
+ ),
766
+ /* @__PURE__ */ jsxs3("div", { style: { display: "flex", justifyContent: "flex-end", marginTop: 6, gap: 4 }, children: [
767
+ /* @__PURE__ */ jsx4(
768
+ "button",
769
+ {
770
+ onClick: () => {
771
+ setShowReasonPopup(false);
772
+ setReason("");
773
+ },
774
+ style: {
775
+ padding: "3px 8px",
776
+ fontSize: 10,
777
+ borderRadius: 4,
778
+ border: "1px solid #e5e7eb",
779
+ background: "#ffffff",
780
+ color: "#6b7280",
781
+ cursor: "pointer"
782
+ },
783
+ children: "Skip"
784
+ }
785
+ ),
786
+ /* @__PURE__ */ jsx4(
787
+ "button",
788
+ {
789
+ onClick: handleSubmitReason,
790
+ style: {
791
+ padding: "3px 8px",
792
+ fontSize: 10,
793
+ borderRadius: 4,
794
+ border: "none",
795
+ background: "#dc2626",
796
+ color: "#ffffff",
797
+ cursor: "pointer",
798
+ fontWeight: 600
799
+ },
800
+ children: "Submit"
801
+ }
802
+ )
803
+ ] })
804
+ ] })
805
+ }
806
+ )
807
+ ] });
808
+ }
809
+
810
+ // src/components/KeywordPanel.tsx
811
+ import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
812
+ var AEO_PURPLE = "#7C3AED";
813
+ function SectionHeader({ label, iconColor, actionButton }) {
814
+ return /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }, children: [
815
+ /* @__PURE__ */ jsx5("div", { style: { width: 7, height: 7, borderRadius: "50%", background: iconColor, flexShrink: 0 } }),
816
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8", fontWeight: 600, flex: 1 }, children: label }),
817
+ actionButton
818
+ ] });
819
+ }
820
+ var cardStyle = {
821
+ borderRadius: 14,
822
+ background: "#ffffff",
823
+ boxShadow: "0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.03)",
824
+ padding: "14px"
825
+ };
826
+ function abbrevVol(v) {
827
+ if (v == null) return "";
828
+ if (v === 0) return "N/A";
829
+ if (v >= 1e4) return Math.round(v / 1e3) + "K";
830
+ if (v >= 1e3) return (v / 1e3).toFixed(1) + "K";
831
+ return String(v);
832
+ }
833
+ function placementCount(p) {
834
+ if (!p) return 0;
835
+ return [p.inBody, p.inTitle, p.inMetaDescription, p.inImages, p.inUrl].filter(Boolean).length;
836
+ }
837
+ function buildSuggestedKeywords(supporting, missing, documentText) {
838
+ const merged = [];
839
+ const lowerText = documentText.toLowerCase();
840
+ for (const kw of supporting) {
841
+ const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
842
+ merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: kw.placement });
843
+ }
844
+ for (const kw of missing) {
845
+ const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
846
+ merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: kw.placement });
847
+ }
848
+ merged.sort((a, b) => {
849
+ const pDiff = placementCount(b.placement) - placementCount(a.placement);
850
+ if (pDiff !== 0) return pDiff;
851
+ return b.volume - a.volume;
852
+ });
853
+ return merged;
854
+ }
855
+ function LightbulbButton({ onClick, isLoading }) {
856
+ const [hovered, setHovered] = useState6(false);
857
+ return /* @__PURE__ */ jsxs4(
858
+ "span",
859
+ {
860
+ onClick: (e) => {
861
+ e.stopPropagation();
862
+ onClick();
863
+ },
864
+ onMouseEnter: () => setHovered(true),
865
+ onMouseLeave: () => setHovered(false),
866
+ style: {
867
+ position: "relative",
868
+ cursor: isLoading ? "wait" : "pointer",
869
+ fontSize: 14,
870
+ lineHeight: 1,
871
+ opacity: isLoading ? 0.5 : 1,
872
+ flexShrink: 0,
873
+ display: "inline-flex",
874
+ alignItems: "center"
875
+ },
876
+ title: "How to use this keyword",
877
+ children: [
878
+ isLoading ? /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: MJH_GOLD }) : "\u{1F4A1}",
879
+ hovered && !isLoading && /* @__PURE__ */ jsx5("span", { style: {
880
+ position: "absolute",
881
+ bottom: "100%",
882
+ left: "50%",
883
+ transform: "translateX(-50%)",
884
+ marginBottom: 4,
885
+ padding: "2px 6px",
886
+ borderRadius: 4,
887
+ background: "#1f2937",
888
+ color: "#ffffff",
889
+ fontSize: 10,
890
+ whiteSpace: "nowrap",
891
+ pointerEvents: "none",
892
+ zIndex: 10
893
+ }, children: "How to use" })
894
+ ]
895
+ }
896
+ );
897
+ }
898
+ function HighlightKeyword({ text, keyword }) {
899
+ if (!keyword || !text) return /* @__PURE__ */ jsx5(Fragment2, { children: text });
900
+ const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "gi");
901
+ const parts = text.split(regex);
902
+ return /* @__PURE__ */ jsx5(Fragment2, { children: parts.map(
903
+ (part, i) => regex.test(part) ? /* @__PURE__ */ jsx5("span", { style: { background: "#FEF08A", fontWeight: 600, borderRadius: 2, padding: "0 1px" }, children: part }, i) : /* @__PURE__ */ jsx5("span", { children: part }, i)
904
+ ) });
905
+ }
906
+ function KeywordHelpDisplay({ suggestions, onRegenerate, isRegenerating, term, publication }) {
907
+ return /* @__PURE__ */ jsxs4("div", { style: { paddingLeft: 8, paddingTop: 4, paddingBottom: 4, display: "flex", flexDirection: "column", gap: 6 }, children: [
908
+ suggestions.map((s, i) => /* @__PURE__ */ jsx5("div", { style: { fontSize: 11, lineHeight: 1.5, padding: "6px 8px", background: "rgba(0,93,172,0.05)", borderRadius: 6, borderLeft: `2px solid ${MJH_BLUE}` }, children: /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between" }, children: [
909
+ /* @__PURE__ */ jsx5("div", { style: { flex: 1 }, children: s.type === "change" ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
910
+ /* @__PURE__ */ jsx5("div", { style: { color: "#9ca3af", fontWeight: 600, fontSize: 10, textTransform: "uppercase", marginBottom: 2 }, children: "Change" }),
911
+ /* @__PURE__ */ jsx5("div", { style: { color: "#991b1b", textDecoration: "line-through", marginBottom: 2 }, children: s.original }),
912
+ /* @__PURE__ */ jsx5("div", { style: { color: "#166534" }, children: /* @__PURE__ */ jsx5(HighlightKeyword, { text: s.revised || "", keyword: term }) })
913
+ ] }) : /* @__PURE__ */ jsxs4(Fragment2, { children: [
914
+ /* @__PURE__ */ jsxs4("div", { style: { color: "#9ca3af", fontWeight: 600, fontSize: 10, textTransform: "uppercase", marginBottom: 2 }, children: [
915
+ "Add",
916
+ s.where ? ` - ${s.where}` : ""
917
+ ] }),
918
+ /* @__PURE__ */ jsx5("div", { style: { color: "#374151" }, children: /* @__PURE__ */ jsx5(HighlightKeyword, { text: s.sentence || "", keyword: term }) })
919
+ ] }) }),
920
+ /* @__PURE__ */ jsx5(
921
+ FeedbackButton,
922
+ {
923
+ suggestionType: "keyword_help",
924
+ suggestionText: `${term}: ${s.type === "change" ? s.revised : s.sentence}`,
925
+ publication
926
+ }
927
+ )
928
+ ] }) }, i)),
929
+ /* @__PURE__ */ jsxs4(
930
+ "button",
931
+ {
932
+ onClick: onRegenerate,
933
+ disabled: isRegenerating,
934
+ style: {
935
+ display: "flex",
936
+ alignItems: "center",
937
+ gap: 4,
938
+ padding: "4px 8px",
939
+ fontSize: 10,
940
+ color: isRegenerating ? "#9ca3af" : MJH_BLUE,
941
+ background: "none",
942
+ border: "none",
943
+ cursor: isRegenerating ? "wait" : "pointer",
944
+ alignSelf: "flex-start",
945
+ transition: "color 150ms"
946
+ },
947
+ title: "Regenerate suggestions",
948
+ children: [
949
+ /* @__PURE__ */ jsx5("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", style: { animation: isRegenerating ? "spin 1s linear infinite" : "none" }, children: /* @__PURE__ */ jsx5("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" }) }),
950
+ isRegenerating ? "Regenerating..." : "Regenerate"
951
+ ]
952
+ }
953
+ )
954
+ ] });
955
+ }
956
+ function PencilButton({ onClick, active }) {
957
+ return /* @__PURE__ */ jsx5(
958
+ "button",
959
+ {
960
+ onClick,
961
+ style: {
962
+ background: "none",
963
+ border: "none",
964
+ cursor: "pointer",
965
+ padding: 2,
966
+ display: "flex",
967
+ alignItems: "center",
968
+ color: active ? MJH_GOLD : "#9ca3af",
969
+ transition: "color 150ms",
970
+ flexShrink: 0
971
+ },
972
+ title: "Add custom keyword",
973
+ children: /* @__PURE__ */ jsx5("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx5("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" }) })
974
+ }
975
+ );
976
+ }
977
+ function PrimaryKeywordSelector({
978
+ candidates,
979
+ selectedTerm,
980
+ onSelect,
981
+ publication,
982
+ documentId
983
+ }) {
984
+ const [customInputOpen, setCustomInputOpen] = useState6(false);
985
+ const [customValue, setCustomValue] = useState6("");
986
+ const handleCustomSubmit = () => {
987
+ const trimmed = customValue.trim();
988
+ if (trimmed) {
989
+ onSelect(trimmed);
990
+ setCustomValue("");
991
+ setCustomInputOpen(false);
992
+ }
993
+ };
994
+ return /* @__PURE__ */ jsxs4("div", { style: cardStyle, children: [
995
+ /* @__PURE__ */ jsx5(
996
+ SectionHeader,
997
+ {
998
+ label: "Primary Keyword",
999
+ iconColor: "#16a34a",
1000
+ actionButton: /* @__PURE__ */ jsx5(PencilButton, { onClick: () => setCustomInputOpen(!customInputOpen), active: customInputOpen })
1001
+ }
1002
+ ),
1003
+ customInputOpen && /* @__PURE__ */ jsxs4("div", { style: { marginBottom: 8, display: "flex", gap: 6 }, children: [
1004
+ /* @__PURE__ */ jsx5(
1005
+ "input",
1006
+ {
1007
+ type: "text",
1008
+ value: customValue,
1009
+ onChange: (e) => setCustomValue(e.target.value),
1010
+ onKeyDown: (e) => {
1011
+ if (e.key === "Enter") handleCustomSubmit();
1012
+ },
1013
+ placeholder: "Type a custom primary keyword",
1014
+ autoFocus: true,
1015
+ style: {
1016
+ flex: 1,
1017
+ padding: "5px 8px",
1018
+ fontSize: 12,
1019
+ borderRadius: 8,
1020
+ border: "1px solid #e5e7eb",
1021
+ outline: "none",
1022
+ fontFamily: "inherit"
1023
+ }
1024
+ }
1025
+ ),
1026
+ /* @__PURE__ */ jsx5(
1027
+ "button",
1028
+ {
1029
+ onClick: handleCustomSubmit,
1030
+ disabled: !customValue.trim(),
1031
+ style: {
1032
+ padding: "5px 10px",
1033
+ fontSize: 11,
1034
+ fontWeight: 600,
1035
+ borderRadius: 6,
1036
+ border: "none",
1037
+ background: customValue.trim() ? MJH_GOLD : "#e5e7eb",
1038
+ color: customValue.trim() ? "#ffffff" : "#9ca3af",
1039
+ cursor: customValue.trim() ? "pointer" : "not-allowed"
1040
+ },
1041
+ children: "Set"
1042
+ }
1043
+ )
1044
+ ] }),
1045
+ /* @__PURE__ */ jsx5("div", { style: { display: "flex", flexDirection: "column", gap: 6 }, children: candidates.map((candidate) => {
1046
+ const isSelected = candidate.term === selectedTerm;
1047
+ return /* @__PURE__ */ jsxs4(
1048
+ "div",
1049
+ {
1050
+ onClick: () => onSelect(candidate.term),
1051
+ style: {
1052
+ display: "flex",
1053
+ alignItems: "center",
1054
+ gap: 8,
1055
+ padding: "6px 8px",
1056
+ borderRadius: 8,
1057
+ cursor: "pointer",
1058
+ background: isSelected ? "rgba(22,163,74,0.06)" : "transparent",
1059
+ border: isSelected ? "1px solid rgba(22,163,74,0.2)" : "1px solid transparent",
1060
+ transition: "all 150ms"
1061
+ },
1062
+ children: [
1063
+ /* @__PURE__ */ jsx5("div", { style: {
1064
+ width: 14,
1065
+ height: 14,
1066
+ borderRadius: "50%",
1067
+ border: isSelected ? "none" : "2px solid #d1d5db",
1068
+ background: isSelected ? "#16a34a" : "transparent",
1069
+ flexShrink: 0,
1070
+ display: "flex",
1071
+ alignItems: "center",
1072
+ justifyContent: "center"
1073
+ }, children: isSelected && /* @__PURE__ */ jsx5("div", { style: { width: 6, height: 6, borderRadius: "50%", background: "#ffffff" } }) }),
1074
+ /* @__PURE__ */ jsxs4("div", { style: { flex: 1, minWidth: 0 }, children: [
1075
+ /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }, children: [
1076
+ /* @__PURE__ */ jsx5("span", { style: {
1077
+ fontSize: 12,
1078
+ fontWeight: isSelected ? 600 : 400,
1079
+ color: isSelected ? "#166534" : "#374151"
1080
+ }, children: candidate.term }),
1081
+ candidate.volume != null && /* @__PURE__ */ jsxs4("span", { style: { fontSize: 11, color: "#9ca3af" }, children: [
1082
+ abbrevVol(candidate.volume),
1083
+ "/mo"
1084
+ ] }),
1085
+ /* @__PURE__ */ jsxs4("span", { style: { fontSize: 10, color: "#9ca3af" }, children: [
1086
+ Math.round(candidate.confidence * 100),
1087
+ "% confidence"
1088
+ ] })
1089
+ ] }),
1090
+ candidate.placement && /* @__PURE__ */ jsx5("div", { style: { marginTop: 3 }, children: /* @__PURE__ */ jsx5(PlacementIndicators, { placement: candidate.placement }) })
1091
+ ] })
1092
+ ]
1093
+ },
1094
+ candidate.term
1095
+ );
1096
+ }) })
1097
+ ] });
1098
+ }
1099
+ var PLACEMENT_FILTERS = [
1100
+ { key: "inBody", label: "Body", letter: "B" },
1101
+ { key: "inTitle", label: "Title", letter: "T" },
1102
+ { key: "inMetaDescription", label: "Description", letter: "D" },
1103
+ { key: "inImages", label: "Images", letter: "I" },
1104
+ { key: "inUrl", label: "URL", letter: "U" }
1105
+ ];
1106
+ var INITIAL_SHOW = 8;
1107
+ function computePlacementClient(term, content, fields) {
1108
+ const lower = term.toLowerCase();
1109
+ return {
1110
+ inBody: content.toLowerCase().includes(lower),
1111
+ inTitle: fields?.title?.toLowerCase().includes(lower) ?? false,
1112
+ inMetaDescription: fields?.metaDescription?.toLowerCase().includes(lower) ?? false,
1113
+ inImages: fields?.imageNames?.some((name) => name.toLowerCase().includes(lower)) ?? false,
1114
+ inUrl: fields?.slug?.toLowerCase().includes(lower) ?? false
1115
+ };
1116
+ }
1117
+ function SuggestedKeywordsCard({
1118
+ keywords,
1119
+ text,
1120
+ apiUrl,
1121
+ publication,
1122
+ documentFields,
1123
+ refreshVolumes,
1124
+ isVolumesLoading
1125
+ }) {
1126
+ const [helpData, setHelpData] = useState6({});
1127
+ const [loadingTerm, setLoadingTerm] = useState6(null);
1128
+ const [regeneratingTerm, setRegeneratingTerm] = useState6(null);
1129
+ const [manualInputOpen, setManualInputOpen] = useState6(false);
1130
+ const [manualInputValue, setManualInputValue] = useState6("");
1131
+ const [manualKeywords, setManualKeywords] = useState6([]);
1132
+ const [expanded, setExpanded] = useState6(false);
1133
+ const [extraKeywords, setExtraKeywords] = useState6([]);
1134
+ const [isGeneratingMore, setIsGeneratingMore] = useState6(false);
1135
+ const [sortAsc, setSortAsc] = useState6(false);
1136
+ const [activeFilters, setActiveFilters] = useState6(/* @__PURE__ */ new Set());
1137
+ const [showFilterDropdown, setShowFilterDropdown] = useState6(false);
1138
+ const fetchHelp = async (term, forceRegenerate = false) => {
1139
+ if (helpData[term] && !forceRegenerate) {
1140
+ const next = { ...helpData };
1141
+ delete next[term];
1142
+ setHelpData(next);
1143
+ return;
1144
+ }
1145
+ if (forceRegenerate) {
1146
+ setRegeneratingTerm(term);
1147
+ } else {
1148
+ setLoadingTerm(term);
1149
+ }
1150
+ try {
1151
+ const previousSuggestions = forceRegenerate && helpData[term] ? helpData[term].map((s) => s.revised || s.sentence || "").filter(Boolean) : void 0;
1152
+ const res = await fetch(`${apiUrl}/api/seo-copilot/keyword-help`, {
1153
+ method: "POST",
1154
+ headers: { "Content-Type": "application/json" },
1155
+ body: JSON.stringify({ keyword: term, content: text, publication, previousSuggestions })
1156
+ });
1157
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
1158
+ const data = await res.json();
1159
+ setHelpData((prev) => ({ ...prev, [term]: data.suggestions || [] }));
1160
+ } catch {
1161
+ setHelpData((prev) => ({ ...prev, [term]: [{ type: "add", sentence: "Failed to generate suggestions. Try again.", where: "" }] }));
1162
+ }
1163
+ setLoadingTerm(null);
1164
+ setRegeneratingTerm(null);
1165
+ };
1166
+ const [enrichingTerms, setEnrichingTerms] = useState6(/* @__PURE__ */ new Set());
1167
+ const handleAddManual = async () => {
1168
+ const trimmed = manualInputValue.trim();
1169
+ if (!trimmed) return;
1170
+ if (manualKeywords.includes(trimmed) || allKeywords.some((kw) => kw.term.toLowerCase() === trimmed.toLowerCase())) return;
1171
+ setManualKeywords((prev) => [...prev, trimmed]);
1172
+ setManualInputValue("");
1173
+ const placement = computePlacementClient(trimmed, text, documentFields);
1174
+ const inContent = text.toLowerCase().includes(trimmed.toLowerCase());
1175
+ setExtraKeywords((prev) => [...prev, { term: trimmed, volume: 0, inContent, placement }]);
1176
+ setEnrichingTerms((prev) => new Set(prev).add(trimmed));
1177
+ try {
1178
+ const res = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
1179
+ method: "POST",
1180
+ headers: { "Content-Type": "application/json" },
1181
+ body: JSON.stringify({ keywords: [trimmed] })
1182
+ });
1183
+ if (res.ok) {
1184
+ const data = await res.json();
1185
+ const match = (data.results || []).find((r) => r.keyword.toLowerCase() === trimmed.toLowerCase());
1186
+ if (match) {
1187
+ setExtraKeywords((prev) => prev.map(
1188
+ (kw) => kw.term.toLowerCase() === trimmed.toLowerCase() ? { ...kw, volume: match.volume ?? 0 } : kw
1189
+ ));
1190
+ }
1191
+ }
1192
+ } catch {
1193
+ }
1194
+ setEnrichingTerms((prev) => {
1195
+ const next = new Set(prev);
1196
+ next.delete(trimmed);
1197
+ return next;
1198
+ });
1199
+ fetchHelp(trimmed);
1200
+ };
1201
+ const toggleFilter = (key) => {
1202
+ setActiveFilters((prev) => {
1203
+ if (key === "none") {
1204
+ return prev.has("none") ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set(["none"]);
1205
+ }
1206
+ const next = new Set(prev);
1207
+ next.delete("none");
1208
+ if (next.has(key)) {
1209
+ next.delete(key);
1210
+ } else {
1211
+ next.add(key);
1212
+ }
1213
+ return next;
1214
+ });
1215
+ };
1216
+ let filtered = keywords;
1217
+ if (activeFilters.size > 0) {
1218
+ const hasNoneFilter = activeFilters.has("none");
1219
+ const placementFilters = [...activeFilters].filter((f) => f !== "none");
1220
+ filtered = keywords.filter((kw) => {
1221
+ if (hasNoneFilter) {
1222
+ return placementCount(kw.placement) === 0;
1223
+ }
1224
+ if (placementFilters.length === 0) return true;
1225
+ if (!kw.placement) return false;
1226
+ for (const f of placementFilters) {
1227
+ if (f === "none") continue;
1228
+ if (!kw.placement[f]) return false;
1229
+ }
1230
+ return true;
1231
+ });
1232
+ }
1233
+ const sorted = [...filtered].sort((a, b) => {
1234
+ const pA = placementCount(a.placement);
1235
+ const pB = placementCount(b.placement);
1236
+ if (sortAsc) {
1237
+ if (pA !== pB) return pA - pB;
1238
+ return a.volume - b.volume;
1239
+ }
1240
+ if (pA !== pB) return pB - pA;
1241
+ return b.volume - a.volume;
1242
+ });
1243
+ const allKeywords = [...sorted, ...extraKeywords.filter((ek) => !sorted.some((s) => s.term.toLowerCase() === ek.term.toLowerCase()))];
1244
+ const visible = expanded ? allKeywords : allKeywords.slice(0, INITIAL_SHOW);
1245
+ const hiddenCount = allKeywords.length - INITIAL_SHOW;
1246
+ const missingCount = keywords.filter((kw) => !kw.inContent).length;
1247
+ const generateMoreKeywords = async () => {
1248
+ setIsGeneratingMore(true);
1249
+ try {
1250
+ const existingTerms = allKeywords.map((kw) => kw.term);
1251
+ const res = await fetch(`${apiUrl}/api/seo-copilot/more-keywords`, {
1252
+ method: "POST",
1253
+ headers: { "Content-Type": "application/json" },
1254
+ body: JSON.stringify({ content: text, existingKeywords: existingTerms, publication })
1255
+ });
1256
+ if (res.ok) {
1257
+ const data = await res.json();
1258
+ const newKws = (data.keywords || []).map((kw) => ({
1259
+ term: kw.term,
1260
+ volume: kw.volume ?? 0,
1261
+ inContent: kw.inContent
1262
+ }));
1263
+ setExtraKeywords((prev) => [...prev, ...newKws]);
1264
+ }
1265
+ } catch {
1266
+ }
1267
+ setIsGeneratingMore(false);
1268
+ };
1269
+ return /* @__PURE__ */ jsxs4("div", { style: cardStyle, children: [
1270
+ /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }, children: [
1271
+ /* @__PURE__ */ jsx5("div", { style: { width: 6, height: 6, borderRadius: "50%", background: MJH_BLUE, flexShrink: 0 } }),
1272
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em", color: "#9ca3af", fontWeight: 600, flex: 1 }, children: "Supporting Keywords" }),
1273
+ refreshVolumes && /* @__PURE__ */ jsx5(
1274
+ "button",
1275
+ {
1276
+ onClick: refreshVolumes,
1277
+ disabled: isVolumesLoading,
1278
+ style: { background: "none", border: "none", cursor: isVolumesLoading ? "wait" : "pointer", padding: 2, display: "flex", color: isVolumesLoading ? "#d1d5db" : "#9ca3af", fontSize: 10 },
1279
+ title: "Refresh keyword volumes",
1280
+ children: isVolumesLoading ? /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: "#9ca3af" }) : /* @__PURE__ */ jsx5("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", style: { transition: "transform 150ms" }, children: /* @__PURE__ */ jsx5("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" }) })
1281
+ }
1282
+ ),
1283
+ /* @__PURE__ */ jsx5(
1284
+ "button",
1285
+ {
1286
+ onClick: () => setSortAsc(!sortAsc),
1287
+ style: { background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#9ca3af", fontSize: 10 },
1288
+ title: sortAsc ? "Sort: least placements first" : "Sort: most placements first",
1289
+ children: /* @__PURE__ */ jsx5("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", style: { transform: sortAsc ? "rotate(180deg)" : "none", transition: "transform 150ms" }, children: /* @__PURE__ */ jsx5("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" }) })
1290
+ }
1291
+ ),
1292
+ /* @__PURE__ */ jsxs4("div", { style: { position: "relative" }, children: [
1293
+ /* @__PURE__ */ jsxs4(
1294
+ "button",
1295
+ {
1296
+ onClick: () => setShowFilterDropdown(!showFilterDropdown),
1297
+ style: {
1298
+ background: activeFilters.size > 0 ? "rgba(0,93,172,0.1)" : "none",
1299
+ border: "none",
1300
+ cursor: "pointer",
1301
+ padding: "2px 4px",
1302
+ display: "flex",
1303
+ alignItems: "center",
1304
+ gap: 2,
1305
+ color: activeFilters.size > 0 ? MJH_BLUE : "#9ca3af",
1306
+ borderRadius: 4,
1307
+ fontSize: 10
1308
+ },
1309
+ title: "Filter by placement",
1310
+ children: [
1311
+ /* @__PURE__ */ jsx5("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx5("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" }) }),
1312
+ activeFilters.size > 0 && /* @__PURE__ */ jsx5("span", { children: activeFilters.size })
1313
+ ]
1314
+ }
1315
+ ),
1316
+ showFilterDropdown && /* @__PURE__ */ jsxs4("div", { style: {
1317
+ position: "absolute",
1318
+ top: "100%",
1319
+ right: 0,
1320
+ marginTop: 4,
1321
+ width: 150,
1322
+ background: "#ffffff",
1323
+ borderRadius: 8,
1324
+ boxShadow: "0 4px 12px rgba(0,0,0,0.12)",
1325
+ border: "1px solid #e5e7eb",
1326
+ zIndex: 50,
1327
+ padding: "4px 0"
1328
+ }, children: [
1329
+ PLACEMENT_FILTERS.map(({ key, label, letter }) => /* @__PURE__ */ jsxs4(
1330
+ "button",
1331
+ {
1332
+ onClick: () => toggleFilter(key),
1333
+ style: {
1334
+ width: "100%",
1335
+ display: "flex",
1336
+ alignItems: "center",
1337
+ gap: 8,
1338
+ padding: "5px 10px",
1339
+ background: "none",
1340
+ border: "none",
1341
+ cursor: "pointer",
1342
+ fontSize: 11,
1343
+ color: "#374151",
1344
+ textAlign: "left"
1345
+ },
1346
+ children: [
1347
+ /* @__PURE__ */ jsx5("div", { style: {
1348
+ width: 14,
1349
+ height: 14,
1350
+ borderRadius: 3,
1351
+ border: "1.5px solid " + (activeFilters.has(key) ? MJH_BLUE : "#d1d5db"),
1352
+ background: activeFilters.has(key) ? MJH_BLUE : "transparent",
1353
+ display: "flex",
1354
+ alignItems: "center",
1355
+ justifyContent: "center",
1356
+ flexShrink: 0
1357
+ }, children: activeFilters.has(key) && /* @__PURE__ */ jsx5("svg", { width: "8", height: "8", viewBox: "0 0 12 12", fill: "white", children: /* @__PURE__ */ jsx5("path", { d: "M10 3L4.5 8.5 2 6", stroke: "white", strokeWidth: "2", fill: "none", strokeLinecap: "round", strokeLinejoin: "round" }) }) }),
1358
+ /* @__PURE__ */ jsx5("span", { style: { fontWeight: 600, color: "#9ca3af", width: 14 }, children: letter }),
1359
+ /* @__PURE__ */ jsx5("span", { children: label })
1360
+ ]
1361
+ },
1362
+ key
1363
+ )),
1364
+ /* @__PURE__ */ jsxs4(
1365
+ "button",
1366
+ {
1367
+ onClick: () => toggleFilter("none"),
1368
+ style: {
1369
+ width: "100%",
1370
+ display: "flex",
1371
+ alignItems: "center",
1372
+ gap: 8,
1373
+ padding: "5px 10px",
1374
+ background: "none",
1375
+ border: "none",
1376
+ cursor: "pointer",
1377
+ fontSize: 11,
1378
+ color: "#374151",
1379
+ textAlign: "left",
1380
+ borderTop: "1px solid #f1f5f9"
1381
+ },
1382
+ children: [
1383
+ /* @__PURE__ */ jsx5("div", { style: {
1384
+ width: 14,
1385
+ height: 14,
1386
+ borderRadius: 3,
1387
+ border: "1.5px solid " + (activeFilters.has("none") ? MJH_BLUE : "#d1d5db"),
1388
+ background: activeFilters.has("none") ? MJH_BLUE : "transparent",
1389
+ display: "flex",
1390
+ alignItems: "center",
1391
+ justifyContent: "center",
1392
+ flexShrink: 0
1393
+ }, children: activeFilters.has("none") && /* @__PURE__ */ jsx5("svg", { width: "8", height: "8", viewBox: "0 0 12 12", fill: "white", children: /* @__PURE__ */ jsx5("path", { d: "M10 3L4.5 8.5 2 6", stroke: "white", strokeWidth: "2", fill: "none", strokeLinecap: "round", strokeLinejoin: "round" }) }) }),
1394
+ /* @__PURE__ */ jsx5("span", { style: { fontWeight: 600, color: "#9ca3af", width: 14 }, children: "-" }),
1395
+ /* @__PURE__ */ jsx5("span", { children: "None (missing all)" })
1396
+ ]
1397
+ }
1398
+ ),
1399
+ activeFilters.size > 0 && /* @__PURE__ */ jsx5(
1400
+ "button",
1401
+ {
1402
+ onClick: () => {
1403
+ setActiveFilters(/* @__PURE__ */ new Set());
1404
+ setShowFilterDropdown(false);
1405
+ },
1406
+ style: {
1407
+ width: "100%",
1408
+ padding: "5px 10px",
1409
+ background: "none",
1410
+ border: "none",
1411
+ borderTop: "1px solid #f1f5f9",
1412
+ cursor: "pointer",
1413
+ fontSize: 10,
1414
+ color: "#dc2626",
1415
+ textAlign: "center"
1416
+ },
1417
+ children: "Clear filters"
1418
+ }
1419
+ )
1420
+ ] })
1421
+ ] }),
1422
+ /* @__PURE__ */ jsx5(PencilButton, { onClick: () => setManualInputOpen(!manualInputOpen), active: manualInputOpen })
1423
+ ] }),
1424
+ manualInputOpen && /* @__PURE__ */ jsxs4("div", { style: { marginBottom: 8, display: "flex", gap: 6 }, children: [
1425
+ /* @__PURE__ */ jsx5(
1426
+ "input",
1427
+ {
1428
+ type: "text",
1429
+ value: manualInputValue,
1430
+ onChange: (e) => setManualInputValue(e.target.value),
1431
+ onKeyDown: (e) => {
1432
+ if (e.key === "Enter") handleAddManual();
1433
+ },
1434
+ placeholder: "Add a keyword manually",
1435
+ autoFocus: true,
1436
+ style: { flex: 1, padding: "5px 8px", fontSize: 12, borderRadius: 8, border: "1px solid #e5e7eb", outline: "none", fontFamily: "inherit" }
1437
+ }
1438
+ ),
1439
+ /* @__PURE__ */ jsx5(
1440
+ "button",
1441
+ {
1442
+ onClick: handleAddManual,
1443
+ disabled: !manualInputValue.trim(),
1444
+ style: {
1445
+ padding: "5px 10px",
1446
+ fontSize: 11,
1447
+ fontWeight: 600,
1448
+ borderRadius: 6,
1449
+ border: "none",
1450
+ background: manualInputValue.trim() ? MJH_BLUE : "#e5e7eb",
1451
+ color: manualInputValue.trim() ? "#ffffff" : "#9ca3af",
1452
+ cursor: manualInputValue.trim() ? "pointer" : "not-allowed"
1453
+ },
1454
+ children: "Add"
1455
+ }
1456
+ )
1457
+ ] }),
1458
+ /* @__PURE__ */ jsx5("div", { children: visible.map((kw, i) => /* @__PURE__ */ jsxs4("div", { children: [
1459
+ /* @__PURE__ */ jsxs4("div", { style: {
1460
+ display: "flex",
1461
+ alignItems: "center",
1462
+ gap: 8,
1463
+ padding: "5px 0",
1464
+ borderBottom: i < visible.length - 1 ? "1px solid #f3f4f6" : "none",
1465
+ minHeight: 28
1466
+ }, children: [
1467
+ /* @__PURE__ */ jsx5("div", { style: {
1468
+ width: 8,
1469
+ height: 8,
1470
+ borderRadius: "50%",
1471
+ flexShrink: 0,
1472
+ background: kw.inContent ? "#16a34a" : "#d1d5db"
1473
+ } }),
1474
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 12, fontWeight: 500, flexGrow: 1, color: kw.inContent ? "#9ca3af" : "#374151" }, children: kw.term }),
1475
+ enrichingTerms.has(kw.term) && /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: "#9ca3af" }),
1476
+ !enrichingTerms.has(kw.term) && kw.volume != null && /* @__PURE__ */ jsx5("span", { style: { fontSize: 10, color: "#d1d5db", flexShrink: 0 }, children: abbrevVol(kw.volume) }),
1477
+ kw.placement && /* @__PURE__ */ jsx5(PlacementIndicators, { placement: kw.placement }),
1478
+ !kw.inContent && /* @__PURE__ */ jsx5(LightbulbButton, { onClick: () => fetchHelp(kw.term), isLoading: loadingTerm === kw.term })
1479
+ ] }),
1480
+ helpData[kw.term] && /* @__PURE__ */ jsx5(
1481
+ KeywordHelpDisplay,
1482
+ {
1483
+ suggestions: helpData[kw.term],
1484
+ onRegenerate: () => fetchHelp(kw.term, true),
1485
+ isRegenerating: regeneratingTerm === kw.term,
1486
+ term: kw.term,
1487
+ publication
1488
+ }
1489
+ )
1490
+ ] }, kw.term)) }),
1491
+ !expanded && hiddenCount > 0 && /* @__PURE__ */ jsxs4(
1492
+ "button",
1493
+ {
1494
+ onClick: () => setExpanded(true),
1495
+ style: {
1496
+ marginTop: 6,
1497
+ width: "100%",
1498
+ padding: "4px 0",
1499
+ background: "none",
1500
+ border: "none",
1501
+ cursor: "pointer",
1502
+ fontSize: 10,
1503
+ color: "#9ca3af",
1504
+ display: "flex",
1505
+ alignItems: "center",
1506
+ justifyContent: "center",
1507
+ gap: 4
1508
+ },
1509
+ children: [
1510
+ /* @__PURE__ */ jsx5("svg", { width: "10", height: "10", viewBox: "0 0 20 20", fill: "#9ca3af", children: /* @__PURE__ */ jsx5("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" }) }),
1511
+ "Show more"
1512
+ ]
1513
+ }
1514
+ ),
1515
+ expanded && /* @__PURE__ */ jsx5(
1516
+ "button",
1517
+ {
1518
+ onClick: generateMoreKeywords,
1519
+ disabled: isGeneratingMore,
1520
+ style: {
1521
+ marginTop: 6,
1522
+ width: "100%",
1523
+ padding: "5px 0",
1524
+ background: "none",
1525
+ border: "none",
1526
+ cursor: isGeneratingMore ? "wait" : "pointer",
1527
+ fontSize: 10,
1528
+ color: isGeneratingMore ? "#9ca3af" : MJH_BLUE,
1529
+ display: "flex",
1530
+ alignItems: "center",
1531
+ justifyContent: "center",
1532
+ gap: 4,
1533
+ fontWeight: 500
1534
+ },
1535
+ children: isGeneratingMore ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
1536
+ /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: MJH_BLUE }),
1537
+ "Generating..."
1538
+ ] }) : /* @__PURE__ */ jsxs4(Fragment2, { children: [
1539
+ /* @__PURE__ */ jsx5("svg", { width: "10", height: "10", viewBox: "0 0 20 20", fill: MJH_BLUE, children: /* @__PURE__ */ jsx5("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" }) }),
1540
+ "Generate more"
1541
+ ] })
1542
+ }
1543
+ )
1544
+ ] });
1545
+ }
1546
+ function KeywordPanel({
1547
+ text,
1548
+ publication,
1549
+ seedKeywords = [],
1550
+ onSeedsChange,
1551
+ onSelectPrimary,
1552
+ documentFields,
1553
+ externalAnalysis
1554
+ }) {
1555
+ const { apiUrl } = useConfig();
1556
+ const internalAnalysis = useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFields);
1557
+ const activeAnalysis = externalAnalysis || internalAnalysis;
1558
+ const { analysis, isLoading, error, deepAnalysis, isDeepLoading, runDeepAnalysis } = activeAnalysis;
1559
+ const isVolumesLoading = activeAnalysis.isVolumesLoading ?? false;
1560
+ const refreshVolumes = activeAnalysis.refreshVolumes;
1561
+ const aeoContentChanged = activeAnalysis.aeoContentChanged ?? false;
1562
+ const [aeoTriggered, setAeoTriggered] = useState6(false);
1563
+ useEffect4(() => {
1564
+ const hasV2Aeo = deepAnalysis?.aeo?.questionHeadings?.length || deepAnalysis?.aeo?.faqSuggestions?.length;
1565
+ if (analysis && !hasV2Aeo && !isDeepLoading && !aeoTriggered) {
1566
+ setAeoTriggered(true);
1567
+ runDeepAnalysis();
1568
+ }
1569
+ }, [analysis, deepAnalysis, isDeepLoading, aeoTriggered, runDeepAnalysis]);
1570
+ useEffect4(() => {
1571
+ setAeoTriggered(false);
1572
+ }, [text]);
1573
+ const [moreFaqs, setMoreFaqs] = useState6([]);
1574
+ const [isMoreFaqsLoading, setIsMoreFaqsLoading] = useState6(false);
1575
+ const loadMoreFaqs = useCallback2(async () => {
1576
+ const aeo = deepAnalysis?.aeo;
1577
+ const existingQs = [...(aeo?.faqSuggestions ?? aeo?.faqItems ?? []).map((f) => f.question), ...moreFaqs.map((f) => f.question)];
1578
+ setIsMoreFaqsLoading(true);
1579
+ try {
1580
+ const res = await fetch(`${apiUrl}/api/seo-copilot/more-faqs`, {
1581
+ method: "POST",
1582
+ headers: { "Content-Type": "application/json" },
1583
+ body: JSON.stringify({ content: text, existingQuestions: existingQs, publication })
1584
+ });
1585
+ if (res.ok) {
1586
+ const data = await res.json();
1587
+ setMoreFaqs((prev) => [...prev, ...data.faqSuggestions || []]);
1588
+ }
1589
+ } catch {
1590
+ }
1591
+ setIsMoreFaqsLoading(false);
1592
+ }, [deepAnalysis, moreFaqs, apiUrl, text, publication]);
1593
+ const defaultSelectedTerm = analysis?.primaryKeyword?.term ?? "";
1594
+ const [selectedPrimaryTerm, setSelectedPrimaryTerm] = useState6(defaultSelectedTerm);
1595
+ const prevDefaultRef = useRef5(defaultSelectedTerm);
1596
+ useEffect4(() => {
1597
+ if (defaultSelectedTerm && defaultSelectedTerm !== prevDefaultRef.current) {
1598
+ setSelectedPrimaryTerm((prev) => prev === prevDefaultRef.current ? defaultSelectedTerm : prev);
1599
+ prevDefaultRef.current = defaultSelectedTerm;
1600
+ }
1601
+ }, [defaultSelectedTerm]);
1602
+ if ((!text || text.trim().length < 20) && (!seedKeywords || seedKeywords.length === 0)) {
1603
+ return /* @__PURE__ */ jsxs4("div", { style: { padding: 24, textAlign: "center" }, children: [
1604
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 14, color: "#9ca3af", fontWeight: 500 }, children: "Start writing to see keyword suggestions" }),
1605
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 12, color: "#d1d5db", marginTop: 4 }, children: "Need at least a few sentences" })
1606
+ ] });
1607
+ }
1608
+ if (isLoading && !analysis) {
1609
+ return /* @__PURE__ */ jsxs4("div", { style: { padding: 24, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }, children: [
1610
+ /* @__PURE__ */ jsx5(LoadingBars, {}),
1611
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 12, color: "#9ca3af" }, children: "Analyzing content..." })
1612
+ ] });
1613
+ }
1614
+ if (error && !analysis) {
1615
+ return /* @__PURE__ */ jsx5("div", { style: { ...cardStyle, margin: 12, background: "#fef2f2", color: "#dc2626" }, children: /* @__PURE__ */ jsxs4("span", { style: { fontSize: 12 }, children: [
1616
+ "Error: ",
1617
+ error
1618
+ ] }) });
1619
+ }
1620
+ if (!analysis) return null;
1621
+ const suggestedKeywords = buildSuggestedKeywords(
1622
+ analysis.supportingKeywords || [],
1623
+ analysis.missingKeywords,
1624
+ text
1625
+ );
1626
+ const candidates = analysis.primaryKeywordCandidates && analysis.primaryKeywordCandidates.length > 0 ? analysis.primaryKeywordCandidates : [analysis.primaryKeyword];
1627
+ const activeTerm = candidates.find((c) => c.term === selectedPrimaryTerm) ? selectedPrimaryTerm : candidates[0]?.term ?? "";
1628
+ return /* @__PURE__ */ jsxs4("div", { style: { padding: 12, display: "flex", flexDirection: "column", gap: 12 }, children: [
1629
+ onSeedsChange && /* @__PURE__ */ jsx5(SeedKeywordInput, { seeds: seedKeywords, onSeedsChange }),
1630
+ /* @__PURE__ */ jsx5(
1631
+ PrimaryKeywordSelector,
1632
+ {
1633
+ candidates,
1634
+ selectedTerm: activeTerm,
1635
+ onSelect: (term) => {
1636
+ setSelectedPrimaryTerm(term);
1637
+ onSelectPrimary?.(term);
1638
+ },
1639
+ publication
1640
+ }
1641
+ ),
1642
+ suggestedKeywords.length > 0 && /* @__PURE__ */ jsx5(
1643
+ SuggestedKeywordsCard,
1644
+ {
1645
+ keywords: suggestedKeywords,
1646
+ text,
1647
+ apiUrl,
1648
+ publication,
1649
+ documentFields,
1650
+ refreshVolumes,
1651
+ isVolumesLoading
1652
+ }
1653
+ ),
1654
+ !deepAnalysis && isDeepLoading ? /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "12px 0" }, children: [
1655
+ /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: AEO_PURPLE }),
1656
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 12, color: "#9ca3af" }, children: "Generating AEO insights..." })
1657
+ ] }) : deepAnalysis ? /* @__PURE__ */ jsxs4("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
1658
+ /* @__PURE__ */ jsx5("div", { style: { padding: "6px 10px", background: "#fefce8", borderRadius: 8, border: "1px solid #fde68a" }, children: /* @__PURE__ */ jsx5("div", { style: { fontSize: 10, color: "#92400e", lineHeight: 1.5 }, children: "Answers generated by AI may contain inaccuracies. Always verify facts, drug information, and clinical details before publishing." }) }),
1659
+ /* @__PURE__ */ jsx5("div", { style: { ...cardStyle, padding: "8px 14px", background: "rgba(124,58,237,0.03)", borderLeft: "3px solid " + AEO_PURPLE }, children: /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", gap: 7 }, children: [
1660
+ /* @__PURE__ */ jsx5("div", { style: { width: 7, height: 7, borderRadius: "50%", background: AEO_PURPLE, flexShrink: 0 } }),
1661
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8", fontWeight: 600 }, children: "AEO Insights" })
1662
+ ] }) }),
1663
+ !deepAnalysis.aeo && /* @__PURE__ */ jsx5("div", { style: { ...cardStyle, textAlign: "center" }, children: /* @__PURE__ */ jsx5("span", { style: { fontSize: 12, color: "#9ca3af" }, children: "No AEO data was returned. Try again - the analysis may have timed out." }) }),
1664
+ deepAnalysis.aeo && (deepAnalysis.aeo.questionHeadings ?? deepAnalysis.aeo.headingSuggestions ?? []).length > 0 && /* @__PURE__ */ jsxs4("div", { style: cardStyle, children: [
1665
+ /* @__PURE__ */ jsx5(SectionHeader, { label: "Question Headline Recommendations", iconColor: AEO_PURPLE }),
1666
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 10, color: "#9ca3af", marginBottom: 8, marginTop: -4 }, children: "Rewrite your headings as questions. Google targets these for featured snippets." }),
1667
+ /* @__PURE__ */ jsx5("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: (deepAnalysis.aeo.questionHeadings?.map((qh) => ({ heading: qh.suggestedHeading, originalHeading: qh.originalHeading, rationale: qh.rationale })) ?? deepAnalysis.aeo.headingSuggestions?.map((h) => ({ heading: h.heading, originalHeading: void 0, rationale: h.rationale })) ?? []).map((h, i) => /* @__PURE__ */ jsxs4("div", { style: { padding: "8px 10px", background: "rgba(124,58,237,0.03)", borderRadius: 10, borderLeft: "3px solid " + AEO_PURPLE }, children: [
1668
+ /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }, children: [
1669
+ /* @__PURE__ */ jsxs4("div", { style: { flex: 1 }, children: [
1670
+ h.originalHeading && /* @__PURE__ */ jsx5("div", { style: { fontSize: 11, color: "#9ca3af", textDecoration: "line-through", marginBottom: 2 }, children: h.originalHeading }),
1671
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 12, fontWeight: 700, color: AEO_PURPLE, lineHeight: 1.5 }, children: h.heading })
1672
+ ] }),
1673
+ /* @__PURE__ */ jsx5(
1674
+ FeedbackButton,
1675
+ {
1676
+ suggestionType: "aeo_heading",
1677
+ suggestionText: h.heading,
1678
+ publication
1679
+ }
1680
+ )
1681
+ ] }),
1682
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 10, color: "#9ca3af", marginTop: 4, fontStyle: "italic" }, children: h.rationale })
1683
+ ] }, i)) })
1684
+ ] }),
1685
+ (() => {
1686
+ const faqs = deepAnalysis.aeo ? [...deepAnalysis.aeo.faqSuggestions ?? deepAnalysis.aeo.faqItems ?? [], ...moreFaqs] : [];
1687
+ return faqs.length > 0 ? /* @__PURE__ */ jsxs4("div", { style: cardStyle, children: [
1688
+ /* @__PURE__ */ jsx5(SectionHeader, { label: "FAQ Suggestions", iconColor: AEO_PURPLE }),
1689
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 10, color: "#9ca3af", marginBottom: 8, marginTop: -4 }, children: "Add these Q&As at the bottom of your article. Answers are derived from your article content. Can be wrapped with FAQ schema markup." }),
1690
+ /* @__PURE__ */ jsx5("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: faqs.map((faq, i) => /* @__PURE__ */ jsxs4("div", { style: { padding: "8px 10px", background: "rgba(124,58,237,0.03)", borderRadius: 10, borderLeft: "3px solid " + AEO_PURPLE }, children: [
1691
+ /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }, children: [
1692
+ /* @__PURE__ */ jsxs4("span", { style: { fontSize: 12, fontWeight: 700, color: "#1f2937", lineHeight: 1.5 }, children: [
1693
+ "Q: ",
1694
+ faq.question
1695
+ ] }),
1696
+ /* @__PURE__ */ jsx5(
1697
+ FeedbackButton,
1698
+ {
1699
+ suggestionType: "aeo_faq",
1700
+ suggestionText: faq.question,
1701
+ publication
1702
+ }
1703
+ )
1704
+ ] }),
1705
+ /* @__PURE__ */ jsxs4("div", { style: { fontSize: 12, color: "#374151", lineHeight: 1.6, marginTop: 4 }, children: [
1706
+ /* @__PURE__ */ jsx5("span", { style: { fontWeight: 600, color: "#6b7280" }, children: "A: " }),
1707
+ faq.answer
1708
+ ] })
1709
+ ] }, i)) }),
1710
+ /* @__PURE__ */ jsx5(
1711
+ "button",
1712
+ {
1713
+ onClick: loadMoreFaqs,
1714
+ disabled: isMoreFaqsLoading,
1715
+ style: {
1716
+ marginTop: 8,
1717
+ width: "100%",
1718
+ padding: "6px 12px",
1719
+ fontSize: 11,
1720
+ fontWeight: 600,
1721
+ color: isMoreFaqsLoading ? "#9ca3af" : AEO_PURPLE,
1722
+ background: isMoreFaqsLoading ? "#f3f4f6" : "rgba(124,58,237,0.06)",
1723
+ border: "1px solid rgba(124,58,237,0.15)",
1724
+ borderRadius: 6,
1725
+ cursor: isMoreFaqsLoading ? "wait" : "pointer",
1726
+ display: "flex",
1727
+ alignItems: "center",
1728
+ justifyContent: "center",
1729
+ gap: 6,
1730
+ transition: "all 150ms"
1731
+ },
1732
+ children: isMoreFaqsLoading ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
1733
+ /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: AEO_PURPLE }),
1734
+ " Generating..."
1735
+ ] }) : "More FAQ suggestions"
1736
+ }
1737
+ )
1738
+ ] }) : null;
1739
+ })(),
1740
+ aeoContentChanged && /* @__PURE__ */ jsxs4(
1741
+ "div",
1742
+ {
1743
+ onClick: runDeepAnalysis,
1744
+ style: {
1745
+ padding: "8px 12px",
1746
+ background: "#fffbeb",
1747
+ border: "1px solid #fde68a",
1748
+ borderRadius: 8,
1749
+ display: "flex",
1750
+ alignItems: "center",
1751
+ justifyContent: "space-between",
1752
+ cursor: "pointer"
1753
+ },
1754
+ children: [
1755
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 11, color: "#92400e" }, children: "Content has changed since this was generated." }),
1756
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 11, fontWeight: 600, color: AEO_PURPLE, textDecoration: "underline" }, children: "Update" })
1757
+ ]
1758
+ }
1759
+ )
1760
+ ] }) : null,
1761
+ isVolumesLoading && /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", gap: 6, justifyContent: "center", padding: "4px 0" }, children: [
1762
+ /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: MJH_GOLD }),
1763
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 10, color: "#9ca3af" }, children: "Checking search volumes..." })
1764
+ ] }),
1765
+ isLoading && analysis && /* @__PURE__ */ jsxs4("div", { style: { display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }, children: [
1766
+ /* @__PURE__ */ jsx5(LoadingBars, { size: "xs", color: "#9ca3af" }),
1767
+ /* @__PURE__ */ jsx5("span", { style: { fontSize: 10, color: "#9ca3af" }, children: "Updating insights..." })
1768
+ ] })
1769
+ ] });
1770
+ }
1771
+
1772
+ // src/components/ChatPanel.tsx
1773
+ import { useState as useState8, useRef as useRef7, useEffect as useEffect6 } from "react";
1774
+ import ReactMarkdown from "react-markdown";
1775
+ import remarkGfm from "remark-gfm";
1776
+ import { useDocumentPane as useDocumentPane2 } from "sanity/structure";
1777
+
1778
+ // src/hooks/useSEOChat.ts
1779
+ import { useState as useState7, useCallback as useCallback3, useEffect as useEffect5, useRef as useRef6 } from "react";
1780
+ function getUserId() {
1781
+ const key = "seo-copilot-user-id";
1782
+ try {
1783
+ let id = localStorage.getItem(key);
1784
+ if (!id) {
1785
+ id = `user-${Math.random().toString(36).slice(2)}-${Date.now()}`;
1786
+ localStorage.setItem(key, id);
1787
+ }
1788
+ return id;
1789
+ } catch {
1790
+ return "anonymous";
1791
+ }
1792
+ }
1793
+ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documentId) {
1794
+ const chatCacheKey = documentId ? `seo-copilot-chat-${documentId}` : "seo-copilot-chat-default";
1795
+ const [messages, setMessagesRaw] = useState7(() => {
1796
+ try {
1797
+ const cached = typeof window !== "undefined" ? sessionStorage.getItem(chatCacheKey) : null;
1798
+ return cached ? JSON.parse(cached) : [];
1799
+ } catch {
1800
+ return [];
1801
+ }
1802
+ });
1803
+ const setMessages = useCallback3((msgs) => {
1804
+ setMessagesRaw((prev) => {
1805
+ const next = typeof msgs === "function" ? msgs(prev) : msgs;
1806
+ try {
1807
+ sessionStorage.setItem(chatCacheKey, JSON.stringify(next));
1808
+ } catch {
1809
+ }
1810
+ return next;
1811
+ });
1812
+ }, [chatCacheKey]);
1813
+ const [isStreaming, setIsStreaming] = useState7(false);
1814
+ const [historyLoaded, setHistoryLoaded] = useState7(false);
1815
+ const userId = useRef6(getUserId());
1816
+ const saveTimerRef = useRef6(null);
1817
+ useEffect5(() => {
1818
+ if (!documentId || historyLoaded) return;
1819
+ let cancelled = false;
1820
+ loadChatHistory(apiUrl, userId.current, documentId).then((loaded) => {
1821
+ if (!cancelled && loaded.length > 0 && messages.length === 0) {
1822
+ setMessages(loaded);
1823
+ }
1824
+ if (!cancelled) setHistoryLoaded(true);
1825
+ });
1826
+ return () => {
1827
+ cancelled = true;
1828
+ };
1829
+ }, [apiUrl, documentId, historyLoaded]);
1830
+ const scheduleSave = useCallback3((msgs) => {
1831
+ if (!documentId) return;
1832
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
1833
+ saveTimerRef.current = setTimeout(() => {
1834
+ saveChatHistory(apiUrl, userId.current, documentId, msgs, publication);
1835
+ }, 800);
1836
+ }, [apiUrl, documentId, publication]);
1837
+ const sendMessage = useCallback3(
1838
+ async (text) => {
1839
+ const userMessage = { role: "user", content: text };
1840
+ const updatedMessages = [...messages, userMessage];
1841
+ setMessages(updatedMessages);
1842
+ setIsStreaming(true);
1843
+ try {
1844
+ const stream = await fetchChatStream(
1845
+ apiUrl,
1846
+ updatedMessages,
1847
+ documentText,
1848
+ publication,
1849
+ keywordPanelData
1850
+ );
1851
+ if (!stream) {
1852
+ setIsStreaming(false);
1853
+ return;
1854
+ }
1855
+ const reader = stream.getReader();
1856
+ const decoder = new TextDecoder();
1857
+ let assistantContent = "";
1858
+ setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
1859
+ while (true) {
1860
+ const { done, value } = await reader.read();
1861
+ if (done) break;
1862
+ const chunk = decoder.decode(value, { stream: true });
1863
+ const lines = chunk.split("\n");
1864
+ for (const line of lines) {
1865
+ if (line.startsWith("data: ")) {
1866
+ const data = line.slice(6);
1867
+ if (data === "[DONE]") continue;
1868
+ try {
1869
+ const parsed = JSON.parse(data);
1870
+ if (parsed.text) {
1871
+ assistantContent += parsed.text;
1872
+ setMessages((prev) => {
1873
+ const updated = [...prev];
1874
+ updated[updated.length - 1] = {
1875
+ role: "assistant",
1876
+ content: assistantContent
1877
+ };
1878
+ return updated;
1879
+ });
1880
+ }
1881
+ } catch {
1882
+ }
1883
+ }
1884
+ }
1885
+ }
1886
+ const finalMessages = [
1887
+ ...updatedMessages,
1888
+ { role: "assistant", content: assistantContent }
1889
+ ];
1890
+ scheduleSave(finalMessages);
1891
+ } catch (err) {
1892
+ const errorMsg = err instanceof Error ? err.message : "Chat failed";
1893
+ setMessages((prev) => [
1894
+ ...prev,
1895
+ { role: "assistant", content: `Error: ${errorMsg}` }
1896
+ ]);
1897
+ }
1898
+ setIsStreaming(false);
1899
+ },
1900
+ [messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
1901
+ );
1902
+ const clearChat = useCallback3(() => {
1903
+ setMessages([]);
1904
+ if (documentId) {
1905
+ saveChatHistory(apiUrl, userId.current, documentId, [], publication);
1906
+ }
1907
+ }, [apiUrl, documentId, publication]);
1908
+ return { messages, isStreaming, sendMessage, clearChat };
1909
+ }
1910
+
1911
+ // src/components/ChatPanel.tsx
1912
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1913
+ var SUGGESTIONS = [
1914
+ "What keywords am I missing?",
1915
+ "How do I optimize for AEO?",
1916
+ "Chat about primary and supporting keywords",
1917
+ "What semantically related terms should I include?"
1918
+ ];
1919
+ function LogoIcon() {
1920
+ return /* @__PURE__ */ jsxs5("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", children: [
1921
+ /* @__PURE__ */ jsx6("rect", { x: "1", y: "3", width: "4", height: "10", rx: "1", fill: MJH_GOLD, opacity: "1" }),
1922
+ /* @__PURE__ */ jsx6("rect", { x: "6", y: "1", width: "4", height: "14", rx: "1", fill: MJH_GOLD, opacity: "0.85" }),
1923
+ /* @__PURE__ */ jsx6("rect", { x: "11", y: "5", width: "4", height: "8", rx: "1", fill: MJH_GOLD, opacity: "0.6" })
1924
+ ] });
1925
+ }
1926
+ function ChatPanel({ text, publication, keywordPanelData }) {
1927
+ const { apiUrl } = useConfig();
1928
+ const { value } = useDocumentPane2();
1929
+ const documentId = value?._id || void 0;
1930
+ const { messages, isStreaming, sendMessage, clearChat } = useSEOChat(apiUrl, text, publication, keywordPanelData, documentId);
1931
+ const [input, setInput] = useState8("");
1932
+ const [inputFocused, setInputFocused] = useState8(false);
1933
+ const [hoveredSuggestion, setHoveredSuggestion] = useState8(null);
1934
+ const [clearHovered, setClearHovered] = useState8(false);
1935
+ const messagesEndRef = useRef7(null);
1936
+ useEffect6(() => {
1937
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
1938
+ }, [messages]);
1939
+ const handleSend = () => {
1940
+ const trimmed = input.trim();
1941
+ if (!trimmed || isStreaming) return;
1942
+ setInput("");
1943
+ sendMessage(trimmed);
1944
+ };
1945
+ const handleKeyDown = (e) => {
1946
+ if (e.key === "Enter" && !e.shiftKey) {
1947
+ e.preventDefault();
1948
+ handleSend();
1949
+ }
1950
+ };
1951
+ const showTypingBars = isStreaming && (messages.length === 0 || messages[messages.length - 1].role === "user" || messages[messages.length - 1].role === "assistant" && !messages[messages.length - 1].content);
1952
+ return /* @__PURE__ */ jsx6("div", { style: { position: "relative", flex: 1, minHeight: 0 }, children: /* @__PURE__ */ jsxs5("div", { style: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, display: "flex", flexDirection: "column" }, children: [
1953
+ /* @__PURE__ */ jsx6("div", { style: { flex: 1, overflowY: "auto", padding: 12, minHeight: 0 }, children: messages.length === 0 && !isStreaming ? /* @__PURE__ */ jsxs5("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
1954
+ /* @__PURE__ */ jsxs5("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }, children: [
1955
+ /* @__PURE__ */ jsx6(LogoIcon, {}),
1956
+ /* @__PURE__ */ jsx6("span", { style: { fontSize: 12, fontWeight: 600, color: "#6b7280" }, children: "Welcome to SEO Copilot! Ask anything about your content." })
1957
+ ] }),
1958
+ SUGGESTIONS.map((s, i) => /* @__PURE__ */ jsx6(
1959
+ "button",
1960
+ {
1961
+ onClick: () => sendMessage(s),
1962
+ onMouseEnter: () => setHoveredSuggestion(i),
1963
+ onMouseLeave: () => setHoveredSuggestion(null),
1964
+ style: {
1965
+ width: "100%",
1966
+ textAlign: "left",
1967
+ padding: "10px 14px",
1968
+ borderRadius: 12,
1969
+ fontSize: 12.5,
1970
+ color: "#475569",
1971
+ background: hoveredSuggestion === i ? USER_BLUE : "#ffffff",
1972
+ border: `1px solid ${hoveredSuggestion === i ? USER_BLUE_BORDER : "#f1f5f9"}`,
1973
+ boxShadow: "0 1px 2px rgba(0,0,0,0.03)",
1974
+ cursor: "pointer",
1975
+ transition: "all 200ms ease"
1976
+ },
1977
+ children: s
1978
+ },
1979
+ i
1980
+ ))
1981
+ ] }) : /* @__PURE__ */ jsxs5("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
1982
+ messages.map((msg, i) => {
1983
+ if (msg.role === "assistant" && !msg.content) return null;
1984
+ return /* @__PURE__ */ jsx6(
1985
+ "div",
1986
+ {
1987
+ style: {
1988
+ display: "flex",
1989
+ justifyContent: msg.role === "user" ? "flex-end" : "flex-start",
1990
+ animation: "fade-up 0.2s ease-out forwards"
1991
+ },
1992
+ children: /* @__PURE__ */ jsxs5(
1993
+ "div",
1994
+ {
1995
+ style: {
1996
+ maxWidth: "88%",
1997
+ padding: "10px 14px",
1998
+ fontSize: 12.5,
1999
+ lineHeight: 1.65,
2000
+ borderRadius: 18,
2001
+ ...msg.role === "user" ? {
2002
+ background: USER_BLUE,
2003
+ border: `1px solid ${USER_BLUE_BORDER}`,
2004
+ boxShadow: "0 1px 3px rgba(0,93,172,0.08)",
2005
+ borderBottomRightRadius: 6,
2006
+ color: "#1e293b"
2007
+ } : {
2008
+ background: "#ffffff",
2009
+ boxShadow: "0 1px 2px rgba(0,0,0,0.04)",
2010
+ borderBottomLeftRadius: 6,
2011
+ color: "#475569"
2012
+ }
2013
+ },
2014
+ children: [
2015
+ msg.role === "assistant" ? /* @__PURE__ */ jsx6("div", { className: "prose-chat", children: /* @__PURE__ */ jsx6(ReactMarkdown, { remarkPlugins: [remarkGfm], children: msg.content }) }) : /* @__PURE__ */ jsx6("span", { style: { whiteSpace: "pre-wrap" }, children: msg.content }),
2016
+ isStreaming && i === messages.length - 1 && msg.role === "assistant" && msg.content && /* @__PURE__ */ jsx6("span", { style: { display: "inline-flex", alignItems: "flex-end", gap: 2, height: 10, marginLeft: 4, verticalAlign: "middle" }, children: [1, 2, 3].map((n) => /* @__PURE__ */ jsx6(
2017
+ "span",
2018
+ {
2019
+ style: {
2020
+ width: 2,
2021
+ height: 6,
2022
+ borderRadius: 1,
2023
+ background: MJH_GOLD,
2024
+ animation: `bar-shift-${n} 1.4s ease-in-out infinite`
2025
+ }
2026
+ },
2027
+ n
2028
+ )) })
2029
+ ]
2030
+ }
2031
+ )
2032
+ },
2033
+ i
2034
+ );
2035
+ }),
2036
+ showTypingBars && /* @__PURE__ */ jsx6("div", { style: { display: "flex", justifyContent: "flex-start" }, children: /* @__PURE__ */ jsx6(
2037
+ "div",
2038
+ {
2039
+ style: {
2040
+ padding: 12,
2041
+ borderRadius: 16,
2042
+ borderBottomLeftRadius: 4,
2043
+ background: "#ffffff",
2044
+ boxShadow: "0 1px 3px rgba(0,0,0,0.06)"
2045
+ },
2046
+ children: /* @__PURE__ */ jsx6(LoadingBars, { size: "xs" })
2047
+ }
2048
+ ) }),
2049
+ /* @__PURE__ */ jsx6("div", { ref: messagesEndRef })
2050
+ ] }) }),
2051
+ /* @__PURE__ */ jsxs5(
2052
+ "div",
2053
+ {
2054
+ style: {
2055
+ display: "flex",
2056
+ gap: 8,
2057
+ padding: 12,
2058
+ borderTop: "1px solid #f3f4f6",
2059
+ background: "rgba(255,255,255,0.9)",
2060
+ backdropFilter: "blur(8px)",
2061
+ flexShrink: 0
2062
+ },
2063
+ children: [
2064
+ /* @__PURE__ */ jsx6(
2065
+ "input",
2066
+ {
2067
+ type: "text",
2068
+ value: input,
2069
+ onChange: (e) => setInput(e.target.value),
2070
+ onKeyDown: handleKeyDown,
2071
+ onFocus: () => setInputFocused(true),
2072
+ onBlur: () => setInputFocused(false),
2073
+ placeholder: "Ask about SEO...",
2074
+ disabled: isStreaming,
2075
+ style: {
2076
+ flex: 1,
2077
+ padding: "8px 12px",
2078
+ fontSize: 12,
2079
+ borderRadius: 12,
2080
+ border: `1px solid ${inputFocused ? MJH_BLUE : "#e5e7eb"}`,
2081
+ background: "#ffffff",
2082
+ boxShadow: inputFocused ? "0 0 0 3px rgba(0,93,172,0.1)" : "0 1px 2px rgba(0,0,0,0.04)",
2083
+ outline: "none",
2084
+ opacity: isStreaming ? 0.4 : 1,
2085
+ transition: "border-color 150ms, box-shadow 150ms"
2086
+ }
2087
+ }
2088
+ ),
2089
+ /* @__PURE__ */ jsx6(
2090
+ "button",
2091
+ {
2092
+ onClick: handleSend,
2093
+ disabled: isStreaming || !input.trim(),
2094
+ style: {
2095
+ padding: "8px 12px",
2096
+ borderRadius: 12,
2097
+ border: "none",
2098
+ color: "#ffffff",
2099
+ background: `linear-gradient(135deg, ${MJH_BLUE}, #004A8A)`,
2100
+ boxShadow: "0 2px 6px rgba(0,93,172,0.3)",
2101
+ cursor: isStreaming || !input.trim() ? "not-allowed" : "pointer",
2102
+ opacity: isStreaming || !input.trim() ? 0.4 : 1,
2103
+ transition: "all 150ms",
2104
+ display: "flex",
2105
+ alignItems: "center"
2106
+ },
2107
+ children: /* @__PURE__ */ jsx6("svg", { width: "16", height: "16", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx6("path", { d: "M3.105 2.289a.75.75 0 00-.826.95l1.414 4.925A1.5 1.5 0 005.135 9.25h6.115a.75.75 0 010 1.5H5.135a1.5 1.5 0 00-1.442 1.086l-1.414 4.926a.75.75 0 00.826.95 28.896 28.896 0 0015.293-7.154.75.75 0 000-1.115A28.897 28.897 0 003.105 2.289z" }) })
2108
+ }
2109
+ )
2110
+ ]
2111
+ }
2112
+ ),
2113
+ messages.length > 0 && /* @__PURE__ */ jsx6("div", { style: { display: "flex", justifyContent: "flex-end", padding: "0 12px 8px", flexShrink: 0 }, children: /* @__PURE__ */ jsxs5(
2114
+ "button",
2115
+ {
2116
+ onClick: clearChat,
2117
+ onMouseEnter: () => setClearHovered(true),
2118
+ onMouseLeave: () => setClearHovered(false),
2119
+ style: {
2120
+ background: "none",
2121
+ border: "none",
2122
+ fontSize: 10,
2123
+ color: clearHovered ? "#ef4444" : "#d1d5db",
2124
+ cursor: "pointer",
2125
+ display: "flex",
2126
+ alignItems: "center",
2127
+ gap: 4,
2128
+ transition: "color 150ms"
2129
+ },
2130
+ children: [
2131
+ /* @__PURE__ */ jsx6("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx6("path", { fillRule: "evenodd", d: "M8.75 1A2.75 2.75 0 006 3.75v.443c-.795.077-1.584.176-2.365.298a.75.75 0 10.23 1.482l.149-.022.841 10.518A2.75 2.75 0 007.596 19h4.807a2.75 2.75 0 002.742-2.53l.841-10.519.149.023a.75.75 0 00.23-1.482A41.03 41.03 0 0014 4.193V3.75A2.75 2.75 0 0011.25 1h-2.5zM10 4c.84 0 1.673.025 2.5.075V3.75c0-.69-.56-1.25-1.25-1.25h-2.5c-.69 0-1.25.56-1.25 1.25v.325C8.327 4.025 9.16 4 10 4zM8.58 7.72a.75.75 0 00-1.5.06l.3 7.5a.75.75 0 101.5-.06l-.3-7.5zm4.34.06a.75.75 0 10-1.5-.06l-.3 7.5a.75.75 0 101.5.06l.3-7.5z", clipRule: "evenodd" }) }),
2132
+ "Clear"
2133
+ ]
2134
+ }
2135
+ ) })
2136
+ ] }) });
2137
+ }
2138
+
2139
+ // src/components/SEOCopilotPanel.tsx
2140
+ import { Fragment as Fragment3, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
2141
+ function LogoIcon2() {
2142
+ return /* @__PURE__ */ jsxs6("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", children: [
2143
+ /* @__PURE__ */ jsx7("rect", { x: "1", y: "3", width: "4", height: "10", rx: "1", fill: MJH_GOLD, opacity: "1" }),
2144
+ /* @__PURE__ */ jsx7("rect", { x: "6", y: "1", width: "4", height: "14", rx: "1", fill: MJH_GOLD, opacity: "0.85" }),
2145
+ /* @__PURE__ */ jsx7("rect", { x: "11", y: "5", width: "4", height: "8", rx: "1", fill: MJH_GOLD, opacity: "0.6" })
2146
+ ] });
2147
+ }
2148
+ function PanelContent({ initialPublication, isFloating, isFullscreen, onToggleFloat, onToggleFullscreen, onClose, floatPos: _floatPos, onDragStart, seedKeywords, onSeedsChange, text, documentFields, onSelectPrimary, externalAnalysis }) {
2149
+ const publication = initialPublication;
2150
+ const [keywordsOpen, setKeywordsOpen] = useState9(true);
2151
+ const [chatOpen, setChatOpen] = useState9(true);
2152
+ const isLoading = externalAnalysis.isLoading;
2153
+ const keywordAnalysisState = externalAnalysis;
2154
+ const keywordPanelData = useMemo(() => {
2155
+ const { analysis } = keywordAnalysisState;
2156
+ if (!analysis) return void 0;
2157
+ return {
2158
+ primaryKeyword: { term: analysis.primaryKeyword.term, volume: analysis.primaryKeyword.volume },
2159
+ supportingKeywords: (analysis.supportingKeywords || []).map((kw) => ({ term: kw.term, volume: kw.volume })),
2160
+ missingKeywords: analysis.missingKeywords.map((kw) => ({ term: kw.term, volume: kw.volume })),
2161
+ aeoData: keywordAnalysisState.deepAnalysis?.aeo ? {
2162
+ questionHeadings: (keywordAnalysisState.deepAnalysis.aeo.questionHeadings || []).map((h) => ({
2163
+ suggestedHeading: h.suggestedHeading,
2164
+ rationale: h.rationale
2165
+ })),
2166
+ faqSuggestions: (keywordAnalysisState.deepAnalysis.aeo.faqSuggestions || []).map((f) => ({
2167
+ question: f.question,
2168
+ answer: f.answer
2169
+ }))
2170
+ } : void 0
2171
+ };
2172
+ }, [keywordAnalysisState.analysis, keywordAnalysisState.deepAnalysis]);
2173
+ const [splitPercent, setSplitPercent] = useState9(75);
2174
+ const containerRef = useRef8(null);
2175
+ const dragging = useRef8(false);
2176
+ const onMouseDown = useCallback4(() => {
2177
+ dragging.current = true;
2178
+ document.body.style.cursor = "row-resize";
2179
+ document.body.style.userSelect = "none";
2180
+ }, []);
2181
+ useEffect7(() => {
2182
+ const onMouseMove = (e) => {
2183
+ if (!dragging.current || !containerRef.current) return;
2184
+ const rect = containerRef.current.getBoundingClientRect();
2185
+ const pct = (e.clientY - rect.top) / rect.height * 100;
2186
+ setSplitPercent(Math.min(85, Math.max(15, pct)));
2187
+ };
2188
+ const onMouseUp = () => {
2189
+ dragging.current = false;
2190
+ document.body.style.cursor = "";
2191
+ document.body.style.userSelect = "";
2192
+ };
2193
+ window.addEventListener("mousemove", onMouseMove);
2194
+ window.addEventListener("mouseup", onMouseUp);
2195
+ return () => {
2196
+ window.removeEventListener("mousemove", onMouseMove);
2197
+ window.removeEventListener("mouseup", onMouseUp);
2198
+ };
2199
+ }, []);
2200
+ const headerCursor = isFloating ? "grab" : "default";
2201
+ return /* @__PURE__ */ jsxs6("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 }, children: [
2202
+ /* @__PURE__ */ jsx7("style", { dangerouslySetInnerHTML: { __html: INJECTED_CSS } }),
2203
+ /* @__PURE__ */ jsxs6(
2204
+ "div",
2205
+ {
2206
+ onMouseDown: isFloating ? onDragStart : void 0,
2207
+ style: {
2208
+ position: "relative",
2209
+ display: "flex",
2210
+ alignItems: "center",
2211
+ justifyContent: "space-between",
2212
+ padding: "14px 16px",
2213
+ background: "linear-gradient(180deg, #FFFFFF 0%, #FBFAF7 100%)",
2214
+ boxShadow: "0 1px 0 rgba(0,0,0,0.04)",
2215
+ zIndex: 10,
2216
+ cursor: headerCursor,
2217
+ userSelect: "none",
2218
+ flexShrink: 0
2219
+ },
2220
+ children: [
2221
+ /* @__PURE__ */ jsxs6("div", { style: { display: "flex", alignItems: "center", gap: 6 }, children: [
2222
+ /* @__PURE__ */ jsx7(LogoIcon2, {}),
2223
+ /* @__PURE__ */ jsxs6("span", { style: { fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }, children: [
2224
+ /* @__PURE__ */ jsx7("span", { style: { color: MJH_GOLD }, children: "SEO" }),
2225
+ /* @__PURE__ */ jsx7("span", { style: { color: MJH_SLATE }, children: " copilot" })
2226
+ ] })
2227
+ ] }),
2228
+ /* @__PURE__ */ jsxs6("div", { style: { display: "flex", alignItems: "center", gap: isFloating ? 4 : 6 }, children: [
2229
+ isFloating && onToggleFullscreen && /* @__PURE__ */ jsx7(
2230
+ "button",
2231
+ {
2232
+ onClick: (e) => {
2233
+ e.stopPropagation();
2234
+ onToggleFullscreen();
2235
+ },
2236
+ onMouseDown: (e) => e.stopPropagation(),
2237
+ style: {
2238
+ background: isFullscreen ? "rgba(230,192,27,0.15)" : "rgba(0,0,0,0.04)",
2239
+ border: "none",
2240
+ borderRadius: 6,
2241
+ cursor: "pointer",
2242
+ padding: "4px 8px",
2243
+ display: "flex",
2244
+ alignItems: "center",
2245
+ gap: 4,
2246
+ color: isFullscreen ? "#8B7310" : "#6b7280",
2247
+ fontSize: 10,
2248
+ fontWeight: 600,
2249
+ transition: "all 150ms"
2250
+ },
2251
+ children: isFullscreen ? /* @__PURE__ */ jsxs6(Fragment3, { children: [
2252
+ /* @__PURE__ */ jsx7("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx7("path", { d: "M3.28 2.22a.75.75 0 00-1.06 1.06L5.44 6.5H3.75a.75.75 0 000 1.5h4.5A.75.75 0 009 7.25v-4.5a.75.75 0 00-1.5 0v1.69L4.28 1.22a.75.75 0 00-1 1zM16.72 17.78a.75.75 0 001.06-1.06L14.56 13.5h1.69a.75.75 0 000-1.5h-4.5a.75.75 0 00-.75.75v4.5a.75.75 0 001.5 0v-1.69l3.22 3.22z" }) }),
2253
+ "Exit fullscreen"
2254
+ ] }) : /* @__PURE__ */ jsxs6(Fragment3, { children: [
2255
+ /* @__PURE__ */ jsx7("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx7("path", { d: "M13.28 7.78l3.22-3.22v1.69a.75.75 0 001.5 0v-4.5a.75.75 0 00-.75-.75h-4.5a.75.75 0 000 1.5h1.69l-3.22 3.22a.75.75 0 001.06 1.06zM2 17.25a.75.75 0 001.5 0v-1.69l3.22 3.22a.75.75 0 001.06-1.06L4.56 14.5h1.69a.75.75 0 000-1.5h-4.5a.75.75 0 00-.75.75v4.5z" }) }),
2256
+ "Fullscreen"
2257
+ ] })
2258
+ }
2259
+ ),
2260
+ isFloating && onToggleFloat && /* @__PURE__ */ jsxs6(
2261
+ "button",
2262
+ {
2263
+ onClick: (e) => {
2264
+ e.stopPropagation();
2265
+ onToggleFloat();
2266
+ },
2267
+ onMouseDown: (e) => e.stopPropagation(),
2268
+ style: {
2269
+ background: "rgba(0,93,172,0.08)",
2270
+ border: "none",
2271
+ borderRadius: 6,
2272
+ cursor: "pointer",
2273
+ padding: "4px 8px",
2274
+ display: "flex",
2275
+ alignItems: "center",
2276
+ gap: 4,
2277
+ color: MJH_BLUE,
2278
+ fontSize: 10,
2279
+ fontWeight: 600,
2280
+ transition: "all 150ms"
2281
+ },
2282
+ children: [
2283
+ /* @__PURE__ */ jsx7("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx7("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" }) }),
2284
+ "Dock"
2285
+ ]
2286
+ }
2287
+ ),
2288
+ !isFloating && onToggleFloat && /* @__PURE__ */ jsx7(
2289
+ "button",
2290
+ {
2291
+ onClick: (e) => {
2292
+ e.stopPropagation();
2293
+ onToggleFloat();
2294
+ },
2295
+ onMouseDown: (e) => e.stopPropagation(),
2296
+ style: {
2297
+ background: "none",
2298
+ border: "none",
2299
+ cursor: "pointer",
2300
+ padding: 2,
2301
+ display: "flex",
2302
+ alignItems: "center",
2303
+ color: "#9ca3af",
2304
+ transition: "color 150ms"
2305
+ },
2306
+ title: "Pop out",
2307
+ children: /* @__PURE__ */ jsxs6("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", children: [
2308
+ /* @__PURE__ */ jsx7("path", { d: "M4.25 5.5a.75.75 0 00-.75.75v8.5c0 .414.336.75.75.75h8.5a.75.75 0 00.75-.75v-4a.75.75 0 011.5 0v4A2.25 2.25 0 0112.75 17h-8.5A2.25 2.25 0 012 14.75v-8.5A2.25 2.25 0 014.25 4h5a.75.75 0 010 1.5h-5z" }),
2309
+ /* @__PURE__ */ jsx7("path", { d: "M6.194 12.753a.75.75 0 001.06.053L16.5 4.44v2.81a.75.75 0 001.5 0v-4.5a.75.75 0 00-.75-.75h-4.5a.75.75 0 000 1.5h2.553l-9.056 8.194a.75.75 0 00-.053 1.06z" })
2310
+ ] })
2311
+ }
2312
+ ),
2313
+ isLoading && /* @__PURE__ */ jsx7("div", { style: { width: 8, height: 8, borderRadius: "50%", background: MJH_GOLD, animation: "content-pulse 2s ease-in-out infinite" } }),
2314
+ onClose && /* @__PURE__ */ jsx7(
2315
+ "button",
2316
+ {
2317
+ onClick: (e) => {
2318
+ e.stopPropagation();
2319
+ onClose();
2320
+ },
2321
+ onMouseDown: (e) => e.stopPropagation(),
2322
+ style: {
2323
+ background: "none",
2324
+ border: "none",
2325
+ cursor: "pointer",
2326
+ padding: 2,
2327
+ display: "flex",
2328
+ alignItems: "center",
2329
+ color: "#9ca3af",
2330
+ transition: "color 150ms"
2331
+ },
2332
+ title: "Close",
2333
+ children: /* @__PURE__ */ jsx7("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx7("path", { d: "M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" }) })
2334
+ }
2335
+ )
2336
+ ] }),
2337
+ /* @__PURE__ */ jsx7("div", { style: {
2338
+ position: "absolute",
2339
+ bottom: 3,
2340
+ left: 38,
2341
+ fontSize: 9,
2342
+ color: "#b0b8c4",
2343
+ fontWeight: 400,
2344
+ fontStyle: "italic",
2345
+ letterSpacing: "0.02em"
2346
+ }, children: "More eyes on your expertise" })
2347
+ ]
2348
+ }
2349
+ ),
2350
+ /* @__PURE__ */ jsxs6("div", { ref: containerRef, style: { flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }, children: [
2351
+ /* @__PURE__ */ jsxs6("div", { style: { height: keywordsOpen ? chatOpen ? `${splitPercent}%` : "100%" : "auto", overflow: keywordsOpen ? "auto" : "hidden", flexShrink: keywordsOpen ? void 0 : 0 }, children: [
2352
+ /* @__PURE__ */ jsxs6(
2353
+ "button",
2354
+ {
2355
+ onClick: () => setKeywordsOpen(!keywordsOpen),
2356
+ 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" },
2357
+ children: [
2358
+ /* @__PURE__ */ jsxs6("span", { style: { display: "flex", alignItems: "center", gap: 6, flex: 1 }, children: [
2359
+ /* @__PURE__ */ jsx7("span", { style: { fontSize: 10, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", color: "#9ca3af" }, children: "Keywords & AEO Insights" }),
2360
+ (keywordAnalysisState.isLoading || keywordAnalysisState.isVolumesLoading || keywordAnalysisState.isDeepLoading) && /* @__PURE__ */ jsx7(LoadingBars, { size: "xs", color: "#9ca3af" })
2361
+ ] }),
2362
+ /* @__PURE__ */ jsx7("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "#9ca3af", style: { transform: keywordsOpen ? "rotate(0deg)" : "rotate(-90deg)", transition: "transform 200ms" }, children: /* @__PURE__ */ jsx7("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" }) })
2363
+ ]
2364
+ }
2365
+ ),
2366
+ /* @__PURE__ */ jsx7("div", { style: { display: keywordsOpen ? "block" : "none" }, children: /* @__PURE__ */ jsx7(
2367
+ KeywordPanel,
2368
+ {
2369
+ text,
2370
+ publication,
2371
+ seedKeywords,
2372
+ onSeedsChange,
2373
+ onSelectPrimary,
2374
+ documentFields,
2375
+ externalAnalysis: keywordAnalysisState
2376
+ }
2377
+ ) })
2378
+ ] }),
2379
+ keywordsOpen && chatOpen && /* @__PURE__ */ jsx7(
2380
+ "div",
2381
+ {
2382
+ onMouseDown,
2383
+ style: {
2384
+ height: 6,
2385
+ cursor: "row-resize",
2386
+ background: "linear-gradient(180deg, rgba(0,0,0,0.04) 0%, rgba(0,0,0,0.08) 50%, rgba(0,0,0,0.04) 100%)",
2387
+ display: "flex",
2388
+ alignItems: "center",
2389
+ justifyContent: "center",
2390
+ flexShrink: 0
2391
+ },
2392
+ children: /* @__PURE__ */ jsx7("div", { style: { width: 32, height: 2, borderRadius: 1, background: "#d1d5db" } })
2393
+ }
2394
+ ),
2395
+ /* @__PURE__ */ jsxs6("div", { style: {
2396
+ flex: chatOpen && !keywordsOpen ? 1 : void 0,
2397
+ height: chatOpen ? keywordsOpen ? `${100 - splitPercent}%` : void 0 : "auto",
2398
+ overflow: "hidden",
2399
+ display: "flex",
2400
+ flexDirection: "column",
2401
+ flexShrink: chatOpen ? void 0 : 0,
2402
+ minHeight: 0
2403
+ }, children: [
2404
+ /* @__PURE__ */ jsxs6(
2405
+ "button",
2406
+ {
2407
+ onClick: () => setChatOpen(!chatOpen),
2408
+ 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" },
2409
+ children: [
2410
+ /* @__PURE__ */ jsx7("span", { style: { fontSize: 10, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", color: "#9ca3af" }, children: "Chat" }),
2411
+ /* @__PURE__ */ jsx7("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "#9ca3af", style: { transform: chatOpen ? "rotate(0deg)" : "rotate(-90deg)", transition: "transform 200ms" }, children: /* @__PURE__ */ jsx7("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" }) })
2412
+ ]
2413
+ }
2414
+ ),
2415
+ /* @__PURE__ */ jsx7("div", { style: { flex: chatOpen ? 1 : 0, overflow: "hidden", display: chatOpen ? "flex" : "none", flexDirection: "column", minHeight: 0 }, children: /* @__PURE__ */ jsx7(ChatPanel, { text, publication, keywordPanelData }) })
2416
+ ] })
2417
+ ] })
2418
+ ] });
2419
+ }
2420
+ function SEOCopilotInner({ config, onClose }) {
2421
+ const [isFloating, setIsFloating] = useState9(false);
2422
+ const [isFullscreen, setIsFullscreen] = useState9(false);
2423
+ const [floatPos, setFloatPos] = useState9({ x: typeof window !== "undefined" ? window.innerWidth - 420 : 400, y: 80 });
2424
+ const [floatSize, setFloatSize] = useState9({ width: 380, height: typeof window !== "undefined" ? Math.round(window.innerHeight * 0.8) : 600 });
2425
+ const dragOffset = useRef8(null);
2426
+ const resizeStart = useRef8(null);
2427
+ const { text, isLoading: docLoading, documentFields, documentId } = useDocumentContent();
2428
+ const { apiUrl } = useConfig();
2429
+ const seedCacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
2430
+ const [seedKeywords, setSeedKeywordsRaw] = useState9(() => {
2431
+ try {
2432
+ const c = sessionStorage.getItem(seedCacheKey);
2433
+ if (c) return JSON.parse(c).seeds || [];
2434
+ } catch {
2435
+ }
2436
+ return [];
2437
+ });
2438
+ const setSeedKeywords = useCallback4((seeds) => {
2439
+ setSeedKeywordsRaw(seeds);
2440
+ try {
2441
+ const c = JSON.parse(sessionStorage.getItem(seedCacheKey) || "{}");
2442
+ sessionStorage.setItem(seedCacheKey, JSON.stringify({ ...c, seeds }));
2443
+ } catch {
2444
+ }
2445
+ }, [seedCacheKey]);
2446
+ const [selectedPrimary, setSelectedPrimary] = useState9();
2447
+ const keywordAnalysisState = useKeywordAnalysis(text, apiUrl, config.publication, seedKeywords, documentFields, selectedPrimary, documentId);
2448
+ const handleDragStart = useCallback4((e) => {
2449
+ dragOffset.current = {
2450
+ dx: e.clientX - floatPos.x,
2451
+ dy: e.clientY - floatPos.y
2452
+ };
2453
+ const onMouseMove = (ev) => {
2454
+ if (!dragOffset.current) return;
2455
+ setFloatPos({
2456
+ x: ev.clientX - dragOffset.current.dx,
2457
+ y: ev.clientY - dragOffset.current.dy
2458
+ });
2459
+ };
2460
+ const onMouseUp = () => {
2461
+ dragOffset.current = null;
2462
+ window.removeEventListener("mousemove", onMouseMove);
2463
+ window.removeEventListener("mouseup", onMouseUp);
2464
+ document.body.style.cursor = "";
2465
+ document.body.style.userSelect = "";
2466
+ };
2467
+ document.body.style.cursor = "grabbing";
2468
+ document.body.style.userSelect = "none";
2469
+ window.addEventListener("mousemove", onMouseMove);
2470
+ window.addEventListener("mouseup", onMouseUp);
2471
+ }, [floatPos]);
2472
+ const handleResizeStart = useCallback4((e) => {
2473
+ e.preventDefault();
2474
+ e.stopPropagation();
2475
+ resizeStart.current = { startX: e.clientX, startY: e.clientY, startW: floatSize.width, startH: floatSize.height };
2476
+ document.body.style.cursor = "nwse-resize";
2477
+ document.body.style.userSelect = "none";
2478
+ const onMouseMove = (ev) => {
2479
+ if (!resizeStart.current) return;
2480
+ const newW = Math.max(320, resizeStart.current.startW + (ev.clientX - resizeStart.current.startX));
2481
+ const newH = Math.max(300, resizeStart.current.startH + (ev.clientY - resizeStart.current.startY));
2482
+ setFloatSize({ width: newW, height: newH });
2483
+ };
2484
+ const onMouseUp = () => {
2485
+ resizeStart.current = null;
2486
+ document.body.style.cursor = "";
2487
+ document.body.style.userSelect = "";
2488
+ window.removeEventListener("mousemove", onMouseMove);
2489
+ window.removeEventListener("mouseup", onMouseUp);
2490
+ };
2491
+ window.addEventListener("mousemove", onMouseMove);
2492
+ window.addEventListener("mouseup", onMouseUp);
2493
+ }, [floatSize]);
2494
+ void docLoading;
2495
+ const panelContent = /* @__PURE__ */ jsx7(
2496
+ PanelContent,
2497
+ {
2498
+ initialPublication: config.publication,
2499
+ isFloating,
2500
+ isFullscreen,
2501
+ onToggleFloat: () => {
2502
+ setIsFloating((v) => !v);
2503
+ setIsFullscreen(false);
2504
+ },
2505
+ onToggleFullscreen: () => setIsFullscreen((v) => !v),
2506
+ onClose,
2507
+ floatPos,
2508
+ onDragStart: handleDragStart,
2509
+ seedKeywords,
2510
+ onSeedsChange: setSeedKeywords,
2511
+ text,
2512
+ documentFields,
2513
+ onSelectPrimary: setSelectedPrimary,
2514
+ externalAnalysis: {
2515
+ analysis: keywordAnalysisState.analysis,
2516
+ isLoading: keywordAnalysisState.isLoading,
2517
+ isVolumesLoading: keywordAnalysisState.isVolumesLoading,
2518
+ error: keywordAnalysisState.error,
2519
+ deepAnalysis: keywordAnalysisState.deepAnalysis,
2520
+ isDeepLoading: keywordAnalysisState.isDeepLoading,
2521
+ runDeepAnalysis: keywordAnalysisState.runDeepAnalysis,
2522
+ refreshVolumes: keywordAnalysisState.refreshVolumes,
2523
+ aeoContentChanged: keywordAnalysisState.aeoContentChanged
2524
+ }
2525
+ }
2526
+ );
2527
+ const floatingPanel = /* @__PURE__ */ jsxs6(
2528
+ "div",
2529
+ {
2530
+ style: {
2531
+ position: "fixed",
2532
+ left: isFullscreen ? 0 : floatPos.x,
2533
+ top: isFullscreen ? 0 : floatPos.y,
2534
+ width: isFullscreen ? "100vw" : floatSize.width,
2535
+ height: isFullscreen ? "100vh" : floatSize.height,
2536
+ zIndex: 2147483647,
2537
+ borderRadius: isFullscreen ? 0 : 12,
2538
+ overflow: "hidden",
2539
+ boxShadow: isFullscreen ? "none" : "0 8px 32px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.10)",
2540
+ border: isFullscreen ? "none" : "1px solid rgba(0,0,0,0.08)",
2541
+ background: "#FBFAF7"
2542
+ },
2543
+ children: [
2544
+ panelContent,
2545
+ !isFullscreen && /* @__PURE__ */ jsx7(
2546
+ "div",
2547
+ {
2548
+ onMouseDown: handleResizeStart,
2549
+ style: {
2550
+ position: "absolute",
2551
+ bottom: 0,
2552
+ right: 0,
2553
+ width: 16,
2554
+ height: 16,
2555
+ cursor: "nwse-resize",
2556
+ display: "flex",
2557
+ alignItems: "center",
2558
+ justifyContent: "center"
2559
+ },
2560
+ children: /* @__PURE__ */ jsxs6("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "#9ca3af", children: [
2561
+ /* @__PURE__ */ jsx7("path", { d: "M9 1v8H1", fill: "none", stroke: "#9ca3af", strokeWidth: "1.5", strokeLinecap: "round" }),
2562
+ /* @__PURE__ */ jsx7("path", { d: "M9 5v4H5", fill: "none", stroke: "#9ca3af", strokeWidth: "1.5", strokeLinecap: "round" })
2563
+ ] })
2564
+ }
2565
+ )
2566
+ ]
2567
+ }
2568
+ );
2569
+ if (isFloating) {
2570
+ return /* @__PURE__ */ jsxs6(Fragment3, { children: [
2571
+ /* @__PURE__ */ jsx7("div", { style: { height: "100%", background: "#FBFAF7", display: "flex", alignItems: "center", justifyContent: "center" }, children: /* @__PURE__ */ jsx7("span", { style: { fontSize: 12, color: "#9ca3af" }, children: "SEO Copilot is floating" }) }),
2572
+ typeof document !== "undefined" && createPortal(floatingPanel, document.body)
2573
+ ] });
2574
+ }
2575
+ return /* @__PURE__ */ jsx7("div", { style: { height: "100%", background: "#FBFAF7", position: "relative", zIndex: 1 }, children: panelContent });
2576
+ }
2577
+ function SEOCopilotPanel({ config, onClose }) {
2578
+ return /* @__PURE__ */ jsx7(
2579
+ Suspense,
2580
+ {
2581
+ fallback: /* @__PURE__ */ jsxs6("div", { style: { padding: 16, display: "flex", alignItems: "center", gap: 12 }, children: [
2582
+ /* @__PURE__ */ jsx7(LoadingBars, {}),
2583
+ /* @__PURE__ */ jsx7("span", { style: { fontSize: 12, color: "#9ca3af" }, children: "Loading SEO Copilot..." })
2584
+ ] }),
2585
+ children: /* @__PURE__ */ jsx7(ConfigProvider, { config, children: /* @__PURE__ */ jsx7(SEOCopilotInner, { config, onClose }) })
2586
+ }
2587
+ );
2588
+ }
2589
+ function LoadingBars({ size = "sm", color = MJH_GOLD }) {
2590
+ const barWidth = size === "xs" ? 4 : 6;
2591
+ const containerHeight = size === "xs" ? 10 : 14;
2592
+ return /* @__PURE__ */ jsx7("div", { style: { display: "inline-flex", alignItems: "flex-end", gap: 2, height: containerHeight }, children: [1, 2, 3].map((i) => /* @__PURE__ */ jsx7(
2593
+ "div",
2594
+ {
2595
+ style: {
2596
+ width: barWidth,
2597
+ height: 8,
2598
+ borderRadius: 2,
2599
+ background: color,
2600
+ animation: `bar-shift-${i} 1.4s ease-in-out infinite`
2601
+ }
2602
+ },
2603
+ i
2604
+ )) });
2605
+ }
2606
+
2607
+ // src/inspector.ts
2608
+ function SEOIcon() {
2609
+ return createElement(
2610
+ "svg",
2611
+ { viewBox: "0 0 25 25", width: "1em", height: "1em", fill: "none" },
2612
+ createElement("circle", { cx: "12.5", cy: "12.5", r: "11.5", fill: "#E6C01B" }),
2613
+ createElement("text", {
2614
+ x: "12.5",
2615
+ y: "7.5",
2616
+ textAnchor: "middle",
2617
+ dominantBaseline: "central",
2618
+ fill: "white",
2619
+ fontSize: "7",
2620
+ fontWeight: "900",
2621
+ fontFamily: "Arial Black, Impact, sans-serif"
2622
+ }, "S"),
2623
+ createElement("text", {
2624
+ x: "12.5",
2625
+ y: "12.8",
2626
+ textAnchor: "middle",
2627
+ dominantBaseline: "central",
2628
+ fill: "white",
2629
+ fontSize: "7",
2630
+ fontWeight: "900",
2631
+ fontFamily: "Arial Black, Impact, sans-serif"
2632
+ }, "E"),
2633
+ createElement("text", {
2634
+ x: "12.5",
2635
+ y: "18",
2636
+ textAnchor: "middle",
2637
+ dominantBaseline: "central",
2638
+ fill: "white",
2639
+ fontSize: "7",
2640
+ fontWeight: "900",
2641
+ fontFamily: "Arial Black, Impact, sans-serif"
2642
+ }, "O")
2643
+ );
2644
+ }
2645
+ function seoCopilotInspector(config) {
2646
+ return {
2647
+ name: "seo-copilot",
2648
+ useMenuItem: () => ({
2649
+ title: "SEO Copilot",
2650
+ icon: SEOIcon,
2651
+ showAsAction: true
2652
+ }),
2653
+ component: function SEOCopilotInspector(props) {
2654
+ return createElement(SEOCopilotPanel, { ...props, config });
2655
+ }
2656
+ };
2657
+ }
2658
+
2659
+ // src/index.ts
2660
+ var seoCopilot = definePlugin((config) => ({
2661
+ name: "seo-copilot",
2662
+ document: {
2663
+ inspectors: (prev) => {
2664
+ return [...prev, seoCopilotInspector(config)];
2665
+ }
2666
+ }
2667
+ }));
2668
+ export {
2669
+ seoCopilot
2670
+ };
2671
+ //# sourceMappingURL=index.mjs.map