import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useRef, useCallback } from "react";
import MainLayout from "../../MainLayout";
import { SidebarPanel } from "../../sidebar/SidebarPanel";
import { ManualPanel } from "../../ai/ManualPanel";
import { DismissableLayerBranch } from "@radix-ui/react-dismissable-layer";
import { RemoveScroll } from "react-remove-scroll";
import { AppPortalContainerProvider, APP_PORTAL_CONTAINER_ID, } from "../../../components/ui/portal-container-context";
import { localStorageService } from "../../services/localStorageService";
export const HELP_PANEL_WIDTH = 400;
const HELP_PANEL_MIN_WIDTH = 300;
const HELP_PANEL_MAX_WIDTH = 800;
const HELP_PANEL_STORAGE_KEY = "help-panel-width";
export function EditorChrome(props) {
    const { className, currentWorkspace, centerPanelView, editContext, showAgentsPanel, handleSetShowAgentsPanel, workspaceId, } = props;
    const agentsPanelSidebar = editContext.availableSidebars?.find((s) => s.id === "agents-panel");
    const noAgentsPanelWorkspaces = [
        "home",
        "settings",
        "agents",
        "taskboard",
        "translation-management",
    ];
    const canShowAgentsPanel = !noAgentsPanelWorkspaces.includes(workspaceId) && !!agentsPanelSidebar;
    const showHelpPanel = editContext.showHelpTerminal && !editContext.isMobile;
    const [helpPanelWidth, setHelpPanelWidth] = useState(() => {
        const stored = localStorageService.getString(HELP_PANEL_STORAGE_KEY);
        if (stored) {
            const parsed = parseInt(stored, 10);
            if (!isNaN(parsed) &&
                parsed >= HELP_PANEL_MIN_WIDTH &&
                parsed <= HELP_PANEL_MAX_WIDTH) {
                return parsed;
            }
        }
        return HELP_PANEL_WIDTH;
    });
    const isResizingRef = useRef(false);
    const startXRef = useRef(0);
    const startWidthRef = useRef(0);
    const handleResizeStart = useCallback((e) => {
        e.preventDefault();
        isResizingRef.current = true;
        startWidthRef.current = helpPanelWidth;
        const clientX = "touches" in e ? (e.touches[0]?.clientX ?? 0) : e.clientX;
        startXRef.current = clientX;
        const iframes = document.querySelectorAll("iframe");
        iframes.forEach((iframe) => {
            iframe.style.pointerEvents = "none";
        });
        document.body.style.cursor = "ew-resize";
        document.body.style.userSelect = "none";
    }, [helpPanelWidth]);
    useEffect(() => {
        const handleMouseMove = (e) => {
            if (!isResizingRef.current)
                return;
            const delta = startXRef.current - e.clientX;
            const newWidth = Math.min(HELP_PANEL_MAX_WIDTH, Math.max(HELP_PANEL_MIN_WIDTH, startWidthRef.current + delta));
            setHelpPanelWidth(newWidth);
        };
        const handleTouchMove = (e) => {
            if (!isResizingRef.current)
                return;
            const touch = e.touches[0];
            if (!touch)
                return;
            const delta = startXRef.current - touch.clientX;
            const newWidth = Math.min(HELP_PANEL_MAX_WIDTH, Math.max(HELP_PANEL_MIN_WIDTH, startWidthRef.current + delta));
            setHelpPanelWidth(newWidth);
        };
        const handleEnd = () => {
            if (!isResizingRef.current)
                return;
            isResizingRef.current = false;
            const iframes = document.querySelectorAll("iframe");
            iframes.forEach((iframe) => {
                iframe.style.pointerEvents = "";
            });
            document.body.style.cursor = "";
            document.body.style.userSelect = "";
        };
        window.addEventListener("mousemove", handleMouseMove);
        window.addEventListener("mouseup", handleEnd);
        window.addEventListener("touchmove", handleTouchMove);
        window.addEventListener("touchend", handleEnd);
        return () => {
            window.removeEventListener("mousemove", handleMouseMove);
            window.removeEventListener("mouseup", handleEnd);
            window.removeEventListener("touchmove", handleTouchMove);
            window.removeEventListener("touchend", handleEnd);
        };
    }, []);
    useEffect(() => {
        localStorageService.setString(HELP_PANEL_STORAGE_KEY, String(helpPanelWidth));
    }, [helpPanelWidth]);
    useEffect(() => {
        const workspaceTitle = currentWorkspace.title;
        const activeSlotContext = editContext.getActiveSlotContext?.();
        const currentItemName = editContext.currentItemDescriptor?.displayName ||
            editContext.currentItemDescriptor?.name ||
            editContext.item?.descriptor?.displayName ||
            editContext.item?.descriptor?.name ||
            editContext.item?.name ||
            editContext.page?.item?.displayName ||
            editContext.page?.item?.name ||
            activeSlotContext?.item?.descriptor?.displayName ||
            activeSlotContext?.item?.descriptor?.name ||
            activeSlotContext?.item?.name ||
            activeSlotContext?.itemDescriptor?.displayName ||
            activeSlotContext?.itemDescriptor?.name;
        document.title = currentItemName
            ? `${currentItemName} - Parhelia`
            : `${workspaceTitle} - Parhelia`;
    }, [
        currentWorkspace.title,
        editContext.currentItemDescriptor?.displayName,
        editContext.currentItemDescriptor?.name,
        editContext.item?.descriptor?.displayName,
        editContext.item?.descriptor?.name,
        editContext.item?.name,
        editContext.page?.item?.displayName,
        editContext.page?.item?.name,
        editContext.activeSlotId,
        editContext.editorSlots,
    ]);
    const [appContainer, setAppContainer] = useState(null);
    const appContainerRef = useCallback((node) => {
        setAppContainer(node);
    }, []);
    const [activeDialogShards, setActiveDialogShards] = useState([]);
    useEffect(() => {
        if (!appContainer) {
            setActiveDialogShards([]);
            return;
        }
        const updateDialogShards = () => {
            setActiveDialogShards(Array.from(appContainer.querySelectorAll('[data-slot="dialog-content"]')));
        };
        updateDialogShards();
        const observer = new MutationObserver(updateDialogShards);
        observer.observe(appContainer, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: ["data-state"],
        });
        return () => {
            observer.disconnect();
        };
    }, [appContainer]);
    const bridgeManualIntoDialog = showHelpPanel && activeDialogShards.length > 0;
    return (_jsxs("div", { className: "overscroll-behavior-none fixed inset-0 flex h-dvh w-screen overflow-hidden", children: [_jsx("div", { ref: appContainerRef, id: APP_PORTAL_CONTAINER_ID, className: "relative min-w-0 flex-1", style: { transform: "translateZ(0)" }, children: _jsx(AppPortalContainerProvider, { value: appContainer, children: _jsx(MainLayout, { className: className, workspace: currentWorkspace, centerPanelView: centerPanelView, farRightSidebar: canShowAgentsPanel && (_jsx(SidebarPanel, { sidebar: {
                                title: agentsPanelSidebar.title,
                                icon: agentsPanelSidebar.icon,
                                panels: agentsPanelSidebar.panels.map((p) => typeof p === "function" ? p(editContext) : p),
                            }, editContext: editContext, active: true, detached: true, paddingRight: true, onClose: () => handleSetShowAgentsPanel(false) })), farRightSidebarCollapsed: !showAgentsPanel, farRightSidebarTitle: "Agents" }) }) }), showHelpPanel && (_jsx(RemoveScroll, { enabled: bridgeManualIntoDialog, removeScrollBar: false, allowPinchZoom: true, shards: activeDialogShards, className: "contents", children: _jsx(DismissableLayerBranch, { className: "contents", children: _jsxs("div", { className: "border-border-default relative flex h-full shrink-0 border-l bg-white", style: {
                            width: helpPanelWidth,
                            pointerEvents: bridgeManualIntoDialog ? "auto" : undefined,
                        }, "data-testid": "help-panel", "data-help-panel": "true", children: [_jsx("div", { className: "hover:bg-feedback-blue/40 active:bg-feedback-blue/60 absolute top-0 bottom-0 left-0 z-10 w-1.5 cursor-ew-resize bg-transparent transition-colors", onMouseDown: handleResizeStart, onTouchStart: handleResizeStart, title: "Drag to resize" }), _jsx("div", { className: "flex-1 overflow-hidden", children: _jsx(ManualPanel, {}) })] }) }) }))] }));
}
//# sourceMappingURL=EditorChrome.js.map