import { useEffect, useRef } from "react";
import { normalizeDialogAgentId } from "../agentMessageHelpers";
import { acceptAgentSessionDialog, clearAgentSessionVisibleDialogEntries, isAgentSessionDialogReceiverElected, registerAgentSessionDialogInstance, setAgentSessionVisibleDialogEntry, subscribeAgentSessionDialogEvents, unregisterAgentSessionDialogInstance, updateAgentSessionDialogFocus, } from "./useAgentSessionSync";
export function useAgentInlineDialogEvents(input) {
    const { agentId, agentStubId, effectiveIsFocused, activeInlineDialog, activeInlineDialogRef, setActiveInlineDialog, dialogTerminalInstanceIdRef, editContextRef, textareaRef, scrollToBottom, onInteractionSubmitted, } = input;
    const orphanTimeoutRef = useRef(null);
    const agentIdRefForDialogs = useRef(null);
    const agentStubIdRefForDialogs = useRef(agentStubId);
    const isActiveRefForDialogs = useRef(effectiveIsFocused);
    const scrollToBottomRefForDialogs = useRef(scrollToBottom);
    useEffect(() => {
        activeInlineDialogRef.current = activeInlineDialog;
        const callbackId = activeInlineDialog?.request.callbackId || null;
        const terminalInstanceId = dialogTerminalInstanceIdRef.current;
        const agentKeys = [
            agentStubIdRefForDialogs.current,
            agentIdRefForDialogs.current,
        ];
        if (callbackId) {
            agentKeys.forEach((key) => {
                setAgentSessionVisibleDialogEntry({
                    agentId: key,
                    instanceId: terminalInstanceId,
                    callbackId,
                    isFocused: isActiveRefForDialogs.current,
                });
            });
        }
        else {
            clearAgentSessionVisibleDialogEntries(agentKeys, terminalInstanceId);
        }
    }, [activeInlineDialog, activeInlineDialogRef, dialogTerminalInstanceIdRef]);
    useEffect(() => {
        const normalizedAgentId = normalizeDialogAgentId(agentId);
        agentIdRefForDialogs.current = normalizedAgentId;
        if (!normalizedAgentId ||
            normalizedAgentId ===
                normalizeDialogAgentId(agentStubIdRefForDialogs.current)) {
            return;
        }
        const terminalInstanceId = dialogTerminalInstanceIdRef.current;
        registerAgentSessionDialogInstance(normalizedAgentId, terminalInstanceId);
        return () => {
            clearAgentSessionVisibleDialogEntries([normalizedAgentId], terminalInstanceId);
            unregisterAgentSessionDialogInstance(normalizedAgentId, terminalInstanceId);
        };
    }, [agentId, dialogTerminalInstanceIdRef]);
    useEffect(() => {
        const prevId = agentStubIdRefForDialogs.current;
        agentStubIdRefForDialogs.current = agentStubId;
        if (prevId && prevId !== agentStubId) {
            const terminalInstanceId = dialogTerminalInstanceIdRef.current;
            clearAgentSessionVisibleDialogEntries([prevId], terminalInstanceId);
            unregisterAgentSessionDialogInstance(prevId, terminalInstanceId);
            registerAgentSessionDialogInstance(agentStubId, terminalInstanceId);
            const orphanedDialog = activeInlineDialogRef.current;
            if (orphanedDialog) {
                setActiveInlineDialog(null);
                window.dispatchEvent(new CustomEvent("agent:dialog:orphaned", {
                    detail: { callbackId: orphanedDialog.request.callbackId },
                }));
            }
        }
    }, [
        activeInlineDialogRef,
        agentStubId,
        dialogTerminalInstanceIdRef,
        setActiveInlineDialog,
    ]);
    useEffect(() => {
        isActiveRefForDialogs.current = effectiveIsFocused;
        updateAgentSessionDialogFocus([agentStubIdRefForDialogs.current, agentIdRefForDialogs.current], dialogTerminalInstanceIdRef.current, effectiveIsFocused);
    }, [dialogTerminalInstanceIdRef, effectiveIsFocused]);
    useEffect(() => {
        scrollToBottomRefForDialogs.current = scrollToBottom;
    }, [scrollToBottom]);
    useEffect(() => {
        const focusHandler = (ev) => {
            try {
                const detail = ev.detail;
                if (detail?.agentId) {
                    const myStubId = agentStubIdRefForDialogs.current;
                    const myAgentId = agentIdRefForDialogs.current;
                    if (detail.agentId !== myStubId && detail.agentId !== myAgentId) {
                        return;
                    }
                }
                else if (!isActiveRefForDialogs.current) {
                    return;
                }
                if (textareaRef.current) {
                    textareaRef.current.focus();
                    const value = textareaRef.current.value || "";
                    textareaRef.current.selectionStart = value.length;
                    textareaRef.current.selectionEnd = value.length;
                }
            }
            catch { }
        };
        window.addEventListener("editor:focusAgentPrompt", focusHandler);
        return () => window.removeEventListener("editor:focusAgentPrompt", focusHandler);
    }, [textareaRef]);
    useEffect(() => {
        if (orphanTimeoutRef.current) {
            clearTimeout(orphanTimeoutRef.current);
            orphanTimeoutRef.current = null;
        }
        const terminalInstanceId = dialogTerminalInstanceIdRef.current;
        registerAgentSessionDialogInstance(agentStubIdRefForDialogs.current, terminalInstanceId);
        const handleDialogShow = (event) => {
            const detail = event?.detail;
            const request = detail?.request;
            const onComplete = detail?.onComplete;
            const onCancel = detail?.onCancel;
            if (!request)
                return;
            const terminalAgentId = normalizeDialogAgentId(agentIdRefForDialogs.current);
            const terminalAgentStubId = normalizeDialogAgentId(agentStubIdRefForDialogs.current);
            const requestAgentId = normalizeDialogAgentId(request.agentId);
            if (requestAgentId &&
                terminalAgentStubId &&
                requestAgentId !== terminalAgentStubId &&
                requestAgentId !== terminalAgentId) {
                return;
            }
            const electionAgentId = requestAgentId || terminalAgentStubId;
            if (electionAgentId &&
                !isAgentSessionDialogReceiverElected(electionAgentId, terminalInstanceId)) {
                return;
            }
            console.log("[AgentTerminal] Received inline dialog request:", request);
            setActiveInlineDialog({
                request,
                onComplete: (result) => {
                    onComplete(result);
                    onInteractionSubmitted?.();
                },
                onCancel: () => {
                    onCancel();
                    onInteractionSubmitted?.();
                },
            });
            if (request.callbackId) {
                window.dispatchEvent(new CustomEvent("agent:dialog:accepted", {
                    detail: { callbackId: request.callbackId },
                }));
                const currentEditContext = editContextRef.current;
                if (currentEditContext?.sessionId) {
                    void acceptAgentSessionDialog({
                        callbackId: request.callbackId,
                        agentId: request.agentId,
                        dialogType: request.dialogType,
                        terminalInstanceId,
                        sessionId: currentEditContext.sessionId,
                    }).catch((error) => {
                        console.warn("[AgentTerminal] Failed to acknowledge dialog:", error);
                    });
                }
            }
            // Questionnaires render inline in the conversation flow and are scrolled
            // into view top-aligned by AgentTerminalFullUpperContent (a tall form
            // scrolled to the bottom would hide its title and first questions).
            if (request.dialogType !== "questionnaire") {
                setTimeout(() => {
                    scrollToBottomRefForDialogs.current?.();
                }, 100);
            }
        };
        const unsubscribeDialogEvents = subscribeAgentSessionDialogEvents(handleDialogShow);
        return () => {
            unregisterAgentSessionDialogInstance(agentStubIdRefForDialogs.current, terminalInstanceId);
            clearAgentSessionVisibleDialogEntries([agentStubIdRefForDialogs.current, agentIdRefForDialogs.current], terminalInstanceId);
            const orphanedDialog = activeInlineDialogRef.current;
            if (orphanedDialog) {
                orphanTimeoutRef.current = setTimeout(() => {
                    orphanTimeoutRef.current = null;
                    window.dispatchEvent(new CustomEvent("agent:dialog:orphaned", {
                        detail: { callbackId: orphanedDialog.request.callbackId },
                    }));
                }, 300);
            }
            unsubscribeDialogEvents();
        };
    }, [
        activeInlineDialogRef,
        dialogTerminalInstanceIdRef,
        editContextRef,
        onInteractionSubmitted,
        setActiveInlineDialog,
    ]);
    return {
        agentIdRefForDialogs,
        agentStubIdRefForDialogs,
    };
}
//# sourceMappingURL=useAgentInlineDialogEvents.js.map