import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useEditContext } from "../client/editContext";
import { toast } from "sonner";
import { useDebouncedCallback } from "use-debounce";
import { FilterInput } from "../../components/FilterInput";
import { ScrollingContentTree } from "../ScrollingContentTree";
import { HomeButton } from "../ui/HomeButton";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { executeSearch } from "../services/searchService";
import { ItemList } from "../ui/ItemList";
import { History, FolderTree } from "lucide-react";
import { GUID_REGEX_EXACT } from "../utils";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
export function PageSelector({ itemDescriptor, }) {
    const editContext = useEditContext();
    const [item, setItem] = useState();
    const [showHistory, setShowHistory] = useState(false);
    const [hoveredItem, setHoveredItem] = useState();
    const [query, setQuery] = useState("");
    const [searchResults, setSearchResults] = useState([]);
    const [historyResults, setHistoryResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const inputRef = useRef(null);
    const loadItem = (selectedItem) => {
        if (Array.isArray(selectedItem) && selectedItem[0]) {
            selectedItem = selectedItem[0];
        }
        if (!selectedItem)
            return;
        const itemDescriptor = selectedItem;
        editContext?.loadItem({
            id: itemDescriptor.id,
            language: itemDescriptor.language,
            version: 0, // Always select the latest version when switching items
        });
        setOpen(false);
    };
    const handleSearch = useDebouncedCallback(async (searchPrompt) => {
        if (!editContext || !searchPrompt) {
            setSearchResults([]);
            setLoading(false);
            return;
        }
        setLoading(true);
        const trimmedPrompt = searchPrompt.trim();
        const currentQuery = searchPrompt;
        // Try a direct GUID lookup first, but fall back to normal search if it doesn't resolve.
        if (GUID_REGEX_EXACT.test(trimmedPrompt)) {
            const normalizedGuid = trimmedPrompt.replace(/[{}()]/g, "");
            const item = await editContext.itemsRepository.getItem({
                id: normalizedGuid,
                language: "en",
                version: 0,
            });
            if (item) {
                if (query === currentQuery) {
                    const resultItem = {
                        id: item.id,
                        name: item.name,
                        language: item.language || "en",
                        icon: item.icon,
                        path: item.path || item.name,
                        idPath: item.idPath,
                    };
                    setSearchResults([resultItem]);
                }
                setLoading(false);
                return;
            }
        }
        // Regular search
        const result = await executeSearch({
            index: "master",
            query: trimmedPrompt,
            editContext,
            maxResults: 5,
        });
        if (query === currentQuery) {
            if (result.type == "success") {
                setSearchResults(result.data);
            }
            else {
                toast.error(result.response.statusText || "Error searching");
                setSearchResults([]);
            }
        }
        setLoading(false);
    }, 600);
    // Filter history results based on query
    const filterHistory = useDebouncedCallback((filterQuery, allHistory) => {
        if (!filterQuery) {
            setHistoryResults([]);
            return;
        }
        const filtered = allHistory.filter((item) => item.name.toLowerCase().includes(filterQuery.toLowerCase()) ||
            item.path.toLowerCase().includes(filterQuery.toLowerCase()));
        // Sort by visitedAt DESC (most recent first)
        const sorted = filtered.sort((a, b) => {
            const dateA = a.visitedAt ? new Date(a.visitedAt).getTime() : 0;
            const dateB = b.visitedAt ? new Date(b.visitedAt).getTime() : 0;
            return dateB - dateA; // DESC order (most recent first)
        });
        setHistoryResults(sorted.slice(0, 6)); // Limit to 6 results
    }, 300);
    useEffect(() => {
        if (query) {
            setLoading(true);
            if (showHistory) {
                // In history mode, use actual history data from editContext
                const allHistoryItems = editContext?.browseHistory || [];
                filterHistory(query, allHistoryItems);
                setLoading(false);
            }
            else {
                handleSearch(query);
            }
        }
        else {
            setSearchResults([]);
            if (showHistory) {
                // Show complete history when query is empty in history mode
                // Sort by visitedAt DESC (most recent first)
                const historyToSet = [...(editContext?.browseHistory || [])].sort((a, b) => {
                    const dateA = a.visitedAt ? new Date(a.visitedAt).getTime() : 0;
                    const dateB = b.visitedAt ? new Date(b.visitedAt).getTime() : 0;
                    return dateB - dateA; // DESC order (most recent first)
                });
                setHistoryResults(historyToSet);
            }
            else {
                setHistoryResults([]);
            }
            setLoading(false);
        }
    }, [query, showHistory, editContext?.browseHistory]);
    useEffect(() => {
        const setName = async () => {
            if (!itemDescriptor || !editContext) {
                setItem(undefined);
                setHoveredItem(undefined);
                return;
            }
            const item = await editContext.itemsRepository.getItem(itemDescriptor);
            setItem(item);
            setHoveredItem(undefined);
        };
        setName();
    }, [itemDescriptor, editContext]);
    // Subscribe to item changes to update the displayed name when the item is renamed
    useEffect(() => {
        if (!editContext?.itemsRepository || !itemDescriptor)
            return;
        const unsubscribe = editContext.itemsRepository.subscribeItemsChanged(async (changes) => {
            // Check if the current item was updated (e.g., renamed)
            // Match by ID and language, and check if properties changed
            const currentItemChanged = changes.some((change) => change.item.id === itemDescriptor.id &&
                change.item.language === itemDescriptor.language &&
                (change.action === "update" || change.action === "add") &&
                change.changes.properties === true);
            if (currentItemChanged) {
                // Re-fetch the item to get the updated name
                // This will get the updated item from cache or fetch it if needed
                const updatedItem = await editContext.itemsRepository.getItem(itemDescriptor);
                if (updatedItem) {
                    setItem(updatedItem);
                }
            }
        });
        return unsubscribe;
    }, [editContext?.itemsRepository, itemDescriptor]);
    useEffect(() => {
        if (inputRef.current && open) {
            inputRef.current.focus();
        }
    }, [open, showHistory]);
    if (!editContext)
        return null;
    const currentResults = showHistory ? historyResults : searchResults;
    const hasResults = currentResults.length > 0;
    return (_jsxs("div", { className: "flex min-w-0 items-center gap-1", children: [editContext.isMobile && (_jsx(HomeButton, { size: 28, className: "flex shrink-0 items-center justify-center" })), _jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("div", { id: "page-selector-button", className: "text-dark text-sm0 flex w-full max-w-full min-w-0 cursor-pointer items-center gap-3 rounded-md px-2 py-1 md:py-2", "data-testid": "page-selector-button", children: _jsxs("div", { className: "flex min-w-0 flex-col", children: [_jsx("div", { className: "truncate text-sm font-medium", "data-testid": "item-name", children: item?.name || "Select a page..." }), !editContext.isMobile && (_jsx("div", { className: "truncate text-xs text-gray-500", children: item?.path || "" }))] }) }) }), _jsx(PopoverContent, { className: "w-[calc(100vw-1rem)] max-w-96 p-0 md:w-96", align: editContext.isMobile ? "center" : "start", collisionPadding: 8, "data-testid": "page-selector-popover", onInteractOutside: (e) => {
                            const target = e.target;
                            if (target && target.closest('[data-help-panel="true"]')) {
                                e.preventDefault();
                            }
                        }, onPointerDownOutside: (e) => {
                            const target = e.target;
                            if (target && target.closest('[data-help-panel="true"]')) {
                                e.preventDefault();
                            }
                        }, onFocusOutside: (e) => {
                            const target = e.target;
                            if (target && target.closest('[data-help-panel="true"]')) {
                                e.preventDefault();
                            }
                        }, children: _jsxs("div", { className: "flex h-[75vh] max-h-[600px] w-full max-w-96 flex-col overflow-hidden md:min-w-96", "data-testid": "page-selector-content", children: [_jsxs("div", { className: "flex items-center gap-2 border-b border-gray-200 p-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(FilterInput, { value: query, onChange: setQuery, ref: inputRef, placeholder: showHistory ? "Filter history..." : "Search content...", loading: loading, className: "w-full", spinnerStyle: { width: "18px", height: "18px" } }) }), _jsxs("div", { className: "flex shrink-0 gap-1", children: [_jsx(SimpleIconButton, { icon: _jsx(FolderTree, { className: "h-4 w-4", strokeWidth: 1 }), label: "Search Content", selected: !showHistory, onClick: () => setShowHistory(false), size: "small", "data-testid": "page-selector-search-toggle" }), _jsx(SimpleIconButton, { icon: _jsx(History, { className: "h-4 w-4", strokeWidth: 1 }), label: "Filter History", selected: showHistory, onClick: () => setShowHistory(true), size: "small", "data-testid": "page-selector-history-toggle" })] })] }), _jsxs("div", { className: "flex flex-1 flex-col overflow-hidden", children: [hasResults && (_jsx("div", { className: "max-h-[50%] shrink-0 overflow-auto border-b border-gray-200", children: _jsx("div", { className: "p-2", children: _jsx(ItemList, { items: currentResults, onItemHover: setHoveredItem, onItemClick: loadItem, maxItems: 20, className: "max-h-full overflow-auto" }) }) })), _jsx("div", { className: "relative min-h-0 flex-1", children: _jsx("div", { className: "absolute inset-0 overflow-auto", children: _jsx(ScrollingContentTree, { hideRootNodes: true, selectedItemId: hoveredItem?.id ?? item?.id, onSelectionChange: loadItem }) }) })] })] }) })] })] }));
}
//# sourceMappingURL=PageSelector.js.map