'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Element list - Left panel: elements grouped by area with drag-and-drop
 */
import { useState, useMemo, useCallback, useRef } from 'react';
import { HiSearch, HiDocument, HiFolder, HiChevronDown, HiChevronRight } from 'react-icons/hi';
import { useFieldLibrary } from '../context.js';
import { parse_element, is_group_element } from '../utils/element_utils.js';
import { format_full_key } from '../utils/key_utils.js';
import { cn } from '../../../utils/cn.js';
export function ElementList() {
    const { filtered_elements, selected_id, set_selected_id, search_query, set_search_query, elements: { loading, update_element }, } = useFieldLibrary();
    const [collapsed_areas, set_collapsed_areas] = useState(new Set());
    const [drag_element_id, set_drag_element_id] = useState(null);
    const [drop_target_area, set_drop_target_area] = useState(null);
    const drag_counter_ref = useRef({});
    // Group elements by area
    const grouped = useMemo(() => {
        const groups = {};
        for (const record of filtered_elements) {
            if (!groups[record.area])
                groups[record.area] = [];
            groups[record.area].push(record);
        }
        // Sort area keys
        const sorted_areas = Object.keys(groups).sort();
        return sorted_areas.map(area => ({ area, elements: groups[area] }));
    }, [filtered_elements]);
    const toggle_area = useCallback((area) => {
        set_collapsed_areas(prev => {
            const next = new Set(prev);
            if (next.has(area))
                next.delete(area);
            else
                next.add(area);
            return next;
        });
    }, []);
    // --- Drag and drop handlers ---
    const handle_drag_start = useCallback((e, record) => {
        set_drag_element_id(record.id);
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', record.id);
    }, []);
    const handle_drag_end = useCallback(() => {
        set_drag_element_id(null);
        set_drop_target_area(null);
        drag_counter_ref.current = {};
    }, []);
    const handle_area_drag_enter = useCallback((e, area) => {
        e.preventDefault();
        if (!drag_counter_ref.current[area])
            drag_counter_ref.current[area] = 0;
        drag_counter_ref.current[area]++;
        set_drop_target_area(area);
    }, []);
    const handle_area_drag_leave = useCallback((area) => {
        if (!drag_counter_ref.current[area])
            drag_counter_ref.current[area] = 0;
        drag_counter_ref.current[area]--;
        if (drag_counter_ref.current[area] <= 0) {
            drag_counter_ref.current[area] = 0;
            set_drop_target_area(prev => prev === area ? null : prev);
        }
    }, []);
    const handle_area_drag_over = useCallback((e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
    }, []);
    const handle_area_drop = useCallback(async (e, target_area) => {
        e.preventDefault();
        const element_id = e.dataTransfer.getData('text/plain');
        set_drag_element_id(null);
        set_drop_target_area(null);
        drag_counter_ref.current = {};
        if (!element_id)
            return;
        // Find the dragged element
        const record = filtered_elements.find(r => r.id === element_id);
        if (!record || record.area === target_area)
            return;
        // Update the element's area
        await update_element(record.id, { area: target_area });
    }, [filtered_elements, update_element]);
    return (_jsxs("div", { className: "flex flex-col h-full", children: [_jsx("div", { className: "p-3 border-b", children: _jsxs("div", { className: "relative", children: [_jsx(HiSearch, { className: "absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" }), _jsx("input", { type: "text", value: search_query, onChange: (e) => set_search_query(e.target.value), placeholder: "Search elements...", className: "w-full pl-8 pr-3 py-1.5 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50" })] }) }), _jsx("div", { className: "flex-1 overflow-auto", children: loading ? (_jsx("div", { className: "text-sm text-muted-foreground text-center py-8", children: "Loading..." })) : grouped.length === 0 ? (_jsx("div", { className: "text-sm text-muted-foreground text-center py-8", children: "No elements found" })) : (grouped.map(({ area, elements: area_elements }) => {
                    const is_collapsed = collapsed_areas.has(area);
                    const is_drop_target = drop_target_area === area && drag_element_id !== null;
                    // Check if the dragged element is from a different area
                    const dragged_record = drag_element_id ? filtered_elements.find(r => r.id === drag_element_id) : null;
                    const is_valid_drop = is_drop_target && dragged_record && dragged_record.area !== area;
                    return (_jsxs("div", { onDragEnter: (e) => handle_area_drag_enter(e, area), onDragLeave: () => handle_area_drag_leave(area), onDragOver: handle_area_drag_over, onDrop: (e) => handle_area_drop(e, area), children: [_jsxs("button", { onClick: () => toggle_area(area), className: cn('w-full flex items-center gap-1.5 px-3 py-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground hover:bg-muted/50 transition-colors border-b border-l-3 border-l-primary/40 sticky top-0 bg-slate-50/95 dark:bg-slate-900/95 backdrop-blur-sm z-10', is_valid_drop && 'bg-primary/10 border-primary/30'), children: [is_collapsed
                                        ? _jsx(HiChevronRight, { className: "h-3.5 w-3.5 flex-shrink-0" })
                                        : _jsx(HiChevronDown, { className: "h-3.5 w-3.5 flex-shrink-0" }), _jsx("span", { className: "flex-1 text-left truncate", children: area.replace(/_/g, ' ') }), _jsx("span", { className: "text-[10px] font-normal tabular-nums", children: area_elements.length })] }), !is_collapsed && (_jsx("div", { className: cn('p-1 space-y-0.5', is_valid_drop && 'bg-primary/5'), children: area_elements.map(record => {
                                    const data = parse_element(record.element);
                                    const is_group = data ? is_group_element(data) : false;
                                    const full_key = format_full_key(record.area, record.key);
                                    const is_selected = selected_id === record.id;
                                    const is_dragging = drag_element_id === record.id;
                                    return (_jsxs("button", { onClick: () => set_selected_id(record.id), draggable: true, onDragStart: (e) => handle_drag_start(e, record), onDragEnd: handle_drag_end, className: cn('w-full flex items-start gap-2 px-2.5 py-2 rounded-md text-left transition-colors cursor-grab active:cursor-grabbing', is_selected
                                            ? 'bg-primary text-primary-foreground'
                                            : 'hover:bg-muted/50', is_dragging && 'opacity-40'), children: [is_group ? (_jsx(HiFolder, { className: cn('h-4 w-4 mt-0.5 flex-shrink-0', is_selected ? 'text-primary-foreground' : 'text-amber-500') })) : (_jsx(HiDocument, { className: cn('h-4 w-4 mt-0.5 flex-shrink-0', is_selected ? 'text-primary-foreground' : 'text-blue-500') })), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-sm font-medium truncate", children: data?.label || record.key }), _jsx("div", { className: cn('text-xs truncate', is_selected ? 'text-primary-foreground/70' : 'text-muted-foreground'), children: record.key })] })] }, record.id));
                                }) }))] }, area));
                })) }), _jsxs("div", { className: "p-2 border-t text-xs text-muted-foreground text-center", children: [filtered_elements.length, " element", filtered_elements.length !== 1 ? 's' : ''] })] }));
}
//# sourceMappingURL=element_list.js.map