import { jsx as _jsx } from "react/jsx-runtime";
import React, { useState, useEffect } from "react";
import { AgentTerminal } from "../ai/AgentTerminal";
import { useEditContext } from "../client/editContext";
import { loadAiProfiles } from "../services/aiService";
import { AgentProfileSelector } from "../ai/AgentProfileSelector";
/**
 * ParheliaView - A minimalistic, focused view for a single agent terminal
 * This view provides a distraction-free interface with just the agent terminal centered on screen
 */
export function ParheliaView() {
    const editContext = useEditContext();
    const [agent, setAgent] = useState(null);
    const [initialMetadata, setInitialMetadata] = useState(undefined);
    const [availableProfiles, setAvailableProfiles] = useState([]);
    const [loadingProfiles, setLoadingProfiles] = useState(false);
    // Function to load profiles
    const reloadProfiles = React.useCallback(async () => {
        try {
            setLoadingProfiles(true);
            const profiles = await loadAiProfiles(editContext?.currentItemDescriptor);
            setAvailableProfiles(profiles || []);
        }
        catch (e) {
            console.error("Failed to load AI profiles", e);
        }
        finally {
            setLoadingProfiles(false);
        }
    }, [editContext?.currentItemDescriptor]);
    // Load available profiles
    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                setLoadingProfiles(true);
                const profiles = await loadAiProfiles(editContext?.currentItemDescriptor);
                if (cancelled)
                    return;
                setAvailableProfiles(profiles || []);
            }
            catch (e) {
                console.error("Failed to load AI profiles", e);
            }
            finally {
                if (!cancelled)
                    setLoadingProfiles(false);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [editContext?.currentItemDescriptor?.id]);
    // Listen for agent profile changes via websocket
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const removeListener = editContext.addSocketMessageListener((message) => {
            if (message.type === "agent-profiles-changed") {
                reloadProfiles();
            }
        });
        return () => {
            removeListener();
        };
    }, [editContext?.addSocketMessageListener, reloadProfiles]);
    // Listen for external requests to add a new agent
    useEffect(() => {
        const handleAddNewAgent = (ev) => {
            let metadata = undefined;
            try {
                const ce = ev;
                metadata = (ce.detail && ce.detail.metadata);
            }
            catch { }
            // Create a new agent
            const newAgent = {
                status: "new",
                id: crypto.randomUUID(),
                name: `New Agent`,
                updatedDate: new Date().toISOString(),
                userId: "",
            };
            setAgent(newAgent);
            setInitialMetadata(metadata);
            // Focus the prompt after the agent mounts
            setTimeout(() => {
                try {
                    window.dispatchEvent(new CustomEvent("editor:focusAgentPrompt"));
                }
                catch { }
            }, 60);
        };
        window.addEventListener("editor:addNewAgent", handleAddNewAgent);
        return () => window.removeEventListener("editor:addNewAgent", handleAddNewAgent);
    }, []);
    // Listen for external requests to open an existing agent
    useEffect(() => {
        const handleOpenAgent = (ev) => {
            try {
                const ce = ev;
                const agentId = (ce.detail && ce.detail.agentId);
                if (!agentId)
                    return;
                // Load the agent
                const loadedAgent = {
                    id: agentId,
                    name: "Loading...",
                    status: "running",
                    userId: "",
                    updatedDate: new Date().toISOString(),
                };
                setAgent(loadedAgent);
            }
            catch (error) {
                console.error("Error opening agent:", error);
            }
        };
        window.addEventListener("editor:openAgent", handleOpenAgent);
        return () => window.removeEventListener("editor:openAgent", handleOpenAgent);
    }, []);
    const handleSelectProfile = (profileId) => {
        try {
            const selected = availableProfiles.find((p) => p.id === profileId);
            // Build initial metadata with preconfigured todos if available
            const additionalData = selected
                ? {
                    profileId: selected.id,
                    profileName: selected.name,
                }
                : {};
            // Add preconfigured todos as todoList if the profile has them
            const preconfiguredTodos = selected?.preconfiguredTodos;
            if (preconfiguredTodos && preconfiguredTodos.length > 0) {
                additionalData.todoList = {
                    title: "Preconfigured Tasks",
                    items: preconfiguredTodos.map((todo) => ({
                        id: todo.id || crypto.randomUUID(),
                        title: todo.title,
                        status: "pending",
                        instructions: todo.instructions,
                        agentProfileId: todo.agentProfileId,
                    })),
                };
            }
            const metadata = selected
                ? {
                    profile: selected.name,
                    additionalData,
                }
                : undefined;
            // Create a new agent with the selected profile
            const newAgent = {
                status: "new",
                id: crypto.randomUUID(),
                name: `New Agent`,
                updatedDate: new Date().toISOString(),
                userId: "",
            };
            setAgent(newAgent);
            setInitialMetadata(metadata);
            // Focus the prompt after the agent mounts
            setTimeout(() => {
                try {
                    window.dispatchEvent(new CustomEvent("editor:focusAgentPrompt"));
                }
                catch { }
            }, 60);
        }
        catch (error) {
            console.error("Error creating agent with profile:", error);
        }
    };
    // Empty state when no agent is active
    if (!agent) {
        return (_jsx("div", { className: "flex h-full items-center justify-center bg-gray-50 p-8", children: _jsx("div", { className: "w-full max-w-4xl", children: _jsx(AgentProfileSelector, { profiles: availableProfiles, onSelectProfile: handleSelectProfile, loading: loadingProfiles, title: "parhelia", description: "Select an AI agent profile to begin your session" }) }) }));
    }
    // Active agent terminal view
    return (_jsx("div", { className: "flex h-full items-center justify-center bg-gray-50", children: _jsx("div", { className: "h-full w-full max-w-6xl", children: _jsx(AgentTerminal, { agentStub: agent, initialMetadata: initialMetadata, profiles: availableProfiles, isActive: true }) }) }));
}
//# sourceMappingURL=ParheliaView.js.map