import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { getInsertOptionsForCurrentSelection } from "../utils/insertOptions";
import { ArrowDownIcon } from "../ui/Icons";
import { getAbsoluteIconUrl, useCollapsedSections } from "../utils";
import { cn } from "../../lib/utils";
import { sanitizeSvg } from "../../lib/sanitize";
import { useEditContext } from "../client/editContext";
import { FilterInput, highlightMatch } from "../../components/FilterInput";
import { useState, useRef, useEffect } from "react";
import { AlertTriangle } from "lucide-react";
export function ComponentPalette({}) {
    const editContext = useEditContext();
    const [filter, setFilter] = useState("");
    const filterRef = useRef(null);
    const { isSectionCollapsed, toggleSection } = useCollapsedSections();
    const insertOptions = getInsertOptionsForCurrentSelection(editContext);
    // Auto-focus filter input when typing
    useEffect(() => {
        function handleKeyDown(event) {
            // Only handle if the filter input is not already focused
            if (document.activeElement === filterRef.current) {
                return;
            }
            // Don't steal focus if user is typing in an input field, textarea, or contenteditable element
            const activeElement = document.activeElement;
            if (activeElement &&
                (activeElement.tagName === "INPUT" ||
                    activeElement.tagName === "TEXTAREA" ||
                    activeElement.isContentEditable)) {
                return;
            }
            // Only handle printable characters (not special keys like arrows, escape, etc.)
            if (event.key.length === 1 &&
                !event.ctrlKey &&
                !event.metaKey &&
                !event.altKey) {
                // Focus the filter input
                filterRef.current?.focus();
                // Clear current filter and set to the typed character
                setFilter(event.key);
                // Prevent the default action to avoid any other handlers
                event.preventDefault();
            }
        }
        // Add event listener to the document
        document.addEventListener("keydown", handleKeyDown);
        // Cleanup
        return () => {
            document.removeEventListener("keydown", handleKeyDown);
        };
    }, []);
    const insertOptionsByGroup = insertOptions.reduce((acc, value) => {
        const group = value.group || "Other";
        if (!acc[group]) {
            acc[group] = [];
        }
        acc[group].push(value);
        return acc;
    }, {});
    return (_jsxs("div", { className: "tour-component-palette relative flex h-full flex-col", "data-testid": "component-palette", children: [_jsx("div", { className: "p-4", children: _jsx(FilterInput, { ref: filterRef, value: filter, onChange: setFilter, className: "border-border-default", placeholder: "Filter..." }) }), _jsx("div", { className: "relative flex-1", children: _jsx("div", { className: "absolute inset-0 overflow-y-auto", children: Object.keys(insertOptionsByGroup)
                        .sort()
                        .map((group, index) => {
                        const options = insertOptionsByGroup[group].filter((x) => !x.isHidden).filter((x) => x.name.toLowerCase().indexOf(filter.toLowerCase()) > -1);
                        if (options.length === 0)
                            return;
                        const isCollapsed = isSectionCollapsed(`palette.${group}`);
                        return (_jsxs("div", { className: cn("m-4", index > 0 ? "border-border-default border-t" : ""), children: [_jsxs("div", { className: "mt-2 mb-3 flex cursor-pointer items-center gap-2 text-xs font-bold select-none", onClick: () => toggleSection(`palette.${group}`), children: [_jsx(ArrowDownIcon, { className: cn("transition-transform", isCollapsed ? "-rotate-90" : "") }), " ", group] }), !isCollapsed && (_jsx("div", { className: "grid grid-cols-[repeat(auto-fill,_minmax(70px,_1fr))] gap-4", children: options.map((option) => {
                                        function handleDragStart(event) {
                                            editContext?.dragStart({
                                                type: "template",
                                                typeId: option.typeId,
                                                name: option.name,
                                            });
                                            // Set the drag image to the entire card element
                                            const cardElement = event.currentTarget;
                                            event.dataTransfer.setDragImage(cardElement, 0, 0);
                                            event.stopPropagation();
                                        }
                                        function handleDragEnd() {
                                            editContext.dragEnd();
                                            editContext.setSelectedForInsertion("");
                                        }
                                        const isDraggable = !option.isInvalid;
                                        return (_jsxs("div", { id: "insert-component-" + option.typeId, onClick: () => {
                                                editContext.setSelectedForInsertion(option.typeId);
                                            }, draggable: isDraggable, onDragStart: handleDragStart, onDragEnd: handleDragEnd, className: cn("border-border-default relative flex flex-col items-center justify-center gap-2 rounded border p-2 text-center text-xs break-all", isDraggable ? "cursor-grab" : "", editContext.selectedForInsertion === option.typeId
                                                ? "border-feedback-blue"
                                                : ""), "data-testid": "insert-component-option", children: [option.svg && (_jsx("div", { className: "h-8 w-8", draggable: false, onDragStart: (e) => e.preventDefault(), dangerouslySetInnerHTML: {
                                                        __html: sanitizeSvg(option.svg),
                                                    } })), !option.svg && (_jsx("img", { src: getAbsoluteIconUrl(option.thumbnail || option.icon), draggable: false, onDragStart: (e) => e.preventDefault() })), _jsx("div", { className: "text-xs", children: highlightMatch(option.name, filter) }), option.isInvalid && (_jsx("span", { title: option.message, children: _jsx(AlertTriangle, { className: "text-feedback-red absolute top-0 right-0 h-4 w-4" }) }))] }, option.typeId));
                                    }) }))] }, group));
                    }) }) })] }));
}
//# sourceMappingURL=ComponentPalette.js.map