/**
 * useFilters Hook
 *
 * React hook for fetching filter values, searching facet values,
 * and retrieving filter schema via the dedicated Filters API.
 */
import { useState, useEffect, useCallback, useRef } from 'react';
import { useSearchContext } from '../components/SearchProvider';
export const useFilters = (options) => {
    const { stateManager } = useSearchContext();
    const [filters, setFilters] = useState([]);
    const [schema, setSchema] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const mountedRef = useRef(true);
    const autoFetch = options?.autoFetch !== false;
    // Track whether we've completed the first fetch (to avoid skeleton flash on refetches)
    const hasDataRef = useRef(false);
    // Extract non-autoFetch options to pass to fetchFilters
    const fetchFilters = useCallback(async () => {
        // Only show loading spinner on the very first fetch; subsequent refetches
        // keep previous data visible to avoid skeleton/flash on facet changes.
        if (!hasDataRef.current) {
            setLoading(true);
        }
        setError(null);
        try {
            const { autoFetch: _, ...filterOptions } = options || {};
            const response = await stateManager.fetchFilters(filterOptions);
            if (mountedRef.current) {
                setFilters(response?.filters || []);
                hasDataRef.current = true;
                setLoading(false);
            }
        }
        catch (err) {
            if (mountedRef.current) {
                setError(err instanceof Error ? err : new Error(String(err)));
                setLoading(false);
            }
        }
    }, [stateManager, options?.facetBy, options?.maxFacetValues, options?.disjunctiveFacets?.join(',')]);
    // Track query to only refetch filters when query actually changes.
    // Sentinel ensures the first subscribe callback always triggers a fetch.
    const prevKeyRef = useRef(null);
    // Refetch when query or refinements change (not on every state update)
    useEffect(() => {
        if (!autoFetch)
            return;
        const unsubscribe = stateManager.subscribe((state) => {
            // Only track query changes — refinements are NOT passed to the Filters API
            // (facets are generated from search query only, not narrowed by active filters).
            // This prevents redundant filters refetches on every facet toggle.
            const key = state.query;
            if (key === prevKeyRef.current)
                return;
            prevKeyRef.current = key;
            fetchFilters();
        });
        // subscribe() immediately invokes the listener with current state,
        // which handles the initial fetch (prevKeyRef starts as '' so key
        // will differ). No explicit fetchFilters() call needed here.
        return unsubscribe;
    }, [stateManager, autoFetch, fetchFilters]);
    // Fetch schema once on mount
    useEffect(() => {
        stateManager.getFiltersSchema().then((response) => {
            if (mountedRef.current) {
                setSchema(response);
            }
        }).catch(() => {
            // Schema fetch failure is non-critical
        });
    }, [stateManager]);
    // Cleanup
    useEffect(() => {
        return () => {
            mountedRef.current = false;
        };
    }, []);
    const searchFacetValues = useCallback((facetName, query) => stateManager.searchFacetValues(facetName, query), [stateManager]);
    const refetch = useCallback(async () => {
        await fetchFilters();
    }, [fetchFilters]);
    return { filters, schema, loading, error, searchFacetValues, refetch };
};
