import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import { Plus, Search } from "lucide-react";
import { Button } from "../../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
function formatRuleText(text) {
    if (!text)
        return "";
    // Sitecore rule text uses [varname,Type,Source,Label] placeholders.
    // Render the user-facing label in brackets so the sentence stays readable.
    return text
        .replace(/\[([^\]]+)\]/g, (_match, body) => {
        const parts = body.split(",");
        const label = (parts[3] || parts[0] || "").trim();
        return label ? `[${label}]` : "[…]";
    })
        .replace(/\s+/g, " ")
        .trim();
}
export function RuleElementPicker({ elements, kind, label, onPick, disabled, triggerVariant = "outline", triggerSize = "xs", fullWidth, }) {
    const [open, setOpen] = useState(false);
    const [filter, setFilter] = useState("");
    const inputRef = useRef(null);
    useEffect(() => {
        if (!open) {
            setFilter("");
            return;
        }
        const id = window.setTimeout(() => inputRef.current?.focus(), 30);
        return () => window.clearTimeout(id);
    }, [open]);
    const grouped = useMemo(() => {
        const query = filter.trim().toLowerCase();
        const matching = elements
            .filter((element) => element.kind === kind)
            .filter((element) => {
            if (!query)
                return true;
            return (element.displayName.toLowerCase().includes(query) ||
                element.name.toLowerCase().includes(query) ||
                element.category.toLowerCase().includes(query) ||
                element.text.toLowerCase().includes(query));
        });
        const map = new Map();
        for (const element of matching) {
            const key = element.category || "Other";
            const list = map.get(key) ?? [];
            list.push(element);
            map.set(key, list);
        }
        return Array.from(map.entries())
            .sort(([a], [b]) => a.localeCompare(b))
            .map(([category, items]) => ({
            category,
            items: items
                .slice()
                .sort((a, b) => (a.displayName || a.name).localeCompare(b.displayName || b.name)),
        }));
    }, [elements, filter, kind]);
    return (_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { type: "button", size: triggerSize, variant: triggerVariant, disabled: disabled, className: fullWidth ? "w-full justify-start" : undefined, children: [_jsx(Plus, { className: "size-3" }), label] }) }), _jsxs(PopoverContent, { align: "start", sideOffset: 4, className: "w-[28rem] max-w-[calc(100vw-2rem)] p-0", children: [_jsx("div", { className: "border-border-default border-b p-2", children: _jsxs("div", { className: "relative", children: [_jsx(Search, { className: "text-neutral-grey-50 pointer-events-none absolute top-1/2 left-2 size-3 -translate-y-1/2" }), _jsx("input", { ref: inputRef, type: "text", className: "border-border-default focus:border-component-default w-full rounded border py-1 pr-2 pl-7 text-xs outline-none", placeholder: `Search ${kind}s...`, value: filter, onChange: (event) => setFilter(event.target.value) })] }) }), _jsx("div", { className: "max-h-72 overflow-auto py-1", children: grouped.length === 0 ? (_jsxs("div", { className: "text-2xs text-neutral-grey-50 px-3 py-4 text-center", children: ["No matching ", kind, "s"] })) : (grouped.map((group) => (_jsxs("div", { className: "py-1", children: [_jsx("div", { className: "text-2xs text-neutral-grey-50 px-3 pt-1 pb-1 font-semibold tracking-wide", children: group.category }), group.items.map((element) => {
                                    const sentence = formatRuleText(element.text);
                                    return (_jsxs("button", { type: "button", className: "hover:bg-feedback-blue-light block w-full px-3 py-1.5 text-left", onClick: () => {
                                            onPick(element);
                                            setOpen(false);
                                        }, title: element.text, children: [_jsx("div", { className: "text-neutral-grey-100 text-xs font-medium", children: element.displayName || element.name }), sentence && (_jsx("div", { className: "text-2xs text-neutral-grey-50 mt-0.5 leading-snug", children: sentence }))] }, element.id));
                                })] }, group.category)))) })] })] }));
}
//# sourceMappingURL=RuleElementPicker.js.map