/**
 * RichQuerySuggestions Component
 *
 * Advanced multi-section dropdown with:
 * - Suggestions with categories
 * - Trending searches
 * - Recent searches
 * - Top searches (popular)
 * - Related searches
 * - Configurable sections
 * - Rich styling options
 */
import React, { useState, useRef, useCallback, useMemo, forwardRef, useImperativeHandle, } from 'react';
import { useSearchContext } from './SearchProvider';
import { useQuerySuggestionsEnhanced } from '../hooks/useQuerySuggestionsEnhanced';
import { clsx } from 'clsx';
// ============================================================================
// Constants
// ============================================================================
const TRANSITIONS = {
    fast: '150ms ease-in-out',
    normal: '200ms ease-in-out',
    slow: '300ms ease-in-out',
};
const BORDER_RADIUS = {
    sm: 4,
    md: 6,
    lg: 8,
    full: 9999,
};
// Default section order
const DEFAULT_SECTIONS = [
    { id: 'recent', title: 'Recent Searches', maxItems: 5, enabled: true, order: 1 },
    { id: 'suggestions', title: 'Suggestions', maxItems: 8, enabled: true, order: 2 },
    { id: 'trending', title: 'Trending', maxItems: 5, enabled: true, order: 3 },
    { id: 'categories', title: 'Categories', maxItems: 6, enabled: false, order: 4 },
];
// ============================================================================
// Styles
// ============================================================================
const styles = {
    container: {
        backgroundColor: 'var(--seekora-bg-surface, transparent)',
        border: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderRadius: `var(--seekora-border-radius-lg, ${BORDER_RADIUS.lg * 1.5}px)`,
        boxShadow: 'var(--seekora-shadow-xl, 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04))',
        overflow: 'hidden',
    },
    header: {
        padding: '12px 16px',
        borderBottom: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
    },
    content: {
        overflowY: 'auto',
        overflowX: 'hidden',
    },
    section: {
        padding: '8px 0',
    },
    sectionHeader: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '8px 16px 4px',
    },
    sectionTitle: {
        fontSize: '11px',
        fontWeight: 600,
        color: 'var(--seekora-text-tertiary, #9ca3af)',
        textTransform: 'uppercase',
        letterSpacing: '0.05em',
        margin: 0,
    },
    sectionAction: {
        fontSize: '12px',
        color: 'var(--seekora-primary, #3b82f6)',
        cursor: 'pointer',
        textDecoration: 'none',
        fontWeight: 500,
    },
    item: {
        display: 'flex',
        alignItems: 'flex-start',
        padding: '10px 16px',
        cursor: 'pointer',
        transition: `background-color ${TRANSITIONS.fast}`,
        gap: '12px',
    },
    itemActive: {
        backgroundColor: 'var(--seekora-bg-hover, #f3f4f6)',
    },
    itemIcon: {
        width: '18px',
        height: '18px',
        color: 'var(--seekora-text-secondary, #6b7280)',
        flexShrink: 0,
        marginTop: '2px',
    },
    itemContent: {
        flex: 1,
        minWidth: 0,
    },
    itemQuery: {
        fontSize: '14px',
        color: 'var(--seekora-text-primary, inherit)',
        fontWeight: 500,
        margin: 0,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
    },
    itemMeta: {
        fontSize: '12px',
        color: 'var(--seekora-text-secondary, inherit)',
        marginTop: '2px',
    },
    itemCount: {
        fontSize: '12px',
        color: 'var(--seekora-text-tertiary, #9ca3af)',
        flexShrink: 0,
    },
    categoriesContainer: {
        display: 'flex',
        flexWrap: 'wrap',
        gap: '6px',
        marginTop: '6px',
    },
    categoryPill: {
        display: 'inline-flex',
        alignItems: 'center',
        gap: '4px',
        padding: '3px 8px',
        fontSize: '11px',
        fontWeight: 500,
        color: 'var(--seekora-text-secondary, inherit)',
        backgroundColor: 'var(--seekora-bg-tertiary, rgba(255, 255, 255, 0.1))',
        borderRadius: `${BORDER_RADIUS.lg * 1.5}px`,
        cursor: 'pointer',
        transition: `all ${TRANSITIONS.fast}`,
    },
    categoryPillHover: {
        backgroundColor: 'var(--seekora-primary-light, #dbeafe)',
        color: 'var(--seekora-primary, #3b82f6)',
    },
    categoryCount: {
        color: 'var(--seekora-text-tertiary, #9ca3af)',
    },
    trendingList: {
        display: 'flex',
        flexWrap: 'wrap',
        gap: '8px',
        padding: '8px 16px',
    },
    trendingChip: {
        display: 'inline-flex',
        alignItems: 'center',
        gap: '6px',
        padding: '6px 12px',
        fontSize: '13px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, inherit)',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
        border: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderRadius: `${BORDER_RADIUS.full}px`,
        cursor: 'pointer',
        transition: `all ${TRANSITIONS.fast}`,
    },
    trendingChipHover: {
        borderColor: 'var(--seekora-primary, #3b82f6)',
        backgroundColor: 'var(--seekora-primary-light, #eff6ff)',
    },
    trendingIcon: {
        width: '14px',
        height: '14px',
        color: 'var(--seekora-success, #10b981)',
    },
    trendingRank: {
        width: '18px',
        height: '18px',
        borderRadius: `${BORDER_RADIUS.full}px`,
        backgroundColor: 'var(--seekora-primary, #3b82f6)',
        color: 'white',
        fontSize: '10px',
        fontWeight: 600,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    removeButton: {
        padding: '4px',
        marginLeft: 'auto',
        borderRadius: `${BORDER_RADIUS.sm}px`,
        border: 'none',
        background: 'transparent',
        cursor: 'pointer',
        color: 'var(--seekora-text-tertiary, #9ca3af)',
        opacity: 0,
        transition: `opacity ${TRANSITIONS.fast}`,
    },
    divider: {
        height: '1px',
        backgroundColor: 'var(--seekora-border-color, rgba(128,128,128,0.2))',
        margin: '4px 16px',
    },
    footer: {
        padding: '12px 16px',
        borderTop: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
        fontSize: '12px',
        color: 'var(--seekora-text-secondary, inherit)',
    },
    emptyState: {
        padding: '32px 16px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, inherit)',
    },
    highlight: {
        backgroundColor: 'var(--seekora-highlight-bg, #fef9c3)',
        fontWeight: 600,
        borderRadius: '2px',
        padding: '0 1px',
    },
};
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", style: styles.itemIcon },
    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" })));
const ClockIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", style: styles.itemIcon },
    React.createElement("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z", clipRule: "evenodd" })));
const TrendingIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", style: styles.trendingIcon },
    React.createElement("path", { fillRule: "evenodd", d: "M12 7a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0V8.414l-4.293 4.293a1 1 0 01-1.414 0L8 10.414l-4.293 4.293a1 1 0 01-1.414-1.414l5-5a1 1 0 011.414 0L11 10.586 14.586 7H12z", clipRule: "evenodd" })));
const ArrowIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", style: { width: 16, height: 16 } },
    React.createElement("path", { fillRule: "evenodd", d: "M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z", clipRule: "evenodd" })));
const CloseIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", style: { width: 14, height: 14 } },
    React.createElement("path", { fillRule: "evenodd", d: "M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z", clipRule: "evenodd" })));
// ============================================================================
// Component
// ============================================================================
export const RichQuerySuggestions = forwardRef(function RichQuerySuggestions(props, ref) {
    const { query, isOpen = true, sections = DEFAULT_SECTIONS, maxSuggestionsPerSection = 8, minQueryLength = 0, debounceMs = 200, includeDropdownRecommendations = true, includeDropdownProductList = true, includeFilteredTabs = true, includeCategories = true, maxCategories = 3, showCounts = true, showCategoryCounts = true, showSectionHeaders = true, classNames = {}, style, renderSuggestion, renderCategory, renderTrendingItem, renderRecentItem, header, footer, width = '100%', maxHeight = '480px', zIndex = 1000, ariaLabel = 'Search suggestions', analyticsTags, onSuggestionSelect, onCategoryClick, onRecentSearchClick, onRecentSearchRemove, onViewAllClick, onOpen, onClose, } = props;
    const { client } = useSearchContext();
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [hoveredCategory, setHoveredCategory] = useState(null);
    // Use enhanced hook
    const { suggestions, loading, trendingSearches, topSearches, recentSearches, addRecentSearch, removeRecentSearch, hasContent, } = useQuerySuggestionsEnhanced({
        client,
        query,
        enabled: isOpen,
        debounceMs,
        maxSuggestions: maxSuggestionsPerSection,
        minQueryLength,
        includeDropdownRecommendations,
        includeDropdownProductList,
        includeFilteredTabs,
        includeCategories,
        maxCategories,
        analyticsTags,
        enableRecentSearches: true,
    });
    // Sort and filter sections
    const enabledSections = useMemo(() => {
        return sections
            .filter(s => s.enabled !== false)
            .sort((a, b) => (a.order || 0) - (b.order || 0));
    }, [sections]);
    // Get section config
    const getSectionConfig = (id) => {
        return enabledSections.find(s => s.id === id);
    };
    // Build flat list of all navigable items
    const allItems = useMemo(() => {
        const items = [];
        enabledSections.forEach((section, sectionIndex) => {
            switch (section.id) {
                case 'recent':
                    if (query.length === 0) {
                        recentSearches.slice(0, section.maxItems || 5).forEach(search => {
                            items.push({ type: 'recent', data: search, sectionIndex });
                        });
                    }
                    break;
                case 'suggestions':
                    suggestions.slice(0, section.maxItems || maxSuggestionsPerSection).forEach(suggestion => {
                        items.push({ type: 'suggestion', data: suggestion, sectionIndex });
                    });
                    break;
                case 'trending':
                    if (query.length === 0) {
                        (trendingSearches.length > 0 ? trendingSearches : topSearches)
                            .slice(0, section.maxItems || 5)
                            .forEach(trending => {
                            items.push({ type: 'trending', data: trending, sectionIndex });
                        });
                    }
                    break;
            }
        });
        return items;
    }, [enabledSections, query, recentSearches, suggestions, trendingSearches, topSearches, maxSuggestionsPerSection]);
    // Navigation functions
    const navigateNext = useCallback(() => {
        setActiveIndex(prev => (prev < allItems.length - 1 ? prev + 1 : 0));
    }, [allItems.length]);
    const navigatePrevious = useCallback(() => {
        setActiveIndex(prev => (prev > 0 ? prev - 1 : allItems.length - 1));
    }, [allItems.length]);
    const selectActive = useCallback(() => {
        if (activeIndex < 0 || activeIndex >= allItems.length)
            return;
        const item = allItems[activeIndex];
        switch (item.type) {
            case 'recent':
                onRecentSearchClick?.(item.data);
                break;
            case 'suggestion':
                onSuggestionSelect?.(item.data);
                addRecentSearch(item.data.query, item.data.count);
                break;
            case 'trending':
                onSuggestionSelect?.({ query: item.data.query, count: item.data.count });
                addRecentSearch(item.data.query);
                break;
        }
    }, [activeIndex, allItems, onRecentSearchClick, onSuggestionSelect, addRecentSearch]);
    // Expose ref methods
    useImperativeHandle(ref, () => ({
        getActiveIndex: () => activeIndex,
        setActiveIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        getTotalItems: () => allItems.length,
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, allItems.length]);
    // Highlight query in text
    const highlightQuery = (text) => {
        if (!query)
            return text;
        const parts = text.split(new RegExp(`(${query})`, 'gi'));
        return parts.map((part, i) => part.toLowerCase() === query.toLowerCase() ? (React.createElement("span", { key: i, style: styles.highlight }, part)) : part);
    };
    // Get item index offset for a section
    const getItemIndex = (sectionId, itemIndex) => {
        let offset = 0;
        for (const item of allItems) {
            const sectionConfig = enabledSections[item.sectionIndex];
            if (sectionConfig.id === sectionId) {
                return offset + itemIndex;
            }
            if (item.sectionIndex < enabledSections.findIndex(s => s.id === sectionId)) {
                offset++;
            }
        }
        return offset + itemIndex;
    };
    // Render recent searches section
    const renderRecentSection = () => {
        const config = getSectionConfig('recent');
        if (!config || query.length > 0 || recentSearches.length === 0)
            return null;
        return (React.createElement("div", { className: clsx('seekora-section', 'seekora-section-recent', classNames.section) },
            showSectionHeaders && (React.createElement("div", { style: styles.sectionHeader },
                React.createElement("h3", { style: styles.sectionTitle }, config.title || 'Recent Searches'),
                recentSearches.length > (config.maxItems || 5) && (React.createElement("button", { style: styles.sectionAction, onClick: () => onViewAllClick?.('recent') }, "View all")))),
            recentSearches.slice(0, config.maxItems || 5).map((search, index) => {
                const itemIndex = getItemIndex('recent', index);
                const isActive = activeIndex === itemIndex;
                return (React.createElement("div", { key: `recent-${search.query}`, role: "option", "aria-selected": isActive, style: { ...styles.item, ...(isActive ? styles.itemActive : {}) }, onClick: () => {
                        onRecentSearchClick?.(search);
                    }, onMouseEnter: () => setActiveIndex(itemIndex), className: clsx(classNames.recentItem, isActive && classNames.suggestionItemActive) }, renderRecentItem ? renderRecentItem(search) : (React.createElement(React.Fragment, null,
                    React.createElement(ClockIcon, null),
                    React.createElement("div", { style: styles.itemContent },
                        React.createElement("p", { style: styles.itemQuery }, search.query)),
                    React.createElement("button", { style: styles.removeButton, onClick: (e) => {
                            e.stopPropagation();
                            removeRecentSearch(search.query);
                            onRecentSearchRemove?.(search);
                        }, "aria-label": "Remove" },
                        React.createElement(CloseIcon, null))))));
            })));
    };
    // Render suggestions section
    const renderSuggestionsSection = () => {
        const config = getSectionConfig('suggestions');
        if (!config || suggestions.length === 0)
            return null;
        return (React.createElement("div", { className: clsx('seekora-section', 'seekora-section-suggestions', classNames.section) },
            showSectionHeaders && query.length > 0 && (React.createElement("div", { style: styles.sectionHeader },
                React.createElement("h3", { style: styles.sectionTitle }, config.title || 'Suggestions'))),
            suggestions.slice(0, config.maxItems || maxSuggestionsPerSection).map((suggestion, index) => {
                const itemIndex = allItems.findIndex((item, idx) => item.type === 'suggestion' &&
                    allItems.slice(0, idx).filter(i => i.type === 'suggestion').length === index);
                const isActive = activeIndex === itemIndex;
                return (React.createElement("div", { key: suggestion.objectID || `suggestion-${index}`, role: "option", "aria-selected": isActive, style: { ...styles.item, ...(isActive ? styles.itemActive : {}) }, onClick: () => {
                        onSuggestionSelect?.(suggestion);
                        addRecentSearch(suggestion.query, suggestion.count);
                    }, onMouseEnter: () => setActiveIndex(itemIndex), className: clsx(classNames.suggestionItem, isActive && classNames.suggestionItemActive) }, renderSuggestion ? renderSuggestion(suggestion, isActive) : (React.createElement(React.Fragment, null,
                    React.createElement(SearchIcon, null),
                    React.createElement("div", { style: styles.itemContent },
                        React.createElement("p", { style: styles.itemQuery }, highlightQuery(suggestion.query)),
                        includeCategories && suggestion.categories && suggestion.categories.length > 0 && (React.createElement("div", { style: styles.categoriesContainer }, suggestion.categories.slice(0, maxCategories).map((category, catIndex) => (renderCategory ? renderCategory(category) : (React.createElement("span", { key: `cat-${catIndex}`, style: {
                                ...styles.categoryPill,
                                ...(hoveredCategory === category.value ? styles.categoryPillHover : {}),
                            }, onClick: (e) => {
                                e.stopPropagation();
                                onCategoryClick?.(category);
                            }, onMouseEnter: () => setHoveredCategory(category.value), onMouseLeave: () => setHoveredCategory(null) },
                            category.value,
                            showCategoryCounts && category.count !== undefined && (React.createElement("span", { style: styles.categoryCount },
                                "(",
                                category.count,
                                ")"))))))))),
                    showCounts && suggestion.count !== undefined && (React.createElement("span", { style: styles.itemCount }, suggestion.count.toLocaleString()))))));
            })));
    };
    // Render trending section
    const renderTrendingSection = () => {
        const config = getSectionConfig('trending');
        const trending = trendingSearches.length > 0 ? trendingSearches : topSearches;
        if (!config || query.length > 0 || trending.length === 0)
            return null;
        return (React.createElement("div", { className: clsx('seekora-section', 'seekora-section-trending', classNames.section) },
            showSectionHeaders && (React.createElement("div", { style: styles.sectionHeader },
                React.createElement("h3", { style: styles.sectionTitle }, config.title || 'Trending'))),
            React.createElement("div", { style: styles.trendingList }, trending.slice(0, config.maxItems || 5).map((item, index) => {
                const itemIndex = allItems.findIndex((navItem, idx) => navItem.type === 'trending' &&
                    allItems.slice(0, idx).filter(i => i.type === 'trending').length === index);
                const isActive = activeIndex === itemIndex;
                return renderTrendingItem ? renderTrendingItem(item, index) : (React.createElement("button", { key: `trending-${item.query}`, style: {
                        ...styles.trendingChip,
                        ...(isActive ? styles.trendingChipHover : {}),
                    }, onClick: () => {
                        onSuggestionSelect?.({
                            query: item.query,
                            count: item.count,
                        });
                        addRecentSearch(item.query);
                    }, onMouseEnter: () => setActiveIndex(itemIndex), className: clsx(classNames.trendingItem, isActive && classNames.suggestionItemActive) },
                    React.createElement("span", { style: styles.trendingRank }, index + 1),
                    React.createElement("span", null, item.query),
                    React.createElement(TrendingIcon, null)));
            }))));
    };
    // Don't render if closed or no content
    if (!isOpen)
        return null;
    const showContent = hasContent || loading || query.length === 0;
    if (!showContent)
        return null;
    return (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": ariaLabel, className: clsx('seekora-rich-suggestions', classNames.root, classNames.container), style: {
            position: 'absolute',
            width,
            zIndex,
            ...styles.container,
            ...style,
        } },
        header && React.createElement("div", { style: styles.header }, header),
        React.createElement("div", { style: { ...styles.content, maxHeight } },
            enabledSections.map((section, index) => {
                let content = null;
                switch (section.id) {
                    case 'recent':
                        content = renderRecentSection();
                        break;
                    case 'suggestions':
                        content = renderSuggestionsSection();
                        break;
                    case 'trending':
                        content = renderTrendingSection();
                        break;
                }
                if (!content)
                    return null;
                return (React.createElement(React.Fragment, { key: section.id },
                    index > 0 && React.createElement("div", { style: styles.divider }),
                    content));
            }),
            !loading && query.length > 0 && suggestions.length === 0 && (React.createElement("div", { style: styles.emptyState },
                React.createElement("p", null,
                    "No suggestions found for \"",
                    query,
                    "\"")))),
        footer && React.createElement("div", { style: styles.footer }, footer),
        React.createElement("style", null, `
          .seekora-rich-suggestions [role="option"]:hover button {
            opacity: 1;
          }
          .seekora-rich-suggestions mark {
            background-color: var(--seekora-highlight-bg, #fef9c3);
            font-weight: 600;
            border-radius: 2px;
            padding: 0 1px;
          }
        `)));
});
export default RichQuerySuggestions;
