import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useRef } from "react";
import { useEditContext } from "../client/editContext";
import { PageViewer } from "../page-viewer/PageViewer";
import { useViewportChangeSignal } from "../page-viewer/pageViewContext";
import { ItemEditor } from "./ItemEditor";
import { MediaFolderEditView } from "./MediaFolderEditView";
import { Spinner } from "../ui/Spinner";
import { useDelayedTrue } from "../hooks/useDelayedTrue";
import { useSlotContext } from "./editorSlotContext";
const LOADING_SPINNER_DELAY_MS = 250;
/**
 * Keeps the previous non-undefined value during loading transitions.
 * Returns undefined only if value has never been defined.
 */
function usePreviousWhileLoading(value, isLoading) {
    const prevRef = useRef(value);
    if (!isLoading && value !== undefined) {
        prevRef.current = value;
    }
    return isLoading ? prevRef.current : value;
}
export function SingleEditView({ compareView, name, view = "primary", className, onActivate, isActive, formEditorCollapsed, setFormEditorCollapsed, slotCloseButton, }) {
    const editContext = useEditContext();
    const slotContext = useSlotContext();
    useViewportChangeSignal();
    // Note: slotContext is a stable object ref with mutated properties, so we must
    // include the actual property values in memo deps to detect changes.
    const pageViewContext = useMemo(() => {
        if (!slotContext)
            return undefined;
        if (view === "compare") {
            return slotContext.pageViewContexts[1] ?? slotContext.primaryPageViewContext;
        }
        return slotContext.primaryPageViewContext;
    }, [slotContext?.primaryPageViewContext, slotContext?.pageViewContexts, view]);
    const effectiveItem = useMemo(() => {
        if (!slotContext)
            return undefined;
        if (view === "compare")
            return slotContext.compareItem;
        return slotContext.item;
    }, [slotContext?.item, slotContext?.compareItem, view]);
    const isLoading = useMemo(() => {
        if (!slotContext)
            return false;
        if (view === "compare")
            return !!slotContext.compareTo && !slotContext.compareItem;
        return slotContext.isLoading;
    }, [slotContext?.isLoading, slotContext?.compareTo, slotContext?.compareItem, view]);
    const isMissing = useMemo(() => {
        if (!slotContext)
            return false;
        if (view === "compare")
            return slotContext.compareItemMissing;
        return slotContext.itemMissing;
    }, [slotContext?.compareItemMissing, slotContext?.itemMissing, view]);
    const isViewLoading = !!slotContext &&
        !!editContext &&
        !!pageViewContext &&
        !isMissing &&
        (isLoading || !effectiveItem);
    const showSpinner = useDelayedTrue(isViewLoading, LOADING_SPINNER_DELAY_MS);
    // Keep showing previous item during fast loads to avoid flicker.
    // Only switch to spinner state after the delay has elapsed.
    const displayItem = usePreviousWhileLoading(effectiveItem, isViewLoading && !showSpinner);
    if (!slotContext || !editContext || !pageViewContext) {
        return (_jsxs("div", { className: "relative grid h-full w-full items-center justify-center", children: [slotCloseButton && (_jsx("div", { className: "absolute top-3 right-3 z-50", children: slotCloseButton })), _jsx("div", { className: "text-xs text-gray-500", children: "No item selected" })] }));
    }
    // Item finished loading and the backend returned no result – show a clear
    // terminal state instead of an indefinite spinner.
    if (isMissing && !effectiveItem) {
        return (_jsxs("div", { className: "relative grid h-full w-full items-center justify-center", "data-testid": "single-edit-view-missing", children: [slotCloseButton && (_jsx("div", { className: "absolute top-3 right-3 z-50", children: slotCloseButton })), _jsxs("div", { className: "flex max-w-sm flex-col items-center gap-2 px-6 text-center", children: [_jsx("div", { className: "text-sm font-medium text-gray-700", children: view === "compare"
                                ? "The comparison item no longer exists."
                                : "This item no longer exists." }), _jsx("div", { className: "text-xs text-gray-500", children: "It may have been deleted or moved." })] })] }));
    }
    // Show spinner only after delay has passed and we still don't have an item
    if (showSpinner && !effectiveItem) {
        return (_jsxs("div", { className: "relative grid h-full w-full items-center justify-center", children: [slotCloseButton && (_jsx("div", { className: "absolute top-3 right-3 z-50", children: slotCloseButton })), _jsx(Spinner, {})] }));
    }
    // If we have no display item at all (first load), show nothing or spinner
    if (!displayItem) {
        return (_jsxs("div", { className: "relative grid h-full w-full items-center justify-center", children: [slotCloseButton && (_jsx("div", { className: "absolute top-3 right-3 z-50", children: slotCloseButton })), showSpinner ? _jsx(Spinner, {}) : null] }));
    }
    // Check if this is a media folder
    const isMediaFolder = displayItem?.templateId?.toLowerCase() ===
        "fe5dd826-48c6-436d-b87a-7c4210c7413b";
    // Check if this is the media library root item (typically has template ID eb22c1a2-8899-4d2d-b36c-4aeb209e66b7)
    const isMediaLibraryRoot = displayItem?.id?.toLowerCase() === "3d6658d8-a0bf-4e75-b3e2-d050fabcf4e1";
    if (isMediaFolder || isMediaLibraryRoot) {
        return (_jsxs("div", { "data-view": "media-folder-edit-view", className: "relative h-full w-full", children: [slotCloseButton && (_jsx("div", { className: "absolute top-3 right-3 z-50", children: slotCloseButton })), _jsx(MediaFolderEditView, { item: displayItem })] }));
    }
    // Show ItemEditor if:
    // - Item has no layout (not a page)
    // - Device is empty (no preview possible)
    // - Item has no versions (can't render a page without a version)
    if ((displayItem && !displayItem.hasLayout) ||
        pageViewContext.device === "" ||
        (displayItem && displayItem.versions === 0)) {
        return (_jsxs("div", { "data-view": "item-editor-view", className: `relative h-full w-full ${className || ""}`, children: [slotCloseButton && (_jsx("div", { className: "absolute top-3 right-3 z-50", children: slotCloseButton })), _jsx(ItemEditor, { item: displayItem })] }));
    }
    return (_jsx("div", { "data-view": "single-edit-view", className: `h-full w-full ${className || ""}`, children: _jsx(PageViewer, { pageViewContext: pageViewContext, showFormEditor: !editContext?.isMobile && editContext?.workspaceId == "editor", compareView: compareView, name: name, followEditsDefault: false, className: className, slotCloseButton: slotCloseButton }) }));
}
//# sourceMappingURL=SingleEditView.js.map