"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useCallback, startTransition, useRef, } from "react";
import { flushSync } from "react-dom";
import { Loader2, RotateCcw, History, ArrowRight, X, } from "lucide-react";
import { useEditContext } from "../editor/client/editContext";
import { loadAiProfiles } from "../editor/services/aiService";
import { closeAgent, getAgentsGrouped, } from "../editor/services/agentService";
import { AgentTerminal } from "../editor/ai/AgentTerminal";
import { ParheliaIconWhite } from "../editor/ui/ParheliaIconWhite";
import { cn } from "../lib/utils";
import { Button } from "../components/ui/button";
import { getSamplePrompts } from "../editor/services/systemService";
const SUGGESTED_PROMPTS = [
    {
        title: "Draft a blog post",
        description: "Write a 500-word post about digital marketing trends.",
        prompt: "Can you help me draft a 500-word blog post about the latest trends in digital marketing for 2025?",
    },
    {
        title: "Analyze my page",
        description: "Give me feedback on the SEO of my current page.",
        prompt: "Please analyze my current page and give me feedback on how I can improve its SEO and readability.",
    },
    {
        title: "Generate ideas",
        description: "Suggest 5 creative topics for my next newsletter.",
        prompt: "Suggest 5 creative and engaging topics for my next monthly customer newsletter.",
    },
    {
        title: "Fix tone of voice",
        description: "Make this text sound more professional and welcoming.",
        prompt: "I have some text that I want to sound more professional and welcoming. Can you help me rewrite it?",
    },
];
export const ParheliaAssistantChat = ({ className, externalAgent, }) => {
    const editContext = useEditContext();
    const [profile, setProfile] = useState(null);
    const [profiles, setProfiles] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [agent, setAgent] = useState(null);
    const [agentKey, setAgentKey] = useState(0); // Force re-render of AgentTerminal
    const [isTerminalVisible, setIsTerminalVisible] = useState(false);
    const [inputValue, setInputValue] = useState("");
    const [recentAgents, setRecentAgents] = useState([]);
    const [initialPrompt, setInitialPrompt] = useState(undefined);
    const [samplePrompts, setSamplePrompts] = useState(SUGGESTED_PROMPTS);
    const inputRef = useRef(null);
    // Create a new agent
    const createNewAgent = useCallback((selectedProfile) => {
        const agentDisplayName = selectedProfile.agentName || "Parhelia";
        const agentId = crypto.randomUUID();
        const newAgent = {
            status: "new",
            id: agentId,
            name: agentDisplayName,
            updatedDate: new Date().toISOString(),
            userId: "",
            profileId: selectedProfile.id,
            profileName: selectedProfile.name,
        };
        setAgent(newAgent);
        return newAgent;
    }, []);
    // Function to load profiles and recent agents
    const loadData = useCallback(async () => {
        try {
            setIsLoading(true);
            // Fetch sample prompts
            getSamplePrompts().then((res) => {
                if (res.data && res.data.length > 0) {
                    setSamplePrompts(res.data);
                }
            });
            const profileList = await loadAiProfiles();
            if (!profileList || profileList.length === 0) {
                setIsLoading(false);
                return;
            }
            // Try to find Parhelia profile with multiple strategies
            let assistantProfile;
            // Strategy 1: Look for exact ID match
            assistantProfile = profileList.find((p) => p.id === "7d45ab97-f253-4915-8b32-f9e8c762c5e9");
            // Strategy 2: Look for exact name match (case-insensitive)
            if (!assistantProfile) {
                assistantProfile = profileList.find((p) => p.name.toLowerCase() === "parhelia");
            }
            // Strategy 3: Look for profile containing "parhelia" in name or displayTitle
            if (!assistantProfile) {
                assistantProfile = profileList.find((p) => p.name.toLowerCase().includes("parhelia") ||
                    p.displayTitle?.toLowerCase().includes("parhelia"));
            }
            // Strategy 4: Fallback to first available profile
            const selectedProfile = assistantProfile || profileList[0];
            if (selectedProfile) {
                setProfile(selectedProfile);
                setProfiles(profileList);
                // Fetch recent agents for this profile
                try {
                    const response = await getAgentsGrouped();
                    const allAgents = [...response.activeAgents];
                    response.closedAgentsByProfile.forEach((group) => {
                        allAgents.push(...group.agents);
                    });
                    const parheliaAgents = allAgents.filter((a) => a.profileId === selectedProfile.id);
                    setRecentAgents(parheliaAgents.slice(0, 5));
                    // Set current agent to the latest one if it exists
                    const latestAgent = parheliaAgents[0];
                    if (latestAgent) {
                        setAgent(latestAgent);
                    }
                    else {
                        createNewAgent(selectedProfile);
                    }
                }
                catch (err) {
                    console.error("Failed to load recent agents:", err);
                    createNewAgent(selectedProfile);
                }
            }
            else {
                console.error("ParheliaAssistantChat: Could not select a profile from the available profiles.");
            }
        }
        catch (err) {
            console.error("Failed to load AI profile:", err);
        }
        finally {
            setIsLoading(false);
        }
    }, [createNewAgent]);
    // Load AI profiles and data on mount
    useEffect(() => {
        loadData();
    }, [loadData]);
    // Listen for agent profile changes via websocket
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const removeListener = editContext.addSocketMessageListener((message) => {
            if (message.type === "agent-profiles-changed") {
                loadData();
            }
        });
        return () => {
            removeListener();
        };
    }, [editContext?.addSocketMessageListener, loadData]);
    // Handle external agent selection
    useEffect(() => {
        if (externalAgent) {
            setAgent(externalAgent);
            setAgentKey((prev) => prev + 1);
            setInitialPrompt(undefined);
            setIsTerminalVisible(true);
        }
    }, [externalAgent]);
    // Handle revealing the terminal
    const handleRevealTerminal = useCallback(() => {
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    setIsTerminalVisible(true);
                });
            });
        }
        else {
            startTransition(() => {
                setIsTerminalVisible(true);
            });
        }
    }, []);
    // Handle starting a conversation with a prompt
    const handleStartWithPrompt = useCallback((prompt) => {
        if (!profile)
            return;
        const performUpdate = () => {
            // Clear any previous state first
            setInitialPrompt(undefined);
            // Always start a new chat for a new prompt
            createNewAgent(profile);
            setInitialPrompt(prompt);
            setAgentKey((prev) => prev + 1);
            setIsTerminalVisible(true);
        };
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    performUpdate();
                });
            });
        }
        else {
            performUpdate();
        }
    }, [profile, createNewAgent]);
    // Handle submit from smart input
    const handleSubmitInput = (e) => {
        e?.preventDefault();
        if (!inputValue.trim())
            return;
        handleStartWithPrompt(inputValue);
        setInputValue("");
    };
    // Handle start over
    const handleStartOver = useCallback(async () => {
        if (!profile || !agent)
            return;
        try {
            // Close the current agent first
            await closeAgent(agent.id);
        }
        catch (error) {
            console.error("Failed to close agent:", error);
        }
        const performUpdate = () => {
            // Create new agent and force re-render
            createNewAgent(profile);
            setAgentKey((prev) => prev + 1);
            setInitialPrompt(undefined);
        };
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    performUpdate();
                });
            });
        }
        else {
            performUpdate();
        }
    }, [profile, agent, createNewAgent]);
    // Handle agent updates from AgentTerminal (e.g., name changes)
    const handleAgentUpdate = useCallback((updates) => {
        setAgent((prev) => (prev ? { ...prev, ...updates } : prev));
    }, []);
    // Handle close
    const handleClose = useCallback(async () => {
        const performUpdate = () => {
            setIsTerminalVisible(false);
            setInitialPrompt(undefined);
            // Refresh history
            loadData();
        };
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    performUpdate();
                });
            });
        }
        else {
            performUpdate();
        }
    }, [loadData]);
    if (isLoading) {
        return (_jsx("div", { className: cn("flex items-center justify-center rounded-2xl border border-white/10 bg-white/3 p-12 shadow-xl", className), children: _jsx(Loader2, { className: "h-6 w-6 animate-spin text-purple-400" }) }));
    }
    if (!agent || !profile) {
        return (_jsx("div", { className: cn("flex items-center justify-center rounded-2xl border border-white/10 bg-white/3 p-12 shadow-xl", className), children: _jsx("p", { className: "text-sm text-slate-400", children: "Assistant unavailable. Please try again later." }) }));
    }
    return (_jsxs("div", { className: cn("flex flex-col overflow-hidden transition-all duration-300", !isTerminalVisible ? "rounded-2xl" : "rounded-xl shadow-2xl", className), style: { viewTransitionName: "assistant-chat-container" }, children: [!isTerminalVisible && (_jsxs("div", { className: "flex flex-col gap-8", children: [_jsx("div", { className: "group relative", style: { viewTransitionName: "assistant-chat-box" }, children: _jsxs("form", { onSubmit: handleSubmitInput, className: "relative flex items-center", children: [_jsx("div", { className: "absolute left-5", children: _jsx(ParheliaIconWhite, { size: 24 }) }), _jsx("input", { ref: inputRef, type: "text", placeholder: "Ask Parhelia anything...", value: inputValue, onChange: (e) => setInputValue(e.target.value), style: { viewTransitionName: "assistant-chat-input" }, className: "h-16 w-full rounded-2xl border border-white/10 bg-white/5 pr-16 pl-14 text-lg text-white shadow-2xl transition-all duration-300 placeholder:text-slate-500 focus:border-purple-500/40 focus:bg-white/8 focus:shadow-[0_0_30px_-5px_rgba(168,85,247,0.3)] focus:outline-none" }), _jsx("button", { type: "submit", disabled: !inputValue.trim(), className: "absolute right-3 flex h-10 w-10 items-center justify-center rounded-xl bg-purple-600 text-white shadow-lg transition-colors hover:bg-purple-500 disabled:bg-white/5 disabled:text-slate-600", children: _jsx(ArrowRight, { className: "h-5 w-5", strokeWidth: 2 }) })] }) }), _jsx("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: samplePrompts.map((item, idx) => (_jsxs("button", { onClick: () => handleStartWithPrompt(item.prompt), className: "group flex flex-col items-start rounded-xl border border-white/10 bg-white/3 p-5 text-left transition-all hover:bg-white/[0.07]", children: [_jsx("span", { className: "text-sm font-semibold text-slate-200 transition-colors group-hover:text-purple-400", children: item.title }), _jsx("span", { className: "mt-1 line-clamp-1 text-xs text-slate-500", children: item.description })] }, idx))) }), recentAgents.length > 0 && (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsxs("div", { className: "flex items-center gap-2 px-1 text-[10px] font-bold tracking-[0.2em] text-slate-500 uppercase", children: [_jsx(History, { className: "h-3 w-3" }), "Recent Parhelia Conversations"] }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [recentAgents.slice(0, 3).map((ra) => (_jsx("button", { onClick: () => {
                                            setAgent(ra);
                                            setIsTerminalVisible(true);
                                            setAgentKey((prev) => prev + 1);
                                        }, className: "max-w-[200px] truncate overflow-hidden rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs whitespace-nowrap text-slate-400 transition-all hover:border-purple-500/30 hover:bg-white/10", children: ra.name }, ra.id))), recentAgents.length > 3 && (_jsx("button", { onClick: () => {
                                            editContext?.switchWorkspace("agents");
                                        }, className: "rounded-full px-3 py-1.5 text-xs font-medium text-purple-400 transition-colors hover:text-purple-300", children: "View All Agents" }))] })] }))] })), isTerminalVisible && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center justify-between border-b border-white/10 bg-white/5 px-5 py-3.5", style: { viewTransitionName: "assistant-chat-box" }, children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-3", children: [_jsx("div", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-white/5 bg-white/5 shadow-inner", children: _jsx(ParheliaIconWhite, { size: 22 }) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("span", { className: "truncate text-[10px] font-bold tracking-[0.2em] text-purple-400/80 uppercase", children: agent.description || "Parhelia AI" }), _jsx("span", { className: "text-sm font-semibold tracking-tight text-slate-100", children: agent.name || profile.agentName || "Assistant" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs(Button, { variant: "ghost", size: "sm", onClick: handleStartOver, className: "h-9 gap-2 rounded-xl px-4 text-xs font-medium text-slate-400 transition-all hover:bg-white/10 hover:text-white", children: [_jsx(RotateCcw, { className: "h-4 w-4", strokeWidth: 1.5 }), "New Chat"] }), _jsx("div", { className: "mx-1 h-5 w-px bg-white/10" }), _jsx(Button, { variant: "ghost", size: "sm", onClick: handleClose, className: "group h-9 w-9 rounded-xl p-0 text-slate-500 transition-all hover:bg-white/10 hover:text-slate-200", "aria-label": "Close", children: _jsx(X, { className: "h-4 w-4 transition-transform duration-300 group-hover:rotate-90", strokeWidth: 2 }) })] })] }), _jsx("div", { className: "flex-1 overflow-hidden bg-slate-50/95", children: _jsx("div", { className: "animate-view-slide-in h-[650px]", children: _jsx(AgentTerminal, { agentStub: agent, initialMetadata: {
                                    profile: profile.name,
                                    additionalData: {
                                        profileId: profile.id,
                                        profileName: profile.name,
                                        initialPrompt: initialPrompt,
                                    },
                                }, profiles: profiles, isActive: true, compact: true, hideContext: true, hideBottomControls: true, hideGreeting: true, className: "h-full", initialPrompt: initialPrompt, onAgentUpdate: handleAgentUpdate }) }, agentKey) })] }))] }));
};
//# sourceMappingURL=ParheliaAssistantChat.js.map