/**
 * Autocomplete search component for selecting sections, groups, or fields
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useMemo, useEffect, useRef } from 'react';
import { FaLayerGroup } from 'react-icons/fa';
import { HiFolder, HiDocument } from 'react-icons/hi';
/**
 * FieldAutocomplete - Search and select sections, groups, or fields
 */
export function FieldAutocomplete({ items, selected_group_ids, selected_section_names, on_select, placeholder = 'Search sections, groups, or fields...', }) {
    const [search, set_search] = useState('');
    const [is_dropdown_open, set_is_dropdown_open] = useState(false);
    const [Components, setComponents] = useState(null);
    const [toast_fn, set_toast_fn] = useState(null);
    const container_ref = useRef(null);
    useEffect(() => {
        const loadComponents = async () => {
            try {
                const commandModule = await import('hazo_ui').catch(() => null);
                if (commandModule) {
                    setComponents({
                        Command: commandModule.ShadcnCommand,
                        CommandInput: commandModule.ShadcnCommandInput,
                        CommandList: commandModule.ShadcnCommandList,
                        CommandEmpty: commandModule.ShadcnCommandEmpty,
                        CommandGroup: commandModule.ShadcnCommandGroup,
                        CommandItem: commandModule.ShadcnCommandItem,
                    });
                }
                // Load sonner toast
                const sonnerModule = await import('sonner').catch(() => null);
                if (sonnerModule?.toast) {
                    set_toast_fn(() => sonnerModule.toast);
                }
            }
            catch (error) {
                console.warn('[FieldAutocomplete] Error loading Command components', { error });
            }
        };
        loadComponents();
    }, []);
    // Handle blur/focus lost - close dropdown when clicking outside
    useEffect(() => {
        const handle_click_outside = (event) => {
            if (container_ref.current && !container_ref.current.contains(event.target)) {
                set_is_dropdown_open(false);
            }
        };
        document.addEventListener('mousedown', handle_click_outside);
        return () => document.removeEventListener('mousedown', handle_click_outside);
    }, []);
    // Open dropdown when search has content
    useEffect(() => {
        if (search.trim().length > 0) {
            set_is_dropdown_open(true);
        }
    }, [search]);
    const available_items = useMemo(() => {
        return items.filter(item => {
            // If this item's section is already selected, hide it
            if (selected_section_names.has(item.section_name)) {
                return false;
            }
            switch (item.item_type) {
                case 'section':
                    // Section is available if not already selected
                    return true;
                case 'group':
                    // Group is available if not already selected
                    return !selected_group_ids.has(item.field_config.id);
                case 'field':
                    // Field is hidden if its parent group is already selected
                    if (item.parent_group_id && selected_group_ids.has(item.parent_group_id)) {
                        return false;
                    }
                    return true;
                default:
                    return false;
            }
        });
    }, [items, selected_group_ids, selected_section_names]);
    const filtered_items = useMemo(() => {
        if (!search)
            return [];
        const lower_search = search.toLowerCase();
        return available_items.filter(item => {
            const matches = item.label.toLowerCase().includes(lower_search) ||
                item.section_name.toLowerCase().includes(lower_search);
            if (item.item_type === 'field' && item.parent_group_label) {
                return matches || item.parent_group_label.toLowerCase().includes(lower_search);
            }
            return matches;
        });
    }, [available_items, search]);
    const grouped = useMemo(() => {
        const groups = new Map();
        filtered_items.forEach(item => {
            const existing = groups.get(item.section_name) || [];
            groups.set(item.section_name, [...existing, item]);
        });
        return groups;
    }, [filtered_items]);
    const render_item = (item, CommandItem) => {
        const handle_select = () => {
            on_select(item);
            // Show toast notification
            if (toast_fn) {
                toast_fn(`Added ${item.label}`, { position: 'bottom-center' });
            }
            // Keep dropdown open - don't clear search
        };
        switch (item.item_type) {
            case 'section':
                return (_jsxs(CommandItem, { value: item.search_id, onSelect: handle_select, onClick: handle_select, className: "cursor-pointer", children: [_jsx(FaLayerGroup, { className: "mr-2 h-4 w-4 text-blue-500 flex-shrink-0" }), _jsx("span", { className: "flex-1 truncate font-medium", children: item.label }), _jsxs("span", { className: "ml-2 text-xs text-muted-foreground", children: ["(", item.child_count, " group", item.child_count !== 1 ? 's' : '', ")"] })] }, item.search_id));
            case 'group':
                return (_jsxs(CommandItem, { value: item.search_id, onSelect: handle_select, onClick: handle_select, className: "cursor-pointer", children: [_jsx(HiFolder, { className: "mr-2 h-4 w-4 text-green-600 flex-shrink-0" }), _jsx("span", { className: "flex-1 truncate", children: item.label }), _jsxs("span", { className: "ml-2 text-xs text-muted-foreground", children: ["(", item.child_count, " field", item.child_count !== 1 ? 's' : '', ")"] })] }, item.search_id));
            case 'field':
                return (_jsxs(CommandItem, { value: item.search_id, onSelect: handle_select, onClick: handle_select, className: "cursor-pointer", children: [_jsx(HiDocument, { className: "mr-2 h-4 w-4 text-gray-500 flex-shrink-0" }), _jsxs("div", { className: "flex flex-col flex-1 min-w-0", children: [_jsx("span", { className: "truncate", children: item.label }), _jsxs("span", { className: "text-xs text-muted-foreground truncate", children: ["in \"", item.parent_group_label, "\""] })] })] }, item.search_id));
            default:
                return null;
        }
    };
    if (!Components) {
        return (_jsx("div", { className: "rounded-lg border bg-background p-4 text-sm text-muted-foreground", children: "Loading search..." }));
    }
    const { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } = Components;
    const show_dropdown = is_dropdown_open && search.trim().length > 0;
    return (_jsx("div", { className: "relative", ref: container_ref, children: _jsxs(Command, { className: "rounded-lg border shadow-sm", shouldFilter: false, children: [_jsx(CommandInput, { placeholder: placeholder, value: search, onValueChange: set_search }), show_dropdown && (_jsxs(CommandList, { className: "absolute left-0 right-0 top-full z-50 mt-1 max-h-[300px] rounded-lg border bg-popover shadow-lg overflow-y-auto", children: [_jsx(CommandEmpty, { children: "No matching items found." }), Array.from(grouped.entries()).map(([section_name, section_items]) => (_jsx(CommandGroup, { heading: section_name, children: section_items.map(item => render_item(item, CommandItem)) }, section_name)))] }))] }) }));
}
//# sourceMappingURL=field_autocomplete.js.map