/**
 * SuggestionSearchBar - Unified Search Component with Premium Dropdowns
 *
 * A self-contained search component that:
 * - Fetches suggestions from the API automatically
 * - Parses responses internally (no user-side parsing needed)
 * - Renders any of the 7 premium dropdown variants
 * - Handles analytics tracking
 * - Supports recent searches via localStorage
 * - Fully responsive and mobile-ready
 *
 * Usage:
 * ```tsx
 * <SuggestionSearchBar
 *   client={seekoraClient}
 *   variant="amazon"
 *   onSearch={(query) => router.push(`/search?q=${query}`)}
 * />
 * ```
 */
import React, { useState, useRef, useCallback, useEffect, forwardRef, useImperativeHandle, useMemo, } from 'react';
import { getRecentSearches, addRecentSearch, removeRecentSearch, cx, mergeStyles, getSuggestionsCache, } from './utils';
import { useResponsive } from './styles/responsive';
import { useInjectResponsiveStyles } from './styles';
import { useSearchContext } from '../SearchProvider';
import { useSuggestionsAnalytics } from '../../hooks/useSuggestionsAnalytics';
// Import all variants
import { AmazonDropdown } from './AmazonDropdown';
import { GoogleDropdown } from './GoogleDropdown';
import { PinterestDropdown } from './PinterestDropdown';
import { SpotlightDropdown } from './SpotlightDropdown';
import { ShopifyDropdown } from './ShopifyDropdown';
import { MobileSheetDropdown } from './MobileSheetDropdown';
import { MinimalDropdown } from './MinimalDropdown';
// ============================================================================
// Theme helpers (support both Theme { colors } and DropdownThemeConfig)
// ============================================================================
function getThemeVars(theme) {
    if (!theme) {
        return {
            '--seekora-bg-surface': '#ffffff',
            '--seekora-bg-secondary': '#f7f7f7',
            '--seekora-bg-tertiary': '#f0f0f0',
            '--seekora-bg-hover': '#f5f5f5',
            '--seekora-text-primary': '#0f1111',
            '--seekora-text-secondary': '#565959',
            '--seekora-text-tertiary': '#767676',
            '--seekora-border-color': '#e7e7e7',
            '--seekora-primary': '#f90',
            '--seekora-text-on-primary': '#0f1111',
            '--seekora-text-inverse': '#ffffff',
            '--seekora-link': '#007185',
            '--seekora-font-family': '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        };
    }
    const t = theme;
    const colors = t.colors ?? {};
    return {
        '--seekora-bg-surface': t.backgroundColor ?? colors.background ?? '#ffffff',
        '--seekora-bg-secondary': t.surfaceColor ?? colors.hover ?? '#f7f7f7',
        '--seekora-bg-tertiary': t.hoverColor ?? colors.hover ?? '#f0f0f0',
        '--seekora-bg-hover': t.hoverColor ?? colors.hover ?? '#f5f5f5',
        '--seekora-text-primary': t.textColor ?? colors.text ?? '#0f1111',
        '--seekora-text-secondary': t.textSecondaryColor ?? colors.text ?? '#565959',
        '--seekora-text-tertiary': t.textSecondaryColor ?? '#767676',
        '--seekora-border-color': t.borderColor ?? colors.border ?? '#e7e7e7',
        '--seekora-primary': t.primaryColor ?? colors.primary ?? '#f90',
        '--seekora-text-on-primary': t.textOnPrimaryColor ?? '#0f1111',
        '--seekora-text-inverse': t.textInverseColor ?? '#ffffff',
        '--seekora-link': t.primaryColor ?? colors.primary ?? '#007185',
        '--seekora-font-family': t.fontFamily ?? '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    };
}
function themeToDropdownConfig(theme) {
    if (!theme)
        return undefined;
    const t = theme;
    const colors = t.colors ?? {};
    return {
        backgroundColor: t.backgroundColor ?? colors.background,
        textColor: t.textColor ?? colors.text,
        surfaceColor: t.surfaceColor ?? colors.hover,
        borderColor: t.borderColor ?? colors.border,
        hoverColor: t.hoverColor ?? colors.hover,
        primaryColor: t.primaryColor ?? colors.primary,
        textSecondaryColor: t.textSecondaryColor ?? colors.text,
        fontFamily: t.fontFamily,
    };
}
// ============================================================================
// Variant Map
// ============================================================================
const VariantComponents = {
    amazon: AmazonDropdown,
    google: GoogleDropdown,
    pinterest: PinterestDropdown,
    spotlight: SpotlightDropdown,
    shopify: ShopifyDropdown,
    'mobile-sheet': MobileSheetDropdown,
    minimal: MinimalDropdown,
};
// ============================================================================
// Styles
// ============================================================================
const createStyles = (isMobile) => ({
    container: {
        position: 'relative',
        width: '100%',
        fontFamily: 'var(--seekora-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif)',
    },
    inputWrapper: {
        display: 'flex',
        alignItems: 'center',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        color: 'var(--seekora-text-primary, #111827)',
        borderWidth: '2px',
        borderStyle: 'solid',
        borderColor: 'var(--seekora-border-color, #d1d5db)',
        borderRadius: isMobile ? '8px' : '24px',
        overflow: 'hidden',
        transition: 'border-color 150ms, box-shadow 150ms',
        boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
    },
    inputWrapperFocused: {
        borderColor: 'var(--seekora-primary, #f90)',
        boxShadow: '0 0 0 3px rgba(255, 153, 0, 0.15), 0 2px 8px rgba(0,0,0,0.1)',
    },
    searchIcon: {
        padding: isMobile ? '0 10px 0 14px' : '0 12px 0 18px',
        color: 'var(--seekora-text-secondary, #6b7280)',
        display: 'flex',
        alignItems: 'center',
        flexShrink: 0,
    },
    input: {
        flex: 1,
        padding: isMobile ? '12px 8px 12px 0' : '14px 12px 14px 0',
        fontSize: isMobile ? '16px' : '15px',
        borderWidth: 0,
        borderStyle: 'none',
        outline: 'none',
        backgroundColor: 'transparent',
        color: 'var(--seekora-text-primary, #0f1111)',
        fontFamily: 'inherit',
        minWidth: 0,
        WebkitAppearance: 'none',
    },
    clearButton: {
        padding: '8px 14px',
        background: 'none',
        borderWidth: 0,
        borderStyle: 'none',
        cursor: 'pointer',
        color: 'var(--seekora-text-tertiary, #9ca3af)',
        fontSize: '18px',
        lineHeight: 1,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
        transition: 'color 150ms',
    },
});
// ============================================================================
// Component
// ============================================================================
export const SuggestionSearchBar = forwardRef(function SuggestionSearchBar(props, ref) {
    const { client, variant = 'amazon', autoMobileVariant = true, placeholder = 'Powered by Seekora', defaultQuery = '', value, minQueryLength = 1, maxSuggestions = 8, debounceMs = 200, includeDropdownRecommendations = true, includeDropdownProductList = true, includeFilteredTabs = true, includeCategories = true, filteredTabs, analyticsTags, enableRecentSearches = true, maxRecentSearches = 10, showProducts = true, showTrendingOnEmpty = true, enableAnalytics = true, analyticsConfig, suggestionFields, productFields, theme, onSearch, onQueryChange, onSuggestionSelect, onProductClick, onCategoryClick, onTabChange, className, style, inputClassName, dropdownWidth, dropdownMaxHeight = '500px', zIndex = 1000, enableCache = true, cacheTtlMs = 30000, cacheMaxSize = 100, } = props;
    // Theme: prop overrides context (SearchProvider theme)
    const searchContext = useSearchContext();
    const effectiveTheme = theme ?? searchContext.theme;
    // Initialize analytics hook for proper event tracking
    const analytics = useSuggestionsAnalytics({
        client,
        enabled: enableAnalytics,
        analyticsTags: analyticsConfig?.tags ?? analyticsTags,
        trackImpressions: analyticsConfig?.trackImpressions ?? true,
        trackClicks: analyticsConfig?.trackSuggestionClicks ?? true,
    });
    // Inject responsive styles
    useInjectResponsiveStyles();
    // Inject theme CSS variables so dropdown and page use one consistent theme
    useEffect(() => {
        const root = document.documentElement;
        const themeVars = getThemeVars(effectiveTheme);
        Object.entries(themeVars).forEach(([key, value]) => {
            root.style.setProperty(key, value);
        });
    }, [effectiveTheme]);
    // Responsive state
    const responsive = useResponsive();
    const { isMobile } = responsive;
    // Determine actual variant (auto-switch to mobile on small screens)
    const actualVariant = useMemo(() => {
        if (autoMobileVariant && isMobile && variant !== 'mobile-sheet' && variant !== 'spotlight') {
            return 'mobile-sheet';
        }
        return variant;
    }, [variant, isMobile, autoMobileVariant]);
    // State
    const [query, setQuery] = useState(defaultQuery);
    const [isOpen, setIsOpen] = useState(false);
    const [isFocused, setIsFocused] = useState(false);
    const [loading, setLoading] = useState(false);
    const [suggestions, setSuggestions] = useState([]);
    const [products, setProducts] = useState([]);
    const [categories, setCategories] = useState([]);
    const [tabs, setTabs] = useState([]);
    const [trendingSearches, setTrendingSearches] = useState([]);
    const [recentSearches, setRecentSearches] = useState([]);
    const [activeTab, setActiveTab] = useState('all');
    // Refs
    const inputRef = useRef(null);
    const dropdownRef = useRef(null);
    const debounceRef = useRef(null);
    const containerRef = useRef(null);
    // Initialize cache
    const cache = useMemo(() => {
        if (!enableCache)
            return null;
        return getSuggestionsCache({ maxSize: cacheMaxSize, defaultTtlMs: cacheTtlMs });
    }, [enableCache, cacheMaxSize, cacheTtlMs]);
    // Controlled vs uncontrolled query
    const currentQuery = value !== undefined ? value : query;
    // Styles
    const styles = useMemo(() => createStyles(isMobile), [isMobile]);
    // Load recent searches on mount
    useEffect(() => {
        if (enableRecentSearches) {
            const allRecent = getRecentSearches();
            setRecentSearches(allRecent.slice(0, maxRecentSearches));
        }
    }, [enableRecentSearches, maxRecentSearches]);
    // ========================================================================
    // API Data Fetching
    // ========================================================================
    const fetchSuggestions = useCallback(async (searchQuery) => {
        if (!client)
            return;
        // Allow empty string "" for focus-triggered search (API returns trending/default); otherwise enforce min length
        if (searchQuery.length > 0 && searchQuery.length < minQueryLength) {
            setSuggestions([]);
            setProducts([]);
            setTabs([]);
            return;
        }
        // Build cache key from query and options
        const cacheOptions = {
            maxSuggestions,
            includeDropdownRecommendations,
            includeDropdownProductList,
            includeFilteredTabs,
            includeCategories,
            filteredTabs: filteredTabs?.map(t => t.filter).join(','),
        };
        const cacheKey = cache?.generateKey(searchQuery, cacheOptions);
        // Check cache first
        if (cache && cacheKey) {
            const cachedResponse = cache.get(cacheKey);
            if (cachedResponse) {
                console.log('Seekora: Cache hit for query:', searchQuery);
                parseAndSetData(cachedResponse);
                return;
            }
        }
        setLoading(true);
        try {
            // Use the SDK client to fetch suggestions ("" is valid - API returns something for empty query)
            // IMPORTANT: returnFullResponse: true is required to get filtered_tabs and extensions
            const response = await client.getSuggestions?.(searchQuery, {
                hitsPerPage: maxSuggestions,
                include_dropdown_recommendations: includeDropdownRecommendations,
                include_dropdown_product_list: includeDropdownProductList,
                include_filtered_tabs: includeFilteredTabs,
                include_categories: includeCategories,
                include_facets: true, // Enable facet-based suggestions
                filtered_tabs: filteredTabs,
                analytics_tags: analyticsTags,
                returnFullResponse: true, // Required to get tabs and products
            });
            // Cache the response
            if (cache && cacheKey && response) {
                cache.set(cacheKey, response);
                console.log('Seekora: Cached response for query:', searchQuery);
            }
            // Parse the response - SDK returns normalized structure
            parseAndSetData(response);
            // Track impressions via analytics hook (sends to API)
            if (enableAnalytics && response && !Array.isArray(response)) {
                const resp = response;
                analytics.trackImpression({
                    suggestions: (resp.suggestions || []).map((s) => ({
                        query: s.query || s.text || '',
                        objectID: s.objectID || s.id,
                        popularity: s.popularity,
                    })),
                    products: resp.extensions?.trending_products || resp.extensions?.item_recommendations || [],
                    categories: resp.extensions?.popular_categories || [],
                    brands: resp.extensions?.popular_brands || [],
                    query: searchQuery,
                    timestamp: Date.now(),
                });
            }
        }
        catch (error) {
            console.error('Seekora: Failed to fetch suggestions', error);
            setSuggestions([]);
            setProducts([]);
            setTabs([]);
        }
        finally {
            setLoading(false);
        }
    }, [client, minQueryLength, maxSuggestions, includeDropdownRecommendations, includeDropdownProductList, includeFilteredTabs, includeCategories, filteredTabs, analyticsTags, enableAnalytics, analytics, cache]);
    // Parse API response - handles multiple response formats
    const parseAndSetData = useCallback((response) => {
        // Handle different response structures from the API/SDK
        let hits = [];
        let extensions = {};
        console.log('Seekora: Raw response structure', {
            hasSuggestions: !!response?.suggestions,
            hasResults: !!response?.results,
            hasExtensions: !!response?.extensions,
            hasData: !!response?.data,
        });
        // SDK returnFullResponse format: { suggestions, results, extensions }
        if (response?.suggestions && response?.extensions) {
            hits = response.suggestions || [];
            extensions = response.extensions || {};
        }
        // Multi-index response: { results: [{ hits, extensions }, ...] }
        else if (response?.results && Array.isArray(response.results)) {
            const result0 = response.results[0] || {};
            const result1 = response.results[1] || {};
            hits = result0.hits || result0.suggestions || [];
            // Extensions can be in result0 or result1
            extensions = result0.extensions || result1.extensions || {};
        }
        // Wrapped response: { data: { hits, extensions, ... } }
        else if (response?.data) {
            hits = response.data.hits || [];
            extensions = response.data.extensions || response.data.dropdown_recommendations || {};
        }
        // Direct response: { hits, extensions, ... }
        else if (response?.hits) {
            hits = response.hits || [];
            extensions = response.extensions || response.dropdown_recommendations || {};
        }
        // Array response
        else if (Array.isArray(response)) {
            hits = response;
        }
        // Set suggestions
        setSuggestions(hits);
        // Set filtered tabs from extensions
        const filteredTabsData = extensions.filtered_tabs || [];
        setTabs(filteredTabsData);
        // Set products from first tab or trending
        if (filteredTabsData.length > 0 && filteredTabsData[0].products) {
            setProducts(filteredTabsData[0].products);
        }
        else {
            setProducts(extensions.trending_products || extensions.item_recommendations || []);
        }
        // Set categories
        setCategories(extensions.popular_categories || []);
        // Set trending searches
        setTrendingSearches(extensions.trending_searches || extensions.top_searches || []);
        console.log('Seekora: Parsed response', {
            suggestions: hits.length,
            tabs: filteredTabsData.length,
            products: filteredTabsData[0]?.products?.length || 0,
            extensionKeys: Object.keys(extensions),
        });
    }, []);
    // ========================================================================
    // Event Handlers
    // ========================================================================
    const handleInputChange = useCallback((e) => {
        const newQuery = e.target.value;
        if (value === undefined) {
            setQuery(newQuery);
        }
        onQueryChange?.(newQuery);
        setActiveTab('all');
        // Debounced fetch
        if (debounceRef.current) {
            clearTimeout(debounceRef.current);
        }
        if (newQuery.length >= minQueryLength) {
            setIsOpen(true);
            debounceRef.current = setTimeout(() => {
                fetchSuggestions(newQuery);
            }, debounceMs);
        }
        else if (newQuery.length === 0 && (enableRecentSearches || showTrendingOnEmpty)) {
            setIsOpen(true);
            setSuggestions([]);
        }
        else {
            setIsOpen(false);
        }
    }, [value, onQueryChange, minQueryLength, debounceMs, fetchSuggestions, enableRecentSearches, showTrendingOnEmpty]);
    const handleInputFocus = useCallback(() => {
        setIsFocused(true);
        setIsOpen(true);
        // Track dropdown open
        if (enableAnalytics) {
            analytics.trackDropdownOpen(currentQuery);
        }
        // Trigger empty search "" when user clicks/focuses the box so API returns trending/default content
        if (currentQuery.length >= minQueryLength) {
            if (suggestions.length === 0)
                fetchSuggestions(currentQuery);
        }
        else {
            fetchSuggestions('');
        }
    }, [currentQuery, minQueryLength, suggestions.length, fetchSuggestions, enableAnalytics, analytics]);
    const handleInputBlur = useCallback(() => {
        setIsFocused(false);
        // Delay close to allow click events on dropdown
        setTimeout(() => {
            if (!containerRef.current?.contains(document.activeElement)) {
                setIsOpen(false);
            }
        }, 150);
    }, []);
    const handleKeyDown = useCallback((e) => {
        if (e.key === 'Escape') {
            setIsOpen(false);
            inputRef.current?.blur();
        }
        else if (e.key === 'Enter') {
            e.preventDefault();
            // Check if there's an active selection in the dropdown
            const activeIndex = dropdownRef.current?.getActiveIndex?.() ?? -1;
            if (activeIndex >= 0 && isOpen) {
                // Let the dropdown handle the selection
                dropdownRef.current?.selectActive?.();
            }
            else if (currentQuery.trim()) {
                // No active selection, submit the current query
                onSearch?.(currentQuery.trim());
                if (enableRecentSearches) {
                    addRecentSearch(currentQuery.trim());
                    setRecentSearches(getRecentSearches().slice(0, maxRecentSearches));
                }
                // Track search submit analytics
                if (enableAnalytics) {
                    analytics.trackSearchSubmit(currentQuery.trim(), false);
                }
                setIsOpen(false);
            }
        }
        else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
            e.preventDefault();
            // Open dropdown if not already open
            if (!isOpen && (suggestions.length > 0 || recentSearches.length > 0)) {
                setIsOpen(true);
            }
            if (e.key === 'ArrowDown') {
                dropdownRef.current?.navigateNext?.();
            }
            else {
                dropdownRef.current?.navigatePrevious?.();
            }
        }
    }, [currentQuery, onSearch, enableRecentSearches, maxRecentSearches, isOpen, suggestions.length, recentSearches.length, enableAnalytics, analytics]);
    const handleSuggestionSelect = useCallback((suggestion, index) => {
        const text = suggestion.query || suggestion.text || suggestion.objectID || '';
        if (value === undefined) {
            setQuery(text);
        }
        onQueryChange?.(text);
        onSuggestionSelect?.(suggestion, index);
        if (enableRecentSearches && text) {
            addRecentSearch(text);
            setRecentSearches(getRecentSearches().slice(0, maxRecentSearches));
        }
        // Track analytics via the proper hook (sends to API)
        if (enableAnalytics) {
            analytics.trackSuggestionClick({
                suggestion: {
                    query: text,
                    objectID: suggestion.objectID || suggestion.id,
                    popularity: suggestion.popularity,
                },
                position: index,
                section: 'suggestions',
                query: currentQuery,
                totalSuggestions: suggestions.length,
            });
            analytics.trackSearchSubmit(text, true, suggestion);
        }
        onSearch?.(text);
        setIsOpen(false);
    }, [value, onQueryChange, onSuggestionSelect, enableRecentSearches, maxRecentSearches, enableAnalytics, onSearch, analytics, currentQuery, suggestions.length]);
    const handleProductClick = useCallback((product, index) => {
        onProductClick?.(product, index);
        // Track analytics via the proper hook (sends to API)
        if (enableAnalytics) {
            analytics.trackProductClick({
                product: {
                    id: product.id || product.objectID,
                    objectID: product.objectID || product.id,
                    title: product.title || product.name,
                    image: product.image,
                    price: product.price,
                },
                position: index,
                section: activeTab !== 'all' ? 'filtered_tab' : 'products',
                tabId: activeTab !== 'all' ? activeTab : undefined,
                query: currentQuery,
            });
        }
    }, [onProductClick, enableAnalytics, analytics, activeTab, currentQuery]);
    const handleCategoryClick = useCallback((category, index) => {
        onCategoryClick?.(category, index);
        // Track analytics via the proper hook (sends to API)
        if (enableAnalytics) {
            analytics.trackCategoryClick({
                value: category.label || category.value || category.id,
                count: category.count,
                path: category.path,
            }, currentQuery);
        }
    }, [onCategoryClick, enableAnalytics, analytics, currentQuery]);
    const handleTabChange = useCallback((tabId) => {
        console.log('Seekora: Tab changed to', tabId);
        setActiveTab(tabId);
        onTabChange?.(tabId);
        // Track analytics via the proper hook (sends to API)
        if (enableAnalytics) {
            const tab = tabs.find(t => t.id === tabId);
            if (tab) {
                analytics.trackTabSelect({
                    id: tab.id,
                    label: tab.label,
                    filter: tab.filter,
                    products: tab.products,
                    nb_hits: tab.nb_hits,
                }, currentQuery);
            }
        }
    }, [onTabChange, enableAnalytics, analytics, tabs, currentQuery]);
    const handleRecentClick = useCallback((text) => {
        if (value === undefined) {
            setQuery(text);
        }
        onQueryChange?.(text);
        fetchSuggestions(text);
        // Track analytics via the proper hook (sends to API)
        if (enableAnalytics) {
            analytics.trackRecentSearchClick({
                query: text,
                timestamp: Date.now(),
            });
        }
    }, [value, onQueryChange, fetchSuggestions, enableAnalytics, analytics]);
    const handleRecentRemove = useCallback((text) => {
        removeRecentSearch(text);
        setRecentSearches(getRecentSearches().slice(0, maxRecentSearches));
    }, [maxRecentSearches]);
    const handleClear = useCallback(() => {
        if (value === undefined) {
            setQuery('');
        }
        onQueryChange?.('');
        setSuggestions([]);
        setProducts([]);
        setTabs([]);
        inputRef.current?.focus();
    }, [value, onQueryChange]);
    const handleClose = useCallback(() => {
        setIsOpen(false);
        // Track dropdown close
        if (enableAnalytics) {
            analytics.trackDropdownClose(currentQuery);
        }
    }, [enableAnalytics, analytics, currentQuery]);
    // ========================================================================
    // Imperative Handle
    // ========================================================================
    useImperativeHandle(ref, () => ({
        focus: () => inputRef.current?.focus(),
        blur: () => inputRef.current?.blur(),
        clear: handleClear,
        getQuery: () => currentQuery,
        setQuery: (q) => {
            if (value === undefined) {
                setQuery(q);
            }
            onQueryChange?.(q);
        },
        openDropdown: () => setIsOpen(true),
        closeDropdown: () => setIsOpen(false),
        refresh: () => fetchSuggestions(currentQuery),
        clearCache: () => cache?.clear(),
        getCacheStats: () => cache?.getStats() ?? null,
    }), [currentQuery, value, onQueryChange, handleClear, fetchSuggestions, cache]);
    // ========================================================================
    // Render
    // ========================================================================
    const DropdownComponent = VariantComponents[actualVariant] || AmazonDropdown;
    // Get products for current tab - always derive from tabs to ensure consistency
    const currentTabProducts = useMemo(() => {
        console.log('Seekora: Computing products for tab', activeTab, 'from', tabs.length, 'tabs');
        if (tabs.length === 0) {
            return products; // Fallback to products state if no tabs
        }
        if (activeTab === 'all') {
            // For 'all' tab, use first tab's products or combined
            const firstTabProducts = tabs[0]?.products || [];
            return firstTabProducts.length > 0 ? firstTabProducts : products;
        }
        // Find the specific tab
        const tab = tabs.find(t => t.id === activeTab);
        if (tab?.products && tab.products.length > 0) {
            console.log('Seekora: Found', tab.products.length, 'products for tab', activeTab);
            return tab.products;
        }
        // Fallback
        return products;
    }, [activeTab, tabs, products]);
    return (React.createElement("div", { ref: containerRef, className: cx('seekora-suggestion-search', className), style: mergeStyles(styles.container, style) },
        React.createElement("div", { style: mergeStyles(styles.inputWrapper, isFocused ? styles.inputWrapperFocused : undefined) },
            React.createElement("div", { style: styles.searchIcon },
                React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "20", height: "20" },
                    React.createElement("path", { fillRule: "evenodd", d: "M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z", clipRule: "evenodd" }))),
            React.createElement("input", { ref: inputRef, type: "text", value: currentQuery, onChange: handleInputChange, onFocus: handleInputFocus, onBlur: handleInputBlur, onKeyDown: handleKeyDown, placeholder: placeholder, className: inputClassName, style: styles.input, autoComplete: "off", autoCorrect: "off", autoCapitalize: "off", spellCheck: false, "aria-label": "Search", "aria-expanded": isOpen, "aria-haspopup": "listbox" }),
            currentQuery && (React.createElement("button", { type: "button", onClick: handleClear, style: styles.clearButton, "aria-label": "Clear search" }, "\u00D7"))),
        isOpen && (React.createElement(DropdownComponent, { query: currentQuery, isOpen: isOpen, loading: loading, suggestions: suggestions, products: currentTabProducts, categories: tabs.map(t => ({ id: t.id, label: t.label, count: t.nb_hits })), recentSearches: recentSearches.map(r => typeof r === 'string' ? r : r.query), trendingSearches: trendingSearches, filteredTabs: tabs, activeTab: activeTab, suggestionFields: suggestionFields, productFields: productFields, theme: themeToDropdownConfig(effectiveTheme) ?? effectiveTheme, width: dropdownWidth || '100%', maxHeight: dropdownMaxHeight, zIndex: zIndex, analytics: {
                enabled: enableAnalytics,
                trackSuggestionClicks: analyticsConfig?.trackSuggestionClicks ?? true,
                trackProductClicks: analyticsConfig?.trackProductClicks ?? true,
                trackImpressions: analyticsConfig?.trackImpressions ?? true,
                trackCategoryClicks: analyticsConfig?.trackCategoryClicks ?? true,
                trackBrandClicks: analyticsConfig?.trackBrandClicks ?? true,
                trackSearchSubmit: analyticsConfig?.trackSearchSubmit ?? true,
                tags: analyticsConfig?.tags ?? analyticsTags,
            }, onSuggestionSelect: handleSuggestionSelect, onProductClick: handleProductClick, onCategoryClick: handleCategoryClick, onTabChange: handleTabChange, onRecentClick: handleRecentClick, onRecentRemove: handleRecentRemove, onClose: handleClose }))));
});
export default SuggestionSearchBar;
