/**
 * useSearchState Hook
 *
 * React hook for accessing and managing search state via SearchStateManager
 * Provides reactive state and methods to update search parameters
 */
import { useState, useEffect, useCallback } from 'react';
import { useSearchContext } from '../components/SearchProvider';
/**
 * Hook to access and manage search state
 * Automatically subscribes to state changes and re-renders when state updates
 */
export const useSearchState = () => {
    const { stateManager } = useSearchContext();
    const [state, setState] = useState(stateManager.getState());
    // Subscribe to state changes
    useEffect(() => {
        const unsubscribe = stateManager.subscribe((newState) => {
            setState(newState);
        });
        return unsubscribe;
    }, [stateManager]);
    // Memoized action methods
    const setQuery = useCallback((query, triggerSearch = true) => {
        stateManager.setQuery(query, triggerSearch);
    }, [stateManager]);
    const addRefinement = useCallback((field, value, triggerSearch = true) => {
        stateManager.addRefinement(field, value, triggerSearch);
    }, [stateManager]);
    const removeRefinement = useCallback((field, value, triggerSearch = true) => {
        stateManager.removeRefinement(field, value, triggerSearch);
    }, [stateManager]);
    const clearRefinements = useCallback((triggerSearch = true) => {
        stateManager.clearRefinements(triggerSearch);
    }, [stateManager]);
    const setPage = useCallback((page, triggerSearch = true) => {
        stateManager.setPage(page, triggerSearch);
    }, [stateManager]);
    const setSortBy = useCallback((sortBy, triggerSearch = true) => {
        stateManager.setSortBy(sortBy, triggerSearch);
    }, [stateManager]);
    const search = useCallback((additionalOptions) => {
        return stateManager.search(additionalOptions);
    }, [stateManager]);
    const clear = useCallback(() => {
        stateManager.clear();
    }, [stateManager]);
    return {
        // State
        query: state.query,
        refinements: state.refinements,
        currentPage: state.currentPage,
        itemsPerPage: state.itemsPerPage,
        sortBy: state.sortBy,
        results: state.results,
        loading: state.loading,
        error: state.error,
        // Actions
        setQuery,
        addRefinement,
        removeRefinement,
        clearRefinements,
        setPage,
        setSortBy,
        search,
        clear,
    };
};
