/**
 * Library search component for selecting pre-defined fields from the field library
 * Renders inline inside a dialog tab panel (not as a popover)
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { IoAdd } from 'react-icons/io5';
import { HiFolder, HiDocumentText } from 'react-icons/hi';
import { cn } from '../../../utils/cn.js';
import { use_elements } from '../../hazo_field_library/hooks/use_elements.js';
import { parse_element, is_field_element, is_group_element } from '../../hazo_field_library/utils/element_utils.js';
import { element_to_pending, group_element_to_pending } from '../utils/library_to_pending.js';
import { ADD_FIELD_TYPE_META } from '../types.js';
/**
 * Map component_type to friendly label
 */
function get_type_label(component_type) {
    if (!component_type)
        return 'Text';
    const meta = ADD_FIELD_TYPE_META.find(m => m.type === component_type);
    return meta?.label || component_type.replace('HazoCollabForm', '');
}
/**
 * LibrarySearch - Inline searchable list for selecting library elements
 */
export function LibrarySearch({ api_base_url, table_name, scope_id, filter_mode = 'both', on_select, }) {
    const [search, set_search] = useState('');
    const search_input_ref = useRef(null);
    const { elements, loading, error, fetch_elements } = use_elements({
        api_base_url,
        table_name,
        scope_id,
    });
    // Fetch on mount
    useEffect(() => {
        fetch_elements();
    }, [fetch_elements]);
    // Focus search input on mount
    useEffect(() => {
        search_input_ref.current?.focus();
    }, []);
    // Parse ALL elements (before filtering) - needed for group lookup
    const all_parsed = useMemo(() => {
        const results = [];
        for (const record of elements) {
            const data = parse_element(record.element);
            if (!data)
                continue;
            results.push({ record, data });
        }
        return results;
    }, [elements]);
    // Build field→group lookup: map "area.key" → parent group ParsedRecord
    const field_to_group = useMemo(() => {
        const map = new Map();
        for (const parsed of all_parsed) {
            if (!is_group_element(parsed.data))
                continue;
            const refs = parsed.data.reference_element;
            if (!Array.isArray(refs))
                continue;
            for (const ref of refs) {
                if (ref.key) {
                    map.set(ref.key, parsed);
                }
            }
        }
        return map;
    }, [all_parsed]);
    // Build "area.key" → ParsedRecord lookup for resolving group children
    const element_by_key = useMemo(() => {
        const map = new Map();
        for (const parsed of all_parsed) {
            const full_key = `${parsed.record.area}.${parsed.record.key}`;
            map.set(full_key, parsed);
        }
        return map;
    }, [all_parsed]);
    // Filter by mode
    const parsed_records = useMemo(() => {
        if (filter_mode === 'fields_only') {
            return all_parsed.filter(p => !is_group_element(p.data));
        }
        return all_parsed;
    }, [all_parsed, filter_mode]);
    // Filter by search text
    const filtered_base = useMemo(() => {
        const query = search.trim().toLowerCase();
        if (!query)
            return parsed_records;
        return parsed_records.filter(({ record, data }) => {
            const label = data.label?.toLowerCase() || '';
            const key = record.key.toLowerCase();
            const area = record.area.toLowerCase();
            return label.includes(query) || key.includes(query) || area.includes(query);
        });
    }, [parsed_records, search]);
    // Build final display list: inject parent groups as standalone items for filtered fields
    const filtered = useMemo(() => {
        const existing_ids = new Set(filtered_base.map(p => p.record.id));
        const groups_to_inject = [];
        const seen_group_ids = new Set();
        for (const parsed of filtered_base) {
            if (!is_field_element(parsed.data))
                continue;
            const field_key = `${parsed.record.area}.${parsed.record.key}`;
            const parent = field_to_group.get(field_key);
            if (!parent)
                continue;
            if (existing_ids.has(parent.record.id))
                continue;
            if (seen_group_ids.has(parent.record.id))
                continue;
            seen_group_ids.add(parent.record.id);
            groups_to_inject.push(parent);
        }
        if (groups_to_inject.length === 0)
            return filtered_base;
        return [...groups_to_inject, ...filtered_base];
    }, [filtered_base, field_to_group]);
    const handle_select = useCallback((parsed) => {
        if (is_group_element(parsed.data)) {
            // Resolve child fields from the group's reference_element
            const group_data = parsed.data;
            const resolved_fields = [];
            for (const ref of group_data.reference_element || []) {
                const child = element_by_key.get(ref.key);
                if (child && is_field_element(child.data)) {
                    // Create a copy with a new unique ID
                    const { id: _old_id, ...rest } = child.data;
                    const new_id = `field_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 8)}`;
                    resolved_fields.push({ ...rest, id: new_id });
                }
            }
            const entry = group_element_to_pending(group_data, parsed.record.area, parsed.record.key, resolved_fields);
            on_select(entry);
        }
        else {
            const entry = element_to_pending(parsed.data, parsed.record.area, parsed.record.key);
            if (entry) {
                on_select(entry);
            }
        }
    }, [on_select, element_by_key]);
    return (_jsxs("div", { className: "space-y-2", children: [_jsx("input", { ref: search_input_ref, type: "text", value: search, onChange: (e) => set_search(e.target.value), placeholder: "Search library fields...", className: "cls_library_search_input flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" }), _jsxs("div", { className: "border rounded-md max-h-[200px] overflow-y-auto", children: [loading && (_jsxs("div", { className: "flex items-center justify-center h-20 text-muted-foreground text-sm", children: [_jsxs("svg", { className: "animate-spin h-4 w-4 mr-2", viewBox: "0 0 24 24", children: [_jsx("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4", fill: "none" }), _jsx("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" })] }), "Loading library..."] })), !loading && error && (_jsx("div", { className: "flex items-center justify-center h-20 text-destructive text-sm px-3", children: error })), !loading && !error && filtered.length === 0 && (_jsx("div", { className: "flex items-center justify-center h-20 text-muted-foreground text-sm", children: search ? 'No matching elements found' : 'No library elements found' })), !loading && !error && filtered.length > 0 && (_jsx("div", { className: "divide-y", children: filtered.map(({ record, data }) => {
                            const is_group = is_group_element(data);
                            const is_field = is_field_element(data);
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            const component_label = is_field ? get_type_label(data.component_type) : 'Group';
                            // Find parent group for field elements
                            const field_key = `${record.area}.${record.key}`;
                            const parent_group = is_field ? field_to_group.get(field_key) : undefined;
                            return (_jsxs("button", { type: "button", onClick: () => handle_select({ record, data }), className: cn('cls_library_search_item flex items-center gap-2 w-full px-3 py-2 text-left text-sm overflow-hidden', 'hover:bg-accent hover:text-accent-foreground transition-colors'), children: [is_group ? (_jsx(HiFolder, { className: "h-4 w-4 text-amber-500 flex-shrink-0" })) : (_jsx(HiDocumentText, { className: "h-4 w-4 text-blue-500 flex-shrink-0" })), _jsxs("div", { className: "flex-1 min-w-0 overflow-hidden", children: [_jsxs("div", { className: "flex items-center gap-1.5 min-w-0", children: [_jsx("span", { className: "truncate font-medium", children: data.label || record.key }), parent_group && (_jsxs("span", { role: "link", tabIndex: 0, onClick: (e) => {
                                                            e.stopPropagation();
                                                            handle_select(parent_group);
                                                        }, onKeyDown: (e) => {
                                                            if (e.key === 'Enter' || e.key === ' ') {
                                                                e.stopPropagation();
                                                                e.preventDefault();
                                                                handle_select(parent_group);
                                                            }
                                                        }, className: "inline-flex items-center gap-0.5 text-blue-600 hover:text-blue-800 hover:underline cursor-pointer text-xs whitespace-nowrap flex-shrink-0", title: `Add group: ${parent_group.data.label}`, children: ["(", _jsx(HiFolder, { className: "h-3 w-3 text-amber-500 inline" }), parent_group.data.label, ")"] }))] }), _jsxs("span", { className: "text-xs text-muted-foreground truncate block", children: [record.area, ".", record.key] })] }), _jsx("span", { className: "text-xs text-muted-foreground flex-shrink-0", children: component_label }), _jsx(IoAdd, { className: "h-4 w-4 text-muted-foreground flex-shrink-0" })] }, record.id));
                        }) }))] }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Click a field to add it to the list below" })] }));
}
//# sourceMappingURL=library_search.js.map