import React, { useState, useCallback } from "react"; import { Stack, Card, Flex, Text, Button } from "@sanity/ui"; import { SparklesIcon } from "@sanity/icons"; import { useFormValue } from "sanity"; import { getPluginConfig } from "../config"; import { generateSEOContent } from "../utils/aiGenerate"; import { resolveBodyContent, getBodyFieldPaths } from "../utils/resolveBodyContent"; /* eslint-disable @typescript-eslint/no-explicit-any */ interface Props { value: Record | undefined; onChange: (keywords: string[]) => void; } export default function AIKeywordsSection({ value, onChange }: Props) { const config = getPluginConfig(); const [loading, setLoading] = useState(false); const [suggestions, setSuggestions] = useState([]); const [error, setError] = useState(null); const docValue = useFormValue([]); const bodyFieldPaths = getBodyFieldPaths(config.bodyFields, config.bodyField); const bodyText = resolveBodyContent(docValue, bodyFieldPaths); const focusKeyword = value?.focusKeyword || ""; const existing: string[] = value?.seoKeywords || []; const handleSuggest = useCallback(async () => { if (!config.aiFeature) return; setLoading(true); setError(null); try { const result = await generateSEOContent("keywords", bodyText, focusKeyword, config.aiFeature); const parsed = result .split(",") .map((k: string) => k.trim()) .filter(Boolean); setSuggestions(parsed); } catch (err: unknown) { setError(err instanceof Error ? err.message : "Keyword generation failed"); } finally { setLoading(false); } }, [config.aiFeature, bodyText, focusKeyword]); const addKeyword = (kw: string) => { if (!existing.includes(kw)) onChange([...existing, kw]); setSuggestions((prev) => prev.filter((s) => s !== kw)); }; if (!config.aiFeature) return null; return ( AI Keyword Suggestions ))} )} ); }