'use client';
/**
 * Custom hook for managing library elements via hazo_connect API
 * Follows the same pattern as use_templates.ts
 */
import { useState, useCallback, useMemo } from 'react';
import { API_ENDPOINTS } from '../../../config/api_endpoints.js';
const DEFAULT_TABLE_NAME = 'hazo_collab_form_elts';
const DEFAULT_API_ENDPOINT = API_ENDPOINTS.library_data;
export function use_elements(options = {}) {
    const { api_base_url = DEFAULT_API_ENDPOINT, table_name = DEFAULT_TABLE_NAME, scope_id, } = options;
    const [elements, set_elements] = useState([]);
    const [loading, set_loading] = useState(false);
    const [error, set_error] = useState(null);
    // Derive distinct areas from elements
    const areas = useMemo(() => {
        const area_set = new Set(elements.map(e => e.area));
        return Array.from(area_set).sort();
    }, [elements]);
    const fetch_elements = useCallback(async (filter) => {
        set_loading(true);
        set_error(null);
        try {
            const params = new URLSearchParams({
                table: table_name,
                orderBy: 'area',
                orderDirection: 'asc',
            });
            if (filter?.area) {
                params.set('filter[area]', filter.area);
            }
            if (scope_id) {
                params.set('filter[scope_id]', scope_id);
            }
            const response = await fetch(`${api_base_url}?${params.toString()}`);
            if (!response.ok) {
                const error_data = await response.json().catch(() => ({}));
                throw new Error(error_data.error || `HTTP ${response.status}`);
            }
            const result = await response.json();
            set_elements(result.data || []);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to fetch elements';
            set_error(message);
            console.error('Error fetching elements:', err);
        }
        finally {
            set_loading(false);
        }
    }, [api_base_url, table_name, scope_id]);
    const create_element = useCallback(async (area, key, element_json) => {
        set_error(null);
        try {
            const now = new Date().toISOString();
            const new_record = {
                scope_id: scope_id ?? null,
                area,
                key,
                element: element_json,
                created_at: now,
                changed_at: now,
            };
            const response = await fetch(api_base_url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    table: table_name,
                    data: new_record,
                }),
            });
            if (!response.ok) {
                const error_data = await response.json().catch(() => ({}));
                throw new Error(error_data.error || `HTTP ${response.status}`);
            }
            const result = await response.json();
            const created = result.data;
            set_elements(prev => [...prev, created]);
            return created;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to create element';
            set_error(message);
            console.error('Error creating element:', err);
            return null;
        }
    }, [api_base_url, table_name, scope_id]);
    const update_element = useCallback(async (id, updates) => {
        set_error(null);
        try {
            const update_data = {
                ...updates,
                changed_at: new Date().toISOString(),
            };
            const response = await fetch(api_base_url, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    table: table_name,
                    criteria: { id },
                    data: update_data,
                }),
            });
            if (!response.ok) {
                const error_data = await response.json().catch(() => ({}));
                throw new Error(error_data.error || `HTTP ${response.status}`);
            }
            const result = await response.json();
            const updated = result.data?.[0];
            if (updated) {
                set_elements(prev => prev.map(e => (e.id === id ? updated : e)));
            }
            return updated || null;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to update element';
            set_error(message);
            console.error('Error updating element:', err);
            return null;
        }
    }, [api_base_url, table_name]);
    const delete_element = useCallback(async (id) => {
        set_error(null);
        try {
            const response = await fetch(api_base_url, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    table: table_name,
                    criteria: { id },
                }),
            });
            if (!response.ok) {
                const error_data = await response.json().catch(() => ({}));
                throw new Error(error_data.error || `HTTP ${response.status}`);
            }
            set_elements(prev => prev.filter(e => e.id !== id));
            return true;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to delete element';
            set_error(message);
            console.error('Error deleting element:', err);
            return false;
        }
    }, [api_base_url, table_name]);
    return {
        elements,
        loading,
        error,
        areas,
        fetch_elements,
        create_element,
        update_element,
        delete_element,
    };
}
//# sourceMappingURL=use_elements.js.map