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, useState } from "react";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { CloseButton } from "../../components/ui/close-button";
import { useEditContext, useFieldsEditContext } from "../client/editContext";
import { Layers, StepForward } from "lucide-react";
import { cn } from "../../lib/utils";
import { Splitter } from "../ui/Splitter";
import { useSlotContext } from "../views/editorSlotContext";
import { localStorageService } from "../services/localStorageService";
export const SLOT_COMPONENT_NAVIGATOR_DEFAULT_WIDTH = 320;
const EDITOR_FORM_DEFAULT_WIDTH = 320;
const EDITOR_FORM_MIN_WIDTH = 240;
const EDITOR_FORM_MIN_VIEWER_WIDTH = 320;
const EDITOR_FORM_WIDTH_STORAGE_KEY = "editor.pageViewer.formWidth.v1";
export function PageViewer(props) {
    if (!props.pageViewContext)
        return null;
    return (_jsx(PageViewerContent, { ...props, pageViewContext: props.pageViewContext }));
}
function PageViewerContent({ pageViewContext, showFormEditor, compareView, name, followEditsDefault, className, noMargins, slotCloseButton, }) {
    const editContext = useEditContext();
    const modifiedFieldsContext = useFieldsEditContext();
    const slotContext = useSlotContext();
    const [followEdits, setFollowEdits] = useState(followEditsDefault);
    const [formPanelDefaultWidth] = useState(() => {
        const storedWidth = localStorageService.getItem(EDITOR_FORM_WIDTH_STORAGE_KEY);
        return typeof storedWidth === "number" &&
            Number.isFinite(storedWidth) &&
            storedWidth >= EDITOR_FORM_MIN_WIDTH
            ? storedWidth
            : EDITOR_FORM_DEFAULT_WIDTH;
    });
    const formHidden = editContext?.isEditorFormHiddenForSlot(slotContext?.slotId ?? null) ??
        false;
    // Insert mode always needs the form open so the user can pick a component or
    // configure the new item, even when the user has hidden the panel. The
    // preference itself is preserved, so the form returns to its hidden state as
    // soon as insert mode ends.
    const formEffectivelyHidden = formHidden && !editContext?.insertMode;
    const collapseFormEditor = useCallback(() => {
        if (!editContext)
            return;
        editContext.setEditorFormHiddenForSlot(slotContext?.slotId ?? null, true);
        if (!editContext.editorFormHintSeen) {
            editContext.showEditorFormHint();
        }
    }, [editContext, slotContext?.slotId]);
    useEffect(() => {
        // Clean up legacy per-slot collapse state from older PageViewer implementation.
        localStorageService.removeAllMatchingKeys("editor.pageViewer.slot-");
    }, []);
    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]);
            }
            let element;
            try {
                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}"]`);
            }
            catch {
                return;
            }
            if (element) {
                element.scrollIntoView({ behavior: "smooth", block: "center" });
            }
        }
    }, [
        modifiedFieldsContext?.recentEdits,
        editContext,
        followEdits,
        pageViewContext,
    ]);
    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);
    const isVertical = !!editContext?.isMobile;
    const formPanelOpen = showFormEditor && !formEffectivelyHidden;
    const viewerPanels = [];
    if (showFormEditor) {
        viewerPanels.push({
            name: "form",
            defaultSize: formPanelDefaultWidth,
            collapsed: !formPanelOpen,
            animatedCollapse: true,
            minSize: EDITOR_FORM_MIN_WIDTH,
            content: (_jsx("div", { "data-testid": "editor-form-slider", "aria-hidden": !formPanelOpen, className: cn("h-full w-full", noMargins ? "py-2" : "py-2 pl-2"), children: _jsxs("div", { className: "border-border-default flex h-full w-full flex-col rounded-md border bg-white", children: [_jsx("div", { className: "min-h-0 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: "text-neutral-grey-50 p-1 text-xs", 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) }) })] })] }) })),
        });
    }
    viewerPanels.push({
        name: "frame",
        defaultSize: "auto",
        minSize: EDITOR_FORM_MIN_VIEWER_WIDTH,
        content: (_jsx(PageViewerFrame, { compareView: compareView || false, pageViewContext: pageViewContext, slotCloseButton: slotCloseButton, className: cn("py-2", noMargins ? "pr-0" : showComponentNavigator ? "pr-0 pl-2" : "px-2", noMargins && formPanelOpen && "ml-2") })),
    });
    if (showComponentNavigator) {
        viewerPanels.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-border-default flex h-full w-full flex-col rounded-md border bg-white", "data-testid": "slot-component-navigator", children: [_jsxs("div", { className: "border-border-default text-neutral-grey-100 flex items-center border-b py-2 pr-2 pl-3 text-sm font-medium", 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(CloseButton, { onClick: () => editContext?.setComponentNavigatorOpenForSlot?.(slotContext?.slotId ?? null, false), 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: viewerPanels, splitterClassName: "bg-transparent -mr-2 md:w-[6px]", direction: isVertical ? "vertical" : "horizontal", localStorageKey: "editor.pageViewer.panels.v2" }) }));
}
//# sourceMappingURL=PageViewer.js.map