import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { Button } from "../../components/ui/button";
import { Search } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { toast } from "sonner";
export function SEOInfo() {
    const [seoData, setSeoData] = useState({});
    const [isAnalyzing, setIsAnalyzing] = useState(false);
    const editContext = useEditContext();
    const runSEOAnalysis = async () => {
        if (!editContext) {
            console.error("No edit context available");
            return;
        }
        setIsAnalyzing(true);
        try {
            // Get current page content for analysis
            const item = editContext.item || editContext.page?.item;
            console.log("Starting SEO Analysis...", { item });
            // Extract title and description from page fields if available
            const titleField = item?.fields?.find((f) => f.name?.toLowerCase().includes("title"));
            const descriptionField = item?.fields?.find((f) => f.name?.toLowerCase().includes("description") ||
                f.name?.toLowerCase().includes("summary"));
            // Update SEO data immediately with current content (this makes the button responsive)
            const currentTitle = titleField?.value || item?.name || "";
            const currentDescription = descriptionField?.value || "";
            const currentUrl = item?.path || "";
            setSeoData({
                title: currentTitle,
                description: currentDescription,
                keywords: [], // Will be populated by AI analysis
                url: currentUrl,
                lastAnalyzed: new Date(),
            });
            console.log("Updated SEO data with current content:", {
                title: currentTitle,
                description: currentDescription,
                url: currentUrl,
            });
            // Show immediate feedback
            toast.info("Analyzing current page content...");
            // Try to send AI analysis request
            const aiServiceUrl = editContext.configuration.services.aiService.endpoint;
            console.log("AI Service URL:", aiServiceUrl);
            if (!aiServiceUrl) {
                throw new Error("AI service URL not configured");
            }
            // Prepare SEO optimization prompt in correct message format
            const seoPrompt = `Analyze the current page for SEO optimization and provide specific recommendations.

Current page details:
- Page: ${item?.name || "Unknown"}
- Path: ${item?.path || "Unknown"}  
- Title: ${currentTitle || "No title found"}
- Description: ${currentDescription || "No description found"}

Please analyze and provide:
1. Title optimization suggestions (should be 50-60 characters)
2. Meta description recommendations (120-155 characters)
3. Keyword analysis and suggestions
4. Content structure improvements
5. Overall SEO recommendations

Focus on actionable insights for improving search engine visibility.`;
            // Format as proper message for AI service
            const messages = [
                {
                    id: Date.now(),
                    content: seoPrompt,
                    role: "user",
                    name: "user",
                },
            ];
            // Send to AI service using correct format
            const response = await fetch(aiServiceUrl, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    profileId: "Editor", // Use default editor profile
                    messages: messages,
                    selection: editContext.selection || [],
                    addSelectedComponents: true,
                    selectedText: null,
                    model: null, // Let AI service use default model
                    sessionId: null,
                    itemid: editContext.currentItemDescriptor?.id,
                    language: editContext.currentItemDescriptor?.language,
                    version: editContext.currentItemDescriptor?.version,
                }),
            });
            console.log("AI Service Response:", response.status, response.statusText);
            if (response.ok) {
                // Handle streaming response like the AI terminal does
                if (response.body) {
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = "";
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done)
                            break;
                        buffer += decoder.decode(value, { stream: true });
                        const lines = buffer.split("\n");
                        if (lines.length > 0) {
                            buffer = lines.pop() || "";
                            for (let line of lines) {
                                if (line.trim() === "")
                                    continue;
                                try {
                                    const jsonData = JSON.parse(line);
                                    console.log("AI Response chunk:", jsonData);
                                    // The AI response contains messages - this will show up in the comments panel
                                    if (jsonData.messages && jsonData.messages.length > 0) {
                                        // Final response received
                                        console.log("Final AI response:", jsonData);
                                    }
                                }
                                catch (e) {
                                    console.error("Error parsing AI response line:", line, e);
                                }
                            }
                        }
                    }
                    // Process any remaining buffer content
                    if (buffer.trim() !== "") {
                        try {
                            const jsonData = JSON.parse(buffer);
                            console.log("Final AI buffer:", jsonData);
                        }
                        catch (e) {
                            console.error("Error parsing final buffer:", e);
                        }
                    }
                }
                // Show success message
                toast.success("AI analysis completed. Check the Comments panel for SEO recommendations.");
            }
            else {
                const errorText = await response.text();
                throw new Error(`AI service responded with ${response.status}: ${errorText}`);
            }
        }
        catch (error) {
            console.error("SEO analysis failed:", error);
            toast.warning("Current page data extracted. AI analysis unavailable.");
        }
        finally {
            setIsAnalyzing(false);
        }
    };
    return (_jsxs("div", { className: "space-y-4 p-4", children: [_jsxs(Button, { size: "sm", onClick: runSEOAnalysis, disabled: isAnalyzing, className: "w-full bg-green-600 text-white hover:bg-green-700", children: [_jsx(Search, { className: "mr-2 h-4 w-4" }), "Run SEO Analysis"] }), _jsx("div", { className: "my-4 border-t border-gray-200" }), _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Page Title" }), _jsx("div", { className: "rounded bg-gray-50 p-2 text-sm text-gray-600", children: seoData.title || "No title detected" }), seoData.title && (_jsxs("div", { className: "mt-1 text-xs text-gray-500", children: ["Length: ", seoData.title.length, "/60 characters"] }))] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Meta Description" }), _jsx("div", { className: "rounded bg-gray-50 p-2 text-sm text-gray-600", children: seoData.description || "No description detected" }), seoData.description && (_jsxs("div", { className: "mt-1 text-xs text-gray-500", children: ["Length: ", seoData.description.length, "/155 characters"] }))] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Keywords" }), _jsx("div", { className: "rounded bg-gray-50 p-2 text-sm text-gray-600", children: seoData.keywords && seoData.keywords.length > 0
                                    ? seoData.keywords.join(", ")
                                    : "No keywords detected" })] }), seoData.lastAnalyzed && (_jsxs("div", { className: "border-t pt-2 text-xs text-gray-500", children: ["Last analyzed: ", seoData.lastAnalyzed.toLocaleString()] }))] })] }));
}
//# sourceMappingURL=SEOInfo.js.map