import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useEffect, useState, useRef } from "react";
import { Dialog, DialogContent, DialogTitle } from "../components/ui/dialog";
import { cn } from "../lib/utils";
import { useEditContext } from "./client/editContext";
import { usePageViewContext } from "./page-viewer/pageViewContext";
import { getAbsoluteIconUrl } from "./utils";
// Helper to determine if a workspace shows EditView as main content
function workspaceShowsEditView(workspaceId) {
    // Workspaces that show EditView: editor workspace (with various sidebars)
    const editWorkspaceIds = ["editor"];
    return editWorkspaceIds.includes(workspaceId);
}
// Skeleton placeholder for non-EditView previews
const SkeletonPreview = () => (_jsxs("div", { className: "h-full w-full animate-pulse bg-gray-100 p-4", children: [_jsx("div", { className: "mb-2 h-4 rounded bg-gray-300" }), _jsx("div", { className: "mb-2 h-4 w-3/4 rounded bg-gray-300" }), _jsx("div", { className: "h-4 w-1/2 rounded bg-gray-300" })] }));
export function QuickItemSwitcher({ visible, entries, selectedIndex, onSelect, onClose, }) {
    const editContext = useEditContext();
    // Track which cards have been selected/visited to enable their previews
    // This prevents rendering all previews at once which causes update loops
    const [visitedIndices, setVisitedIndices] = useState(new Set([0, 1]));
    const prevVisibleRef = useRef(visible);
    // Reset visited indices when dialog opens
    useEffect(() => {
        if (visible && !prevVisibleRef.current) {
            // Dialog just opened - reset to only show first two previews initially
            setVisitedIndices(new Set([0, 1]));
        }
        prevVisibleRef.current = visible;
    }, [visible]);
    // Mark selected index as visited when it changes
    useEffect(() => {
        if (visible && selectedIndex >= 0) {
            setVisitedIndices((prev) => {
                if (prev.has(selectedIndex))
                    return prev;
                const next = new Set(prev);
                next.add(selectedIndex);
                return next;
            });
        }
    }, [selectedIndex, visible]);
    // Scroll selected entry into view
    useEffect(() => {
        if (visible && selectedIndex >= 0) {
            const element = document.querySelector(`[data-switcher-index="${selectedIndex}"]`);
            element?.scrollIntoView({
                behavior: "smooth",
                block: "nearest",
                inline: "center",
            });
        }
    }, [selectedIndex, visible]);
    // Early returns must come after all hooks
    if (!editContext)
        return null;
    if (!visible || entries.length === 0)
        return null;
    const handleOpenChange = (open) => {
        if (!open) {
            onClose();
        }
    };
    return (_jsx(Dialog, { open: visible, onOpenChange: handleOpenChange, children: _jsxs(DialogContent, { className: "max-h-[85vh] max-w-[90vw] gap-0 p-0", overlayClassName: "bg-black/60", showCloseButton: false, children: [_jsx(DialogTitle, { className: "sr-only", children: "Navigation History" }), _jsxs("div", { className: "flex flex-col gap-7 p-6", children: [_jsx("div", { className: "text-center text-sm text-gray-600", children: "Navigation History (Live Previews) \u2022 Hold Ctrl, tap Q to navigate \u2022 Release Ctrl to select \u2022 Escape to cancel" }), _jsx("div", { className: "grid grid-cols-2 gap-5 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5", children: entries.map((entry, index) => {
                                const isSelected = index === selectedIndex;
                                return (_jsxs("div", { "data-switcher-index": index, className: cn("flex cursor-pointer flex-col items-center gap-2 rounded-lg border p-3 transition-all", isSelected
                                        ? "scale-105 shadow-2xl"
                                        : "border-gray-200 bg-white hover:bg-gray-50"), style: isSelected
                                        ? {
                                            backgroundColor: "var(--color-theme-secondary-light)",
                                            boxShadow: "0 0 0 4px var(--color-theme-secondary-light)",
                                        }
                                        : undefined, onClick: () => onSelect(index), children: [_jsx("div", { className: cn("relative w-full overflow-hidden rounded border-2 bg-white transition-all", isSelected ? "" : "border-gray-500"), style: isSelected
                                                ? {
                                                    height: "200px",
                                                    borderColor: "var(--color-theme-secondary-light)",
                                                }
                                                : { height: "200px" }, children: visitedIndices.has(index) ? (_jsx(CardPreview, { entry: entry, itemsRepository: editContext.itemsRepository, configuration: editContext.configuration })) : (_jsx(SkeletonPreview, {})) }), _jsxs("div", { className: "flex w-full flex-col gap-1", children: [_jsxs("div", { className: "flex w-full items-center gap-2", children: [workspaceShowsEditView(entry.workspaceId) &&
                                                            entry.item &&
                                                            entry.itemIcon && (_jsx("img", { src: getAbsoluteIconUrl(entry.itemIcon), alt: "", className: "shrink-0", style: { height: "16px", width: "16px" } })), _jsx("div", { className: cn("flex-1 truncate text-sm font-medium", "text-gray-900"), title: entry.displayName, children: entry.displayName })] }), workspaceShowsEditView(entry.workspaceId) &&
                                                    entry.item &&
                                                    entry.itemPath && (_jsx("div", { className: cn("w-full truncate text-xs", "text-gray-600"), title: entry.itemPath, children: entry.itemPath }))] })] }, `${entry.workspaceId}-${entry.item?.id || "noitem"}-${index}`));
                            }) })] })] }) }));
}
const CardPreview = React.memo(function CardPreview({ entry, itemsRepository, configuration, }) {
    if (!entry.item || !workspaceShowsEditView(entry.workspaceId)) {
        return _jsx(SkeletonPreview, {});
    }
    return (_jsx(CardPreviewFrame, { entry: entry, itemsRepository: itemsRepository, configuration: configuration }));
});
function CardPreviewFrame({ entry, itemsRepository, configuration, }) {
    const descriptor = entry.item
        ? {
            id: entry.item.id,
            language: entry.item.language,
            version: entry.item.version,
        }
        : undefined;
    const pageView = usePageViewContext({
        pageItemDescriptor: descriptor,
        itemsRepository,
        configuration,
    });
    const previewSrc = pageView.previewUrl || pageView.editUrl;
    if (!previewSrc) {
        return _jsx(SkeletonPreview, {});
    }
    return (_jsx("div", { className: "pointer-events-none absolute top-0 left-0 h-full w-full overflow-hidden bg-white select-none", "aria-hidden": "true", children: _jsx("iframe", { title: entry.displayName, src: previewSrc, tabIndex: -1, loading: "eager", className: "h-full w-full border-0" }, previewSrc) }));
}
//# sourceMappingURL=QuickItemSwitcher.js.map