import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { cn } from "../../lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { useEditContext } from "../../editor/client/editContext";
import { X, ChevronDown } from "lucide-react";
import { TreeListSelector } from "../../editor/ui/TreeListSelector";
/**
 * Item selector component for placeholder inputs
 * Allows selecting a Sitecore item via search or tree browsing
 */
export const PlaceholderItemSelector = ({ placeholder, value, onChange, onKeyDown, inputRef }) => {
    const [isOpen, setIsOpen] = React.useState(false);
    const [selectedItem, setSelectedItem] = React.useState(null);
    const [rootItemId, setRootItemId] = React.useState(null);
    const [isLoadingRoot, setIsLoadingRoot] = React.useState(false);
    const editContext = useEditContext();
    // Parse root parameter from placeholder.parameters
    const rootPathOrId = placeholder.parameters.root || "/sitecore/content";
    // Helper to check if a string is a GUID
    const isGuid = (str) => {
        const guidPattern = /^[{]?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}[}]?$/;
        return guidPattern.test(str);
    };
    // Resolve root path/ID to an item ID on mount
    React.useEffect(() => {
        const resolveRootItem = async () => {
            if (!editContext)
                return;
            // If it's already a GUID, use it directly
            if (isGuid(rootPathOrId)) {
                setRootItemId(rootPathOrId.replace(/[{}]/g, ""));
                return;
            }
            // Otherwise, resolve the path to an ID
            setIsLoadingRoot(true);
            try {
                const item = await editContext.itemsRepository.getItem({
                    id: rootPathOrId, // Try as ID first
                    language: "en",
                    version: 0,
                });
                if (item?.id) {
                    setRootItemId(item.id);
                }
                else {
                    // If not found by ID, it might be a path - we need to search for it
                    console.error("Could not resolve root item:", rootPathOrId);
                    // Fallback to Sitecore content root
                    setRootItemId("0DE95AE4-41AB-4D01-9EB0-67441B7C2450");
                }
            }
            catch (error) {
                console.error("Error resolving root item:", error);
                // Fallback to Sitecore content root
                setRootItemId("0DE95AE4-41AB-4D01-9EB0-67441B7C2450");
            }
            finally {
                setIsLoadingRoot(false);
            }
        };
        resolveRootItem();
    }, [editContext, rootPathOrId]);
    const loadItemByIdOrPath = React.useCallback(async (idOrPath) => {
        if (!editContext)
            return;
        try {
            const item = await editContext.itemsRepository.getItem({
                id: idOrPath,
                language: "en",
                version: 0,
            });
            if (item) {
                setSelectedItem({
                    id: item.id,
                    path: item.path || item.name,
                    name: item.name,
                    language: "en",
                    icon: item.icon,
                });
                const newValue = `${item.id}|${item.path || item.name}`;
                onChange(newValue);
            }
        }
        catch (error) {
            console.error("Failed to load item:", error);
        }
    }, [editContext, onChange]);
    // Parse existing value (format: "id|path")
    React.useEffect(() => {
        if (!value || !editContext)
            return;
        if (value.includes("|")) {
            const [id, path] = value.split("|");
            const name = path?.split("/").pop() || "";
            setSelectedItem({ id: id || "", path: path || "", name, language: "en" });
        }
        else {
            // Try to load item by ID or path
            loadItemByIdOrPath(value);
        }
    }, [value, editContext, loadItemByIdOrPath]);
    const handleItemSelected = (item) => {
        const resultItem = {
            id: item.id,
            name: item.name || "",
            path: item.path || "",
            language: item.language || "en",
            icon: item.icon,
            idPath: item.idPath,
        };
        setSelectedItem(resultItem);
        const newValue = `${resultItem.id}|${resultItem.path}`;
        onChange(newValue);
        setIsOpen(false);
    };
    const handleClear = (e) => {
        e.stopPropagation();
        setSelectedItem(null);
        onChange("");
    };
    const displayValue = selectedItem ? selectedItem.path : "";
    // Don't render until root is resolved
    if (isLoadingRoot || !rootItemId) {
        return (_jsx("div", { ref: inputRef, className: "border-border-default inline-flex h-6 max-w-[260px] min-w-[120px] items-center gap-1 rounded-md border bg-white/80 px-2 text-xs", children: _jsx("span", { className: "text-neutral-grey-50 flex-1", children: "Loading..." }) }));
    }
    return (_jsxs(Popover, { open: isOpen, onOpenChange: setIsOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("div", { ref: inputRef, tabIndex: 0, onKeyDown: onKeyDown, className: cn("border-feedback-blue inline-flex h-6 max-w-[260px] min-w-[120px] cursor-pointer items-center gap-1 rounded-md border bg-white/90 px-2 text-xs transition-colors outline-none", "hover:border-feedback-blue hover:bg-white", "focus:border-feedback-blue focus:ring-feedback-blue/15 focus:bg-white focus:ring-2"), children: selectedItem ? (_jsxs(_Fragment, { children: [selectedItem.icon && (_jsx("img", { src: selectedItem.icon, alt: "", className: "h-3 w-3 flex-shrink-0" })), _jsx("span", { className: "flex-1 truncate", children: displayValue }), _jsx("button", { onClick: handleClear, className: "hover:bg-feedback-blue-light rounded p-0.5", title: "Clear selection", children: _jsx(X, { strokeWidth: 1, size: 12 }) })] })) : (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-feedback-blue flex-1", children: placeholder.name }), _jsx(ChevronDown, { strokeWidth: 1, size: 12, className: "text-feedback-blue" })] })) }) }), _jsx(PopoverContent, { className: "w-[260px] p-0", align: "start", onOpenAutoFocus: (e) => e.preventDefault(), children: _jsx("div", { className: "h-[450px]", children: _jsx(TreeListSelector, { rootItemIds: [rootItemId], selectionMode: "single", selectedItemIds: selectedItem ? [selectedItem.id] : [], onSelectionChange: (selection) => {
                            const node = selection[0];
                            if (node) {
                                handleItemSelected({
                                    id: node.id,
                                    name: node.name,
                                    path: node.path || node.name,
                                    language: "en",
                                    version: 0,
                                    icon: node.icon,
                                });
                            }
                        }, onItemSelected: handleItemSelected, language: "en", searchAutoFocus: true }) }) })] }));
};
//# sourceMappingURL=PlaceholderItemSelector.js.map