/**
 * GoogleDropdown - Google-style Clean Search Suggestions
 *
 * Features:
 * - Ultra-clean, minimal design
 * - Instant suggestions with smooth animations
 * - Trending searches when empty
 * - "I'm Feeling Lucky" style quick actions
 * - Voice search integration ready
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from 'react';
import { extractSuggestion, highlightTextReact, cx, mergeStyles, generateCSSVariables, scrollIntoViewIfNeeded, } from './utils';
import { useResponsive } from './styles/responsive';
import { useInjectResponsiveStyles } from './styles';
// ============================================================================
// Styles
// ============================================================================
const createStyles = (isMobile = false) => ({
    root: {
        position: isMobile ? 'fixed' : 'absolute',
        top: isMobile ? 0 : '100%',
        left: 0,
        right: 0,
        bottom: isMobile ? 0 : 'auto',
        marginTop: isMobile ? 0 : '4px',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        color: 'var(--seekora-text-primary, #202124)',
        borderRadius: isMobile ? '0' : '24px',
        boxShadow: isMobile ? 'none' : '0 4px 20px rgba(0,0,0,0.12)',
        overflow: 'hidden',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        fontSize: isMobile ? '17px' : '15px',
        display: 'flex',
        flexDirection: 'column',
    },
    list: {
        listStyle: 'none',
        margin: 0,
        padding: '8px',
        flex: 1,
        overflowY: 'auto',
    },
    item: {
        display: 'flex',
        alignItems: 'center',
        padding: isMobile ? '12px 14px' : '10px 14px',
        cursor: 'pointer',
        transition: 'all 100ms ease',
        gap: '12px',
        minHeight: '44px',
        borderRadius: '12px',
        margin: '2px 0',
        color: 'var(--seekora-text-primary, #202124)',
    },
    itemActive: {
        backgroundColor: 'var(--seekora-bg-hover, #f5f5f5)',
        color: 'var(--seekora-text-primary, #202124)',
    },
    itemIcon: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'var(--seekora-text-tertiary, #9aa0a6)',
        flexShrink: 0,
    },
    itemContent: {
        flex: 1,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        minWidth: 0,
    },
    itemText: {
        fontSize: '16px',
        color: 'var(--seekora-text-primary, #202124)',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    itemTextBold: {
        fontWeight: 400,
    },
    itemMatch: {
        fontWeight: 700,
    },
    itemAction: {
        fontSize: '14px',
        color: 'var(--seekora-link, #1a73e8)',
        marginLeft: '16px',
        opacity: 0,
        transition: 'opacity 100ms',
        whiteSpace: 'nowrap',
    },
    itemActionVisible: {
        opacity: 1,
    },
    removeBtn: {
        padding: '4px 8px',
        background: 'none',
        border: 'none',
        color: 'var(--seekora-link, #1a73e8)',
        cursor: 'pointer',
        fontSize: '13px',
        borderRadius: '4px',
        opacity: 0,
        transition: 'opacity 100ms, background 100ms',
    },
    removeBtnVisible: {
        opacity: 1,
    },
    removeBtnHover: {
        backgroundColor: 'var(--seekora-bg-hover, #e8f0fe)',
        color: 'var(--seekora-text-primary, #202124)',
    },
    divider: {
        height: '1px',
        backgroundColor: 'var(--seekora-border-color, #e8eaed)',
        margin: '8px 0',
    },
    sectionTitle: {
        padding: '12px 16px 8px',
        fontSize: '12px',
        fontWeight: 500,
        color: 'var(--seekora-text-secondary, #5f6368)',
        textTransform: 'uppercase',
        letterSpacing: '0.8px',
    },
    trending: {
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        color: 'var(--seekora-success, #1e8e3e)',
        fontSize: '12px',
        marginLeft: 'auto',
    },
    trendingIcon: {
        width: '12px',
        height: '12px',
    },
    footer: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '12px 16px',
        borderTop: '1px solid var(--seekora-border-color, #e8eaed)',
        gap: '24px',
        backgroundColor: 'var(--seekora-bg-secondary, #f8f9fa)',
    },
    footerButton: {
        padding: '8px 16px',
        backgroundColor: 'var(--seekora-bg-tertiary, #f1f3f4)',
        border: '1px solid var(--seekora-border-color, #f1f3f4)',
        borderRadius: '4px',
        fontSize: '14px',
        color: 'var(--seekora-text-secondary, #3c4043)',
        cursor: 'pointer',
        transition: 'border-color 100ms, box-shadow 100ms',
    },
    footerButtonHover: {
        borderColor: 'var(--seekora-border-color-dark, #dadce0)',
        boxShadow: '0 1px 1px rgba(0,0,0,0.1)',
    },
    voiceBtn: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: '24px',
        height: '24px',
        borderRadius: '50%',
        background: 'none',
        border: 'none',
        cursor: 'pointer',
        color: 'var(--seekora-primary, #4285f4)',
        transition: 'background 100ms',
    },
    voiceBtnHover: {
        backgroundColor: 'var(--seekora-bg-hover, #f1f3f4)',
        color: 'var(--seekora-text-primary, #202124)',
    },
    empty: {
        padding: '24px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #5f6368)',
        fontSize: '14px',
    },
});
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none" },
    React.createElement("path", { d: "M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z", fill: "currentColor" })));
const ClockIcon = () => (React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none" },
    React.createElement("path", { d: "M13 3a9 9 0 00-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0013 21a9 9 0 000-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z", fill: "currentColor" })));
const TrendingIcon = () => (React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none" },
    React.createElement("path", { d: "M16 6l2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z", fill: "currentColor" })));
const RemoveIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", width: "18", height: "18" },
    React.createElement("path", { d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z", fill: "currentColor" })));
const ArrowIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", width: "20", height: "20" },
    React.createElement("path", { d: "M9 5l-4 4 4 4", stroke: "currentColor", strokeWidth: "2", fill: "none", transform: "rotate(-90 12 12)" })));
export const GoogleDropdown = forwardRef(function GoogleDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], recentSearches = [], trendingSearches = [], suggestionFields = { query: 'query' }, theme = {}, showFeelingLucky = true, feelingLuckyText = "I'm Feeling Lucky", showRemoveRecent = true, showVoiceSearch = false, showTrendingIndicator = true, width = '100%', maxHeight = '400px', zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onRecentClick, onRecentRemove, onVoiceSearch, onFeelingLucky, onClose, onSearchSubmit, header, footer, renderEmpty, } = props;
    // Inject global responsive styles
    useInjectResponsiveStyles();
    // Responsive state
    const responsive = useResponsive();
    const { isMobile } = responsive;
    const styles = useMemo(() => createStyles(isMobile), [isMobile]);
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [hoveredIndex, setHoveredIndex] = useState(-1);
    const [hoveredBtn, setHoveredBtn] = useState(null);
    // Process suggestions
    const processedSuggestions = useMemo(() => suggestions.map(s => extractSuggestion(s, suggestionFields)), [suggestions, suggestionFields]);
    const recentQueries = useMemo(() => recentSearches.map(r => typeof r === 'string' ? r : r.query).slice(0, 5), [recentSearches]);
    const trendingQueries = useMemo(() => trendingSearches.map(t => typeof t === 'string' ? t : t.query).slice(0, 5), [trendingSearches]);
    // All items for navigation
    const allItems = useMemo(() => {
        const items = [];
        if (query.length === 0) {
            recentQueries.forEach(q => items.push({ type: 'recent', query: q }));
            trendingQueries.forEach(q => items.push({ type: 'trending', query: q }));
        }
        else {
            processedSuggestions.forEach(s => items.push({ type: 'suggestion', query: s.query, data: s }));
        }
        return items;
    }, [query, recentQueries, trendingQueries, processedSuggestions]);
    // Navigation
    const navigateNext = useCallback(() => {
        setActiveIndex(prev => Math.min(prev + 1, allItems.length - 1));
    }, [allItems.length]);
    const navigatePrevious = useCallback(() => {
        setActiveIndex(prev => Math.max(prev - 1, -1));
    }, []);
    const selectActive = useCallback(() => {
        if (activeIndex < 0) {
            if (query)
                onSearchSubmit?.(query);
            return;
        }
        const item = allItems[activeIndex];
        if (item.type === 'recent' || item.type === 'trending') {
            onRecentClick?.(item.query);
        }
        else {
            onSuggestionSelect?.(item.data?._raw || { query: item.query }, activeIndex);
        }
    }, [activeIndex, allItems, query, onSearchSubmit, onRecentClick, onSuggestionSelect]);
    // Expose ref
    useImperativeHandle(ref, () => ({
        getActiveIndex: () => activeIndex,
        setActiveIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        focus: () => containerRef.current?.focus(),
        close: () => onClose?.(),
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, onClose]);
    // Reset active index when items change
    useEffect(() => {
        setActiveIndex(-1);
    }, [query]);
    // Scroll active item into view
    useEffect(() => {
        if (activeIndex >= 0 && containerRef.current) {
            const activeEl = containerRef.current.querySelector(`[data-index="${activeIndex}"]`);
            if (activeEl) {
                scrollIntoViewIfNeeded(activeEl, containerRef.current);
            }
        }
    }, [activeIndex]);
    if (!isOpen)
        return null;
    const cssVariables = generateCSSVariables(theme);
    const showRecent = query.length === 0 && recentQueries.length > 0;
    const showTrending = query.length === 0 && trendingQueries.length > 0;
    const renderItem = (item, index, globalIndex) => {
        const isActive = activeIndex === globalIndex;
        const isHovered = hoveredIndex === globalIndex;
        const showAction = isActive || isHovered;
        return (React.createElement("li", { key: `${item.type}-${item.query}-${index}`, "data-index": globalIndex, role: "option", "aria-selected": isActive, style: mergeStyles(styles.item, isActive || isHovered ? styles.itemActive : undefined), onClick: () => {
                if (item.type === 'recent' || item.type === 'trending') {
                    onRecentClick?.(item.query);
                }
                else {
                    onSuggestionSelect?.(item.data?._raw || { query: item.query }, index);
                }
            }, onMouseEnter: () => {
                setHoveredIndex(globalIndex);
                setActiveIndex(globalIndex);
            }, onMouseLeave: () => setHoveredIndex(-1) },
            React.createElement("div", { style: styles.itemIcon }, item.type === 'recent' ? React.createElement(ClockIcon, null) :
                item.type === 'trending' ? React.createElement(TrendingIcon, null) :
                    React.createElement(SearchIcon, null)),
            React.createElement("div", { style: styles.itemContent },
                React.createElement("span", { style: styles.itemText }, query ? highlightTextReact(item.query, query, { tag: 'b' }) : item.query),
                React.createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
                    item.type === 'trending' && showTrendingIndicator && (React.createElement("span", { style: styles.trending },
                        React.createElement(TrendingIcon, null),
                        "Trending")),
                    item.type === 'recent' && showRemoveRecent && (React.createElement("button", { style: mergeStyles(styles.removeBtn, showAction ? styles.removeBtnVisible : undefined), onClick: (e) => {
                            e.stopPropagation();
                            onRecentRemove?.(item.query);
                        }, "aria-label": `Remove ${item.query}` }, "Remove")),
                    React.createElement("span", { style: mergeStyles(styles.itemAction, showAction ? styles.itemActionVisible : undefined) },
                        React.createElement(ArrowIcon, null))))));
    };
    let globalIndex = 0;
    return (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": "Search suggestions", className: cx('seekora-google-dropdown', className, classNames.root), style: mergeStyles(styles.root, { width, maxHeight: 'none', zIndex }, cssVariables, style), tabIndex: -1 },
        React.createElement("style", null, `
          @keyframes seekora-spin {
            to { transform: rotate(360deg); }
          }
        `),
        header,
        React.createElement(React.Fragment, null,
            React.createElement("ul", { style: styles.list },
                showRecent && (React.createElement(React.Fragment, null,
                    recentQueries.map((q, idx) => {
                        const item = { type: 'recent', query: q };
                        const el = renderItem(item, idx, globalIndex);
                        globalIndex++;
                        return el;
                    }),
                    showTrending && React.createElement("div", { style: styles.divider }))),
                showTrending && (React.createElement(React.Fragment, null,
                    !showRecent && React.createElement("div", { style: styles.sectionTitle }, "Trending searches"),
                    trendingQueries.map((q, idx) => {
                        const item = { type: 'trending', query: q };
                        const el = renderItem(item, idx, globalIndex);
                        globalIndex++;
                        return el;
                    }))),
                query && processedSuggestions.length > 0 && (processedSuggestions.map((s, idx) => {
                    const item = { type: 'suggestion', query: s.query, data: s };
                    const el = renderItem(item, idx, globalIndex);
                    globalIndex++;
                    return el;
                })),
                query && processedSuggestions.length === 0 && !loading && (renderEmpty ? renderEmpty(query) : (React.createElement("li", { style: styles.empty },
                    "No suggestions for \"",
                    query,
                    "\"")))),
            (showFeelingLucky || showVoiceSearch) && (React.createElement("div", { style: styles.footer }, showFeelingLucky && (React.createElement(React.Fragment, null,
                React.createElement("button", { style: mergeStyles(styles.footerButton, hoveredBtn === 'search' ? styles.footerButtonHover : undefined), onMouseEnter: () => setHoveredBtn('search'), onMouseLeave: () => setHoveredBtn(null), onClick: () => onSearchSubmit?.(query || (activeIndex >= 0 ? allItems[activeIndex]?.query : '')) }, "Search"),
                React.createElement("button", { style: mergeStyles(styles.footerButton, hoveredBtn === 'lucky' ? styles.footerButtonHover : undefined), onMouseEnter: () => setHoveredBtn('lucky'), onMouseLeave: () => setHoveredBtn(null), onClick: () => onFeelingLucky?.(query || (activeIndex >= 0 ? allItems[activeIndex]?.query : '')) }, feelingLuckyText)))))),
        footer));
});
export default GoogleDropdown;
