'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Reference picker - Select and reorder field references for group elements
 * Items are clickable to navigate to the referenced field.
 */
import { useState, useMemo } from 'react';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import { HiPlus, HiTrash, HiArrowUp, HiArrowDown, HiExternalLink } from 'react-icons/hi';
import { parse_element, is_field_element } from '../utils/element_utils.js';
import { format_full_key } from '../utils/key_utils.js';
import { cn } from '../../../utils/cn.js';
export function ReferencePicker({ references, on_change, all_elements, on_navigate_to_field, }) {
    const [picker_open, set_picker_open] = useState(false);
    const [search, set_search] = useState('');
    // Get only field elements as available references
    const available_fields = useMemo(() => {
        return all_elements.filter(record => {
            const data = parse_element(record.element);
            return data !== null && is_field_element(data);
        });
    }, [all_elements]);
    // Field elements not yet referenced
    const unreferenced_fields = useMemo(() => {
        const referenced_keys = new Set(references.map(r => r.key));
        return available_fields.filter(record => {
            const full_key = format_full_key(record.area, record.key);
            return !referenced_keys.has(full_key);
        });
    }, [available_fields, references]);
    // Filtered by search
    const filtered_fields = useMemo(() => {
        if (!search)
            return unreferenced_fields;
        const query = search.toLowerCase();
        return unreferenced_fields.filter(record => {
            const full_key = format_full_key(record.area, record.key);
            const data = parse_element(record.element);
            const label = data?.label?.toLowerCase() ?? '';
            return full_key.toLowerCase().includes(query) || label.includes(query);
        });
    }, [unreferenced_fields, search]);
    // Get label for a reference key
    const get_ref_label = (key) => {
        const record = available_fields.find(r => format_full_key(r.area, r.key) === key);
        if (record) {
            const data = parse_element(record.element);
            return data?.label || key;
        }
        return key;
    };
    const handle_add = (record) => {
        const full_key = format_full_key(record.area, record.key);
        on_change([...references, { key: full_key }]);
        set_picker_open(false);
        set_search('');
    };
    const handle_remove = (index) => {
        on_change(references.filter((_, i) => i !== index));
    };
    const handle_move_up = (index) => {
        if (index === 0)
            return;
        const next = [...references];
        [next[index - 1], next[index]] = [next[index], next[index - 1]];
        on_change(next);
    };
    const handle_move_down = (index) => {
        if (index === references.length - 1)
            return;
        const next = [...references];
        [next[index], next[index + 1]] = [next[index + 1], next[index]];
        on_change(next);
    };
    return (_jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("label", { className: "text-sm font-medium", children: "Fields" }), _jsxs(PopoverPrimitive.Root, { open: picker_open, onOpenChange: set_picker_open, modal: true, children: [_jsx(PopoverPrimitive.Trigger, { asChild: true, children: _jsxs("button", { type: "button", className: "flex items-center gap-1 px-2 py-1 text-xs border rounded hover:bg-muted/50 transition-colors", children: [_jsx(HiPlus, { className: "h-3.5 w-3.5" }), "Add Field"] }) }), _jsx(PopoverPrimitive.Portal, { children: _jsxs(PopoverPrimitive.Content, { align: "end", sideOffset: 4, className: "z-50 w-72 rounded-md border bg-popover p-1 shadow-md", style: { backgroundColor: 'hsl(var(--popover))' }, children: [_jsx("input", { type: "text", value: search, onChange: (e) => set_search(e.target.value), placeholder: "Search fields...", className: "w-full px-2 py-1.5 text-sm border-b outline-none bg-transparent", autoFocus: true }), _jsx("div", { className: "max-h-48 overflow-auto py-1", children: filtered_fields.length === 0 ? (_jsx("div", { className: "px-2 py-4 text-sm text-muted-foreground text-center", children: "No fields available" })) : (filtered_fields.map(record => {
                                                const full_key = format_full_key(record.area, record.key);
                                                const data = parse_element(record.element);
                                                return (_jsxs("button", { onClick: () => handle_add(record), className: "flex flex-col items-start w-full px-2 py-1.5 text-sm rounded-sm hover:bg-accent transition-colors", children: [_jsx("span", { className: "font-medium", children: data?.label || record.key }), _jsx("span", { className: "text-xs text-muted-foreground", children: full_key })] }, record.id));
                                            })) })] }) })] })] }), references.length === 0 ? (_jsx("div", { className: "text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed", children: "No fields. Click \"Add Field\" to add fields from the library." })) : (_jsx("div", { className: "space-y-1", children: references.map((ref, index) => (_jsxs("div", { className: "flex items-center gap-2 p-2 border rounded-md bg-muted/20", children: [_jsx("span", { className: "text-xs text-muted-foreground font-mono w-5 text-center flex-shrink-0", children: index + 1 }), _jsxs("div", { className: cn('flex-1 min-w-0', on_navigate_to_field && 'cursor-pointer hover:text-primary'), onClick: () => on_navigate_to_field?.(ref.key), title: on_navigate_to_field ? 'Click to edit this field' : undefined, children: [_jsxs("div", { className: "text-sm font-medium truncate flex items-center gap-1", children: [get_ref_label(ref.key), on_navigate_to_field && (_jsx(HiExternalLink, { className: "h-3 w-3 opacity-40 flex-shrink-0" }))] }), _jsx("div", { className: "text-xs text-muted-foreground truncate", children: ref.key })] }), _jsxs("div", { className: "flex items-center gap-0.5", children: [_jsx("button", { type: "button", onClick: () => handle_move_up(index), disabled: index === 0, className: cn('p-1 rounded hover:bg-muted transition-colors', index === 0 && 'opacity-30 cursor-not-allowed'), children: _jsx(HiArrowUp, { className: "h-3.5 w-3.5" }) }), _jsx("button", { type: "button", onClick: () => handle_move_down(index), disabled: index === references.length - 1, className: cn('p-1 rounded hover:bg-muted transition-colors', index === references.length - 1 && 'opacity-30 cursor-not-allowed'), children: _jsx(HiArrowDown, { className: "h-3.5 w-3.5" }) }), _jsx("button", { type: "button", onClick: () => handle_remove(index), className: "p-1 rounded hover:bg-destructive/10 text-destructive transition-colors", children: _jsx(HiTrash, { className: "h-3.5 w-3.5" }) })] })] }, `${ref.key}-${index}`))) }))] }));
}
//# sourceMappingURL=reference_picker.js.map