/**
 * SearchProvider Component
 *
 * Provides Seekora client and context to child components.
 * Supports A/B testing via abTestId/abVariant props.
 */
import React, { createContext, useContext, useMemo, useEffect } from 'react';
import { log, SearchStateManager } from '@seekora-ai/ui-sdk-core';
import { defaultTheme } from '../themes/default';
import { createTheme } from '../themes/createTheme';
const SearchContext = createContext(null);
export const SearchProvider = ({ client, theme: themeConfig, enableAnalytics = true, autoTrackSearch = true, stateManager: stateManagerConfig, children, abTestId, abVariant, experiments: _experiments, }) => {
    const theme = useMemo(() => {
        return themeConfig ? createTheme(themeConfig) : defaultTheme;
    }, [themeConfig]);
    // Create state manager instance (memoized to avoid recreating on every render)
    const stateManager = useMemo(() => {
        return new SearchStateManager({
            client,
            autoSearch: true,
            debounceMs: 300,
            itemsPerPage: 10,
            defaultSearchOptions: { widget_mode: true },
            ...stateManagerConfig,
            abTestId,
            abVariant,
        });
    }, [client, stateManagerConfig, abTestId, abVariant]);
    // Update A/B test fields on state manager and SDK client when props change
    useEffect(() => {
        if (abTestId !== undefined || abVariant !== undefined) {
            stateManager.setAbTest(abTestId, abVariant);
            client.setAbTest(abTestId, abVariant);
        }
    }, [stateManager, client, abTestId, abVariant]);
    const value = useMemo(() => ({
        client,
        theme,
        enableAnalytics,
        autoTrackSearch,
        stateManager,
    }), [client, theme, enableAnalytics, autoTrackSearch, stateManager]);
    return (React.createElement(SearchContext.Provider, { value: value }, children));
};
export const useSearchContext = () => {
    const context = useContext(SearchContext);
    if (!context) {
        const error = new Error('useSearchContext must be used within a SearchProvider');
        log.error('SearchProvider: Context not available', { error: error.message });
        throw error;
    }
    return context;
};
