import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useEditContext } from "../client/editContext";
import { LanguageSelector } from "../../components/ui/LanguageSelector";
import { VersionSelector } from "../menubar/VersionSelector";
import { useSearchParams } from "../client/navigation";
import { SingleEditView } from "./SingleEditView";
import { getLanguagesAndVersions } from "../services/contentService";
import { Splitter } from "../ui/Splitter";
import { ItemEditor } from "./ItemEditor";
import { useSlotContext } from "./editorSlotContext";
import { useViewportChangeSignal } from "../page-viewer/pageViewContext";
export function CompareView({ slotCloseButton, }) {
    const editContext = useEditContext();
    const slotContext = useSlotContext();
    const searchParams = useSearchParams();
    useViewportChangeSignal();
    if (!editContext || !slotContext)
        return;
    const [compareToVersions, setCompareToVersions] = useState([]);
    const compareTo = slotContext.compareTo;
    const setCompareTo = slotContext.setCompareTo;
    const compareToItem = slotContext.compareItem;
    const comparePageViewContext = slotContext.pageViewContexts[1] ?? slotContext.primaryPageViewContext;
    // Track whether compare-to has been initialized for the current item ID,
    // so that subsequent editContext.itemLanguages reference changes (e.g. from
    // switching the left-side version) don't re-trigger initialization and
    // overwrite the user's right-side selection.
    const compareInitializedForIdRef = useRef(null);
    const updateCompareToVersions = async () => {
        if (!compareTo || !compareTo.id || !compareTo.language) {
            setCompareToVersions([]);
            return;
        }
        const result = await getLanguagesAndVersions(compareTo);
        if (result?.data) {
            const versions = result.data.versions.reverse();
            setCompareToVersions(versions);
        }
    };
    // Reset initialization tracking when the item ID changes.
    useEffect(() => {
        compareInitializedForIdRef.current = null;
    }, [slotContext.itemDescriptor?.id]);
    useEffect(() => {
        const currentId = slotContext.itemDescriptor?.id;
        // Skip re-initialization if we already set up compareTo for this item.
        if (compareInitializedForIdRef.current === currentId)
            return;
        const updateCompareTo = async () => {
            if (!editContext)
                return;
            if (currentId) {
                let urlLanguage = searchParams.get("compareLanguage") ||
                    slotContext.itemDescriptor.language;
                let urlVersion = parseInt(searchParams.get("compareVersion") || "0") ||
                    slotContext.itemDescriptor?.version;
                const language = editContext.itemLanguages.find((x) => x.languageCode === urlLanguage);
                if (!language || !language.versions) {
                    urlLanguage = "";
                }
                if (!currentId || !language) {
                    setCompareTo(undefined);
                    return;
                }
                const result = await getLanguagesAndVersions({
                    id: currentId,
                    language: language.languageCode,
                    version: 0,
                });
                if (result?.data) {
                    const versions = [...result.data.versions].reverse();
                    const version = versions.find((x) => x.version === urlVersion);
                    setCompareTo({
                        id: slotContext.itemDescriptor.id,
                        language: urlLanguage,
                        version: version?.version || 0,
                    });
                    compareInitializedForIdRef.current = currentId;
                }
            }
        };
        updateCompareTo();
    }, [
        searchParams,
        editContext?.itemLanguages,
        slotContext.itemDescriptor?.id,
    ]);
    useEffect(() => {
        updateCompareToVersions();
    }, [compareTo]);
    function updateCompareTo(compareToItemDescriptor) {
        if (compareToItemDescriptor) {
            const newParams = new URLSearchParams(searchParams.toString());
            newParams.set("compareLanguage", compareToItemDescriptor.language);
            newParams.set("compareVersion", compareToItemDescriptor.version.toString());
            // Use history.pushState instead of router.push to avoid full page reload
            // in static export mode. Then directly update state since searchParams
            // won't automatically update with pushState.
            if (typeof window !== "undefined") {
                window.history.pushState(null, "", `?${newParams.toString()}`);
            }
            setCompareTo(compareToItemDescriptor);
        }
    }
    const originalSelector = (_jsxs("div", { className: "text-neutral-grey-50 flex flex-1 shrink-0 items-center justify-center gap-1 border-b bg-white p-1 text-sm", children: [_jsx(LanguageSelector, { selectedLanguage: slotContext.itemDescriptor?.language, showAllLanguagesSwitch: false, onLanguageSelected: (language) => {
                    editContext.loadItem({
                        id: slotContext.itemDescriptor.id,
                        language: language.languageCode,
                        version: 0,
                    });
                } }), compareTo?.language && (_jsx(VersionSelector, { readOnly: true, versions: editContext.itemVersions, itemDescriptor: slotContext.itemDescriptor, actualVersion: slotContext.item?.version, showVersionPreviews: slotContext.item?.hasLayout === true, onVersionSelected: (version) => {
                    editContext.loadItem({
                        id: slotContext.itemDescriptor.id,
                        language: slotContext.itemDescriptor.language,
                        version,
                    });
                } }))] }));
    const compareToSelector = (_jsxs("div", { className: "text-neutral-grey-50 flex flex-1 shrink-0 items-center justify-center gap-1 border-b bg-white p-1 text-sm", children: [_jsx(LanguageSelector, { selectedLanguage: compareTo?.language, showAllLanguagesSwitch: false, onLanguageSelected: (language) => {
                    if (!compareTo?.id)
                        return;
                    updateCompareTo({
                        id: compareTo.id,
                        language: language.languageCode,
                        version: compareTo.version,
                    });
                } }), compareTo?.language && (_jsx(VersionSelector, { readOnly: true, versions: compareToVersions, itemDescriptor: compareTo, actualVersion: compareToItem?.version, showVersionPreviews: compareToItem?.hasLayout === true, onVersionSelected: (version) => {
                    if (!compareTo?.id)
                        return;
                    updateCompareTo({
                        id: compareTo.id,
                        language: compareTo.language,
                        version,
                    });
                } }))] }));
    if ((compareToItem && !compareToItem.hasLayout) ||
        comparePageViewContext.device === "")
        return (_jsxs("div", { className: "flex h-full w-full flex-col items-stretch", children: [_jsxs("div", { className: "flex w-full", children: [originalSelector, compareToSelector] }), _jsx("div", { className: "relative flex-1", children: _jsx("div", { "data-view": "item-editor-view", className: "absolute h-full w-full", children: _jsx(ItemEditor, { item: slotContext.item, compareToItem: compareToItem }) }) })] }));
    const panels = [
        {
            defaultSize: "auto",
            name: "original",
            content: (_jsxs("div", { className: "flex h-full w-full flex-col items-stretch", children: [originalSelector, _jsx(SingleEditView, { name: "original", compareView: false, view: "primary", slotCloseButton: !compareTo?.language ? slotCloseButton : undefined }, "original")] })),
        },
        {
            defaultSize: "auto",
            name: "compareTo",
            content: (_jsxs("div", { className: "flex h-full w-full flex-col items-stretch", children: [compareToSelector, compareTo?.language && (_jsx(SingleEditView, { name: "compareTo", compareView: true, view: "compare", slotCloseButton: slotCloseButton }, "compareTo")), !compareTo?.language && (_jsx("div", { className: "flex h-full w-full flex-col items-center justify-center", children: _jsx("div", { className: "text-neutral-grey-50", children: "Select a language and version to compare" }) }))] })),
        },
    ];
    return (_jsx(Splitter, { panels: panels, localStorageKey: "compare-view-splitter", className: "flex h-full w-full" }));
}
//# sourceMappingURL=CompareView.js.map