import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { EditorForm } from "./EditorForm";
import { PageViewerFrame } from "./PageViewerFrame";
import { ComponentTree } from "../sidebar/ComponentTree";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { useEditContext, useFieldsEditContext } from "../client/editContext";
import { Layers, StepForward, X } from "lucide-react";
import { cn } from "../../lib/utils";
import { Splitter } from "../ui/Splitter";
import { getComponentById } from "../componentTreeHelper";
import { useSlotContext } from "../views/editorSlotContext";
import { localStorageService } from "../services/localStorageService";
export const SLOT_COMPONENT_NAVIGATOR_DEFAULT_WIDTH = 320;
export function PageViewer({ pageViewContext, showFormEditor, compareView, name, followEditsDefault, className, noMargins, slotCloseButton, }) {
    const editContext = useEditContext();
    const modifiedFieldsContext = useFieldsEditContext();
    const slotContext = useSlotContext();
    const [followEdits, setFollowEdits] = useState(followEditsDefault);
    const [formEditorCollapsed, setFormEditorCollapsed] = useState(false);
    const [dismissedAutoOpenToken, setDismissedAutoOpenToken] = useState(null);
    const wasSlotActiveRef = useRef(false);
    const dismissContextToken = useMemo(() => {
        const selectionKey = (editContext?.selection || []).join(",");
        return [
            slotContext?.slotId || "no-slot",
            selectionKey,
            editContext?.insertMode ? "insert" : "browse",
        ].join("|");
    }, [
        editContext?.insertMode,
        editContext?.selection,
        slotContext?.slotId,
    ]);
    const collapseFormEditor = useCallback(() => {
        setFormEditorCollapsed(true);
        setDismissedAutoOpenToken(dismissContextToken);
    }, [dismissContextToken]);
    useEffect(() => {
        // Remove keys matching the pattern (will match new format with parhelia.* prefix)
        localStorageService.removeAllMatchingKeys("editor.pageViewer.slot-");
    }, []);
    if (!pageViewContext)
        return null;
    useEffect(() => {
        const wasActive = wasSlotActiveRef.current;
        const isActive = !!slotContext?.isActive;
        if (!wasActive && isActive) {
            setDismissedAutoOpenToken(null);
            setFormEditorCollapsed(false);
        }
        wasSlotActiveRef.current = isActive;
    }, [slotContext?.isActive]);
    useEffect(() => {
        // Only open form editor automatically if this slot is active and the user
        // hasn't manually dismissed it for the current selection/intent context.
        if (!slotContext?.isActive) {
            return;
        }
        if (editContext?.activeEditorTab) {
            setFormEditorCollapsed(false);
            return;
        }
        if (!editContext?.insertMode) {
            return;
        }
        if (dismissedAutoOpenToken === dismissContextToken) {
            return;
        }
        setFormEditorCollapsed(false);
    }, [
        dismissContextToken,
        dismissedAutoOpenToken,
        editContext?.activeEditorTab,
        editContext?.insertMode,
        slotContext?.isActive,
    ]);
    useEffect(() => {
        // Only reset collapsed state if:
        // 1. This slot is active
        // 2. The selection contains components relevant to THIS slot's page
        if (!slotContext?.isActive) {
            return;
        }
        const selection = editContext?.selection || [];
        const page = pageViewContext?.page;
        if (!page || selection.length === 0) {
            return;
        }
        // Check if any selected component exists in this page
        const hasRelevantSelection = selection.some((componentId) => {
            const component = getComponentById(componentId, page);
            return !!component;
        });
        if (hasRelevantSelection) {
            if (dismissedAutoOpenToken === dismissContextToken) {
                return;
            }
            setFormEditorCollapsed(false);
        }
    }, [
        dismissContextToken,
        dismissedAutoOpenToken,
        editContext?.selection,
        pageViewContext?.page,
        slotContext?.isActive,
    ]);
    useEffect(() => {
        if (followEdits &&
            modifiedFieldsContext?.recentEdits &&
            modifiedFieldsContext.recentEdits.length > 0) {
            if (modifiedFieldsContext?.inlineEditingFieldElement)
                return;
            const lastEdit = modifiedFieldsContext.recentEdits[modifiedFieldsContext.recentEdits.length - 1];
            if (!lastEdit)
                return;
            if (!lastEdit.user.agentId || lastEdit.user.name !== editContext?.user?.name)
                return;
            if (editContext?.selection.indexOf(lastEdit.item.id) === -1) {
                editContext.select([lastEdit.item.id]);
            }
            const element = pageViewContext?.editorIframe?.contentWindow?.document.querySelector(`[data-fieldid="${lastEdit.fieldId}"][data-itemid="${lastEdit.item.id}"][data-language="${lastEdit.item.language}"][data-version="${lastEdit.item.version}"]`);
            if (element) {
                element.scrollIntoView({ behavior: "smooth", block: "center" });
            }
        }
    }, [
        modifiedFieldsContext?.recentEdits,
        editContext,
        followEdits,
        pageViewContext,
    ]);
    if (!pageViewContext)
        return null;
    const treeItemDescriptor = compareView
        ? slotContext?.compareTo ?? pageViewContext.page?.item
        : slotContext?.itemDescriptor ?? pageViewContext.page?.item;
    const treeItem = compareView ? slotContext?.compareItem : slotContext?.item;
    const treeIsLoading = compareView
        ? !!slotContext?.compareTo && !slotContext?.compareItem
        : slotContext?.isLoading ?? false;
    const showComponentNavigator = !!editContext?.isComponentNavigatorOpenForSlot?.(slotContext?.slotId ?? null) &&
        !editContext?.isMobile &&
        (pageViewContext.page?.item?.hasLayout ?? treeItem?.hasLayout ?? false);
    const hasOuterRightPanel = !!editContext?.showAgentsPanel ||
        !!(editContext?.showHelpTerminal && editContext?.currentItemDescriptor);
    // Create panels array for the Splitter component
    const panels = [];
    if (showFormEditor && !formEditorCollapsed) {
        panels.push({
            name: "form",
            defaultSize: 300,
            collapsible: true,
            content: (_jsx("div", { className: cn("h-full w-full", noMargins ? "py-2" : "py-2 pl-2", formEditorCollapsed && "hidden"), children: _jsxs("div", { className: "border-gray-3 flex h-full w-full flex-col rounded-md border bg-white", children: [_jsx("div", { className: "flex-1", children: _jsx(EditorForm, { pageViewContext: pageViewContext, readonly: editContext?.mode !== "edit", compareView: compareView || false, onCollapse: collapseFormEditor }) }), _jsxs("div", { className: "flex items-center justify-between gap-1 p-1", children: [_jsx("div", { className: "p-1 text-xs text-gray-500", children: editContext?.statusMessage }), _jsx("div", { className: "flex gap-1", children: _jsx(SimpleIconButton, { "data-testid": "followEditsButton", icon: _jsx(StepForward, { className: "h-4 w-4", strokeWidth: 1 }), selected: followEdits, label: "Follow", onClick: () => setFollowEdits((f) => !f) }) })] })] }) })),
        });
    }
    panels.push({
        name: "frame",
        defaultSize: "auto",
        content: (_jsx(PageViewerFrame, { compareView: compareView || false, pageViewContext: pageViewContext, slotCloseButton: slotCloseButton, className: cn("py-2", noMargins
                ? "pr-0"
                : showComponentNavigator
                    ? "pl-2 pr-0"
                    : "px-2", noMargins && showFormEditor && "ml-2") })),
    });
    if (showComponentNavigator) {
        panels.push({
            name: "componentNavigator",
            defaultSize: SLOT_COMPONENT_NAVIGATOR_DEFAULT_WIDTH,
            content: (_jsx("div", { className: cn("h-full w-full py-2 pl-2", !hasOuterRightPanel && "pr-2"), children: _jsxs("div", { className: "border-gray-3 flex h-full w-full flex-col rounded-md border bg-white", "data-testid": "slot-component-navigator", children: [_jsxs("div", { className: "border-gray-3 flex items-center border-b p-1.5 text-xs text-gray-500 uppercase", children: [_jsx("div", { className: "mr-2", children: _jsx(Layers, { className: "h-4 w-4", strokeWidth: 1 }) }), _jsx("div", { className: "mr-auto truncate", children: "Component Navigator" }), _jsx(SimpleIconButton, { onClick: () => editContext?.setComponentNavigatorOpenForSlot?.(slotContext?.slotId ?? null, false), icon: _jsx(X, { className: "size-4" }), label: "Close", className: "ml-2" })] }), _jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: _jsx(ComponentTree, { pageViewContext: pageViewContext, itemDescriptor: treeItemDescriptor, item: treeItem, isLoading: treeIsLoading }) })] }) })),
        });
    }
    return (_jsx("div", { className: cn("h-full w-full", className), children: _jsx(Splitter, { panels: panels, splitterClassName: "bg-transparent -mr-2 md:w-[6px]", direction: editContext?.isMobile ? "vertical" : "horizontal", localStorageKey: "editor.pageViewer.panels.v2" }) }));
}
//# sourceMappingURL=PageViewer.js.map