import { useEffect, useState } from "react";
import { localStorageService } from "../services/localStorageService";
export const ACTIVE_AGENT_STORAGE_KEY = "editor.activeAgentId";
export const ACTIVE_AGENT_CONVERSATION_EVENT = "editor:activeAgentConversationChanged";
const STORAGE_PREFIX = "parhelia.";
const ACTIVE_AGENT_STORAGE_EVENT_KEY = STORAGE_PREFIX + ACTIVE_AGENT_STORAGE_KEY;
function readHasActiveConversation() {
    return Boolean(localStorageService.getString(ACTIVE_AGENT_STORAGE_KEY));
}
export function getActiveAgentConversationId() {
    return localStorageService.getString(ACTIVE_AGENT_STORAGE_KEY);
}
export function setActiveAgentConversation(agentId) {
    const activeAgentId = agentId || null;
    if (activeAgentId) {
        localStorageService.setString(ACTIVE_AGENT_STORAGE_KEY, activeAgentId);
    }
    else {
        localStorageService.removeItem(ACTIVE_AGENT_STORAGE_KEY);
    }
    if (typeof window === "undefined")
        return;
    window.dispatchEvent(new CustomEvent(ACTIVE_AGENT_CONVERSATION_EVENT, {
        detail: {
            active: Boolean(activeAgentId),
            agentId: activeAgentId ?? undefined,
        },
    }));
}
export function useActiveAgentConversation() {
    const [hasActiveConversation, setHasActiveConversation] = useState(readHasActiveConversation);
    useEffect(() => {
        const handleActiveConversationChange = (event) => {
            const active = event.detail
                ?.active;
            setHasActiveConversation(Boolean(active));
        };
        const handleStorageChange = (event) => {
            if (event.key && event.key !== ACTIVE_AGENT_STORAGE_EVENT_KEY)
                return;
            setHasActiveConversation(readHasActiveConversation());
        };
        window.addEventListener(ACTIVE_AGENT_CONVERSATION_EVENT, handleActiveConversationChange);
        window.addEventListener("storage", handleStorageChange);
        return () => {
            window.removeEventListener(ACTIVE_AGENT_CONVERSATION_EVENT, handleActiveConversationChange);
            window.removeEventListener("storage", handleStorageChange);
        };
    }, []);
    return hasActiveConversation;
}
//# sourceMappingURL=useActiveAgentConversation.js.map