'use client';
import { jsx as _jsx } from "react/jsx-runtime";
/**
 * Field Library context - UI state + data hook integration
 */
import { createContext, useContext, useState, useMemo, useEffect } from 'react';
import { use_elements } from './hooks/use_elements.js';
import { parse_element, is_field_element, is_group_element } from './utils/element_utils.js';
import { format_full_key } from './utils/key_utils.js';
const FieldLibraryContext = createContext(null);
export function useFieldLibrary() {
    const ctx = useContext(FieldLibraryContext);
    if (!ctx) {
        throw new Error('useFieldLibrary must be used within a FieldLibraryProvider');
    }
    return ctx;
}
export function FieldLibraryProvider({ api_base_url, table_name, scope_id, templates, children, }) {
    // UI state
    const [active_tab, set_active_tab] = useState('fields');
    const [selected_id, set_selected_id] = useState(null);
    const [area_filter, set_area_filter] = useState(null);
    const [search_query, set_search_query] = useState('');
    // Data hook
    const elements = use_elements({ api_base_url, table_name, scope_id });
    // Fetch on mount
    useEffect(() => {
        elements.fetch_elements();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    // Filter elements by tab type, area, and search query
    const filtered_elements = useMemo(() => {
        return elements.elements.filter(record => {
            // Filter by tab type (field vs group)
            const data = parse_element(record.element);
            if (!data)
                return false;
            if (active_tab === 'fields' && !is_field_element(data))
                return false;
            if (active_tab === 'groups' && !is_group_element(data))
                return false;
            // Filter by area
            if (area_filter && record.area !== area_filter)
                return false;
            // Filter by search query
            if (search_query) {
                const query = search_query.toLowerCase();
                const full_key = format_full_key(record.area, record.key);
                const label = data.label?.toLowerCase() ?? '';
                if (!full_key.toLowerCase().includes(query) && !label.includes(query)) {
                    return false;
                }
            }
            return true;
        });
    }, [elements.elements, active_tab, area_filter, search_query]);
    const value = useMemo(() => ({
        active_tab,
        set_active_tab,
        selected_id,
        set_selected_id,
        area_filter,
        set_area_filter,
        search_query,
        set_search_query,
        elements,
        filtered_elements,
        templates,
    }), [active_tab, selected_id, area_filter, search_query, elements, filtered_elements, templates]);
    return (_jsx(FieldLibraryContext.Provider, { value: value, children: children }));
}
//# sourceMappingURL=context.js.map