import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { MessageProvider, useActiveDetailedView, useArtifactList, useThread, useToolActivities, } from "@openuidev/react-headless";
import clsx from "clsx";
import { memo, useId, useRef } from "react";
import { useLayoutContext } from "../../context/LayoutContext";
import { useScrollToBottom } from "../../hooks/useScrollToBottom";
import { DetailedViewOverlay, DetailedViewPanel, DetailedViewPortalTarget, } from "./_shared/detailed-view";
import { useAgentInterfaceLabels } from "./_shared/labelsContext";
import { useAgentInterfaceStore } from "./_shared/store";
import { TimelineEntry } from "./_shared/tool-renderer";
import { Callout } from "../Callout";
import { IconButton } from "../IconButton";
import { MarkDownRenderer } from "../MarkDownRenderer";
import { MessageLoading as MessageLoadingComponent } from "../MessageLoading";
import { ResizableSeparator } from "./ResizableSeparator";
import { UserMessageContent } from "./UserMessageContent";
import { AgentInterfaceTooltip } from "./_shared/AgentInterfaceTooltip";
import { GalleryHorizontalEndIcon } from "./_shared/GalleryHorizontalEndIcon";
import { useDetailedViewResize } from "./useDetailedViewResize";
export const ThreadContainer = ({ children, className, }) => {
    const { layout } = useLayoutContext();
    const isMobile = layout === "mobile";
    const { isDetailedViewActive } = useActiveDetailedView();
    const { setIsSidebarOpen } = useAgentInterfaceStore((state) => ({
        setIsSidebarOpen: state.setIsSidebarOpen,
    }));
    const isLoadingMessages = useThread((s) => s.isLoadingMessages);
    const { containerRef, chatPanelRef, detailedViewPanelRef, isDragging, handleResize, handleResizeStep, handleDragStart, handleDragEnd, getResizeAria, } = useDetailedViewResize({
        isDetailedViewActive,
        isMobile,
        setIsSidebarOpen,
    });
    const chatPanelId = useId();
    const detailPanelId = useId();
    return (_jsx("div", { className: clsx("openui-agent-thread-container", className, {
            "openui-agent-thread-container--detailed-view-active": isDetailedViewActive,
        }), style: {
            visibility: isLoadingMessages ? "hidden" : undefined,
        }, children: _jsxs("div", { className: "openui-agent-thread-wrapper", ref: containerRef, children: [_jsxs("div", { ref: chatPanelRef, id: chatPanelId, className: clsx("openui-agent-thread-chat-panel", {
                        "openui-agent-thread-chat-panel--animating": !isDragging,
                    }), children: [children, isMobile && _jsx(DetailedViewOverlay, {})] }), !isMobile && isDetailedViewActive && (_jsxs(_Fragment, { children: [_jsx(ResizableSeparator, { onResize: handleResize, onResizeStep: handleResizeStep, onDragStart: handleDragStart, onDragEnd: handleDragEnd, getAriaValues: getResizeAria, controlsId: `${chatPanelId} ${detailPanelId}`, ariaLabel: "Resize chat panel" }), _jsx("div", { ref: detailedViewPanelRef, id: detailPanelId, className: clsx("openui-agent-thread-detailed-view-panel", {
                                "openui-agent-thread-detailed-view-panel--animating": !isDragging,
                            }), children: _jsx(DetailedViewPortalTarget, {}) })] }))] }) }));
};
export const ScrollArea = ({ children, className, scrollVariant = "user-message-anchor", userMessageSelector = ".openui-agent-thread-message-user", scrollOnLoad = true, }) => {
    const ref = useRef(null);
    const messages = useThread((s) => s.messages);
    const isRunning = useThread((s) => s.isRunning);
    const isLoadingMessages = useThread((s) => s.isLoadingMessages);
    useScrollToBottom({
        ref,
        lastMessage: messages[messages.length - 1] || { id: "" },
        scrollVariant,
        userMessageSelector,
        isRunning,
        isLoadingMessages,
        scrollOnLoad,
    });
    return (_jsx("div", { className: "openui-agent-thread-scroll-container", children: _jsx("div", { ref: ref, className: clsx("openui-agent-thread-scroll-area", {
                "openui-agent-thread-scroll-area--user-message-anchor": scrollVariant === "user-message-anchor",
            }, className), children: children }) }));
};
export const AssistantMessageContainer = ({ children, className, }) => {
    return (_jsx("div", { className: clsx("openui-agent-thread-message-assistant", className), children: _jsx("div", { className: "openui-agent-thread-message-assistant__content", children: children }) }));
};
export const UserMessageContainer = ({ children, className, }) => {
    return (_jsx("div", { className: clsx("openui-agent-thread-message-user", className), children: _jsx("div", { className: "openui-agent-thread-message-user__content", children: children }) }));
};
const AssistantMessageContent = ({ message, allMessages, isLast, }) => {
    // One id-keyed pairing of calls↔results with real status — no positional break,
    // no grouped-not-paired flow, running state from the data.
    const activities = useToolActivities(message, allMessages);
    return (_jsxs(_Fragment, { children: [message.content && (_jsx(MarkDownRenderer, { textMarkdown: message.content, className: "openui-agent-thread-message-assistant__text" })), activities.map((activity, idx) => (_jsx(TimelineEntry, { activity: activity, isLast: isLast && idx === activities.length - 1, detailedViewPanel: DetailedViewPanel }, activity.id)))] }));
};
export const RenderMessage = memo(({ message, className, allMessages, assistantMessage: CustomAssistantMessage, userMessage: CustomUserMessage, isStreaming, isLast, }) => {
    if (message.role === "tool") {
        // Tool messages are rendered inline with their parent assistant message
        return null;
    }
    if (message.role === "assistant") {
        if (CustomAssistantMessage) {
            return _jsx(CustomAssistantMessage, { message: message, isStreaming: isStreaming });
        }
        return (_jsx(AssistantMessageContainer, { className: className, children: _jsx(AssistantMessageContent, { message: message, allMessages: allMessages, isLast: isLast }) }));
    }
    if (message.role === "user") {
        if (CustomUserMessage) {
            return _jsx(CustomUserMessage, { message: message });
        }
        return (_jsx(UserMessageContainer, { className: className, children: _jsx(UserMessageContent, { message: message }) }));
    }
    // Other roles (system, developer, reasoning, activity) — skip by default
    return null;
});
export const MessageLoading = () => {
    return (_jsx("div", { className: "openui-agent-thread-message-loading", children: _jsx(MessageLoadingComponent, {}) }));
};
export const ThreadError = () => {
    const threadError = useThread((s) => s.threadError);
    if (!threadError)
        return null;
    return (_jsx("div", { className: "openui-agent-thread-error", children: _jsx(Callout, { variant: "danger", title: "Something went wrong", description: threadError.message || "An unexpected error occurred. Please try again." }) }));
};
export const Messages = ({ className, loader, assistantMessage, userMessage, }) => {
    const messages = useThread((s) => s.messages);
    const isRunning = useThread((s) => s.isRunning);
    const threadError = useThread((s) => s.threadError);
    // Scan for the last *assistant* message (not the last message index) so the
    // running shimmer survives trailing tool messages.
    let lastAssistantIndex = -1;
    for (let i = messages.length - 1; i >= 0; i--) {
        if (messages[i]?.role === "assistant") {
            lastAssistantIndex = i;
            break;
        }
    }
    return (_jsxs("div", { className: clsx("openui-agent-thread-messages", className), children: [messages.map((message, i) => {
                return (_jsx(MessageProvider, { message: message, children: _jsx(RenderMessage, { message: message, allMessages: messages, assistantMessage: assistantMessage, userMessage: userMessage, isStreaming: isRunning && i === lastAssistantIndex, isLast: i === lastAssistantIndex }) }, message.id));
            }), isRunning && _jsx("div", { children: loader }), !isRunning && threadError && _jsx(ThreadError, {})] }));
};
export const ThreadHeader = ({ children, className, }) => {
    return (_jsxs("div", { className: clsx("openui-agent-thread-header", className), children: [_jsx("div", { className: "openui-agent-thread-header__title" }), _jsxs("div", { className: "openui-agent-thread-header__actions", children: [children, _jsx(WorkspaceToggleButton, {})] })] }));
};
const WorkspaceToggleButton = () => {
    const artifacts = useArtifactList();
    const { isDetailedViewActive } = useActiveDetailedView();
    const { workspaceToggle } = useAgentInterfaceLabels();
    const { isWorkspaceOpen, setIsWorkspaceOpen } = useAgentInterfaceStore((state) => ({
        isWorkspaceOpen: state.isWorkspaceOpen,
        setIsWorkspaceOpen: state.setIsWorkspaceOpen,
    }));
    const hasArtifacts = Object.keys(artifacts).length > 0;
    if (!hasArtifacts || isDetailedViewActive)
        return null;
    return (_jsx(AgentInterfaceTooltip, { content: workspaceToggle, side: "left", children: _jsx(IconButton, { icon: _jsx(GalleryHorizontalEndIcon, { size: "1em" }), onClick: () => {
                if (hasArtifacts)
                    setIsWorkspaceOpen(!isWorkspaceOpen);
            }, size: "small", variant: "tertiary", "aria-label": isWorkspaceOpen ? "Collapse workspace" : "Expand workspace", className: "openui-agent-thread-header__workspace-toggle-button" }) }));
};
// Re-export Composer from components
export { Composer } from "./components";
//# sourceMappingURL=Thread.js.map