/**
 * MinimalDropdown - Ultra-Clean Minimalist Style
 *
 * Features:
 * - Stripped-down, distraction-free design
 * - Focus on typography and whitespace
 * - Subtle animations
 * - Perfect for editorial/content sites
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from 'react';
import { extractSuggestion, extractProduct, formatPrice, highlightTextReact, cx, mergeStyles, generateCSSVariables, scrollIntoViewIfNeeded, } from './utils';
import { useResponsive } from './styles/responsive';
import { useInjectResponsiveStyles } from './styles';
// ============================================================================
// Styles
// ============================================================================
const createStyles = () => ({
    root: {
        position: 'absolute',
        top: '100%',
        left: 0,
        right: 0,
        marginTop: '4px',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        border: '1px solid var(--seekora-border-color, #e5e5e5)',
        fontFamily: 'var(--seekora-font-family, "Inter", -apple-system, sans-serif)',
        fontSize: 'var(--seekora-font-size, 15px)',
        letterSpacing: '-0.01em',
    },
    item: {
        display: 'flex',
        alignItems: 'center',
        padding: '16px 20px',
        cursor: 'pointer',
        transition: 'background-color 150ms ease, padding-left 150ms ease',
        borderBottom: '1px solid var(--seekora-border-color, #e8e8e8)',
        gap: '16px',
        color: 'var(--seekora-text-primary, #111)',
    },
    itemLast: {
        borderBottom: 'none',
    },
    itemActive: {
        backgroundColor: 'var(--seekora-bg-hover, #f5f5f5)',
        color: 'var(--seekora-text-primary, #111)',
        paddingLeft: '24px',
    },
    itemIndex: {
        fontSize: '11px',
        fontWeight: 500,
        color: 'var(--seekora-text-tertiary, #999)',
        fontFamily: 'monospace',
        minWidth: '20px',
    },
    itemContent: {
        flex: 1,
        minWidth: 0,
    },
    itemQuery: {
        fontSize: '15px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, #111)',
    },
    itemMeta: {
        fontSize: '13px',
        color: 'var(--seekora-text-secondary, #666)',
        marginTop: '4px',
        fontWeight: 400,
    },
    itemType: {
        fontSize: '10px',
        fontWeight: 600,
        color: 'var(--seekora-text-tertiary, #999)',
        textTransform: 'uppercase',
        letterSpacing: '0.1em',
        padding: '4px 8px',
        backgroundColor: 'var(--seekora-bg-secondary, #f5f5f5)',
    },
    productRow: {
        display: 'flex',
        alignItems: 'center',
        padding: '16px 20px',
        cursor: 'pointer',
        transition: 'background-color 150ms ease',
        borderBottom: '1px solid var(--seekora-border-color, #e8e8e8)',
        gap: '16px',
        color: 'var(--seekora-text-primary, #111)',
    },
    productRowActive: {
        backgroundColor: 'var(--seekora-bg-hover, #f5f5f5)',
        color: 'var(--seekora-text-primary, #111)',
    },
    productImage: {
        width: '56px',
        height: '56px',
        objectFit: 'cover',
        backgroundColor: 'var(--seekora-bg-secondary, #f5f5f5)',
        flexShrink: 0,
    },
    productContent: {
        flex: 1,
        minWidth: 0,
    },
    productTitle: {
        fontSize: '14px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, #111)',
        marginBottom: '4px',
    },
    productPrice: {
        fontSize: '14px',
        color: 'var(--seekora-text-secondary, #666)',
    },
    divider: {
        padding: '12px 20px 8px',
        fontSize: '10px',
        fontWeight: 600,
        color: 'var(--seekora-text-tertiary, #999)',
        textTransform: 'uppercase',
        letterSpacing: '0.15em',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        borderBottom: '1px solid var(--seekora-border-color, #f0f0f0)',
    },
    footer: {
        padding: '12px 20px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: 'var(--seekora-bg-secondary, #fafafa)',
        fontSize: '12px',
        color: 'var(--seekora-text-tertiary, #999)',
        borderTop: '1px solid var(--seekora-border-color, #e5e5e5)',
    },
    footerHint: {
        display: 'flex',
        alignItems: 'center',
        gap: '12px',
    },
    kbd: {
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '2px 6px',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        border: '1px solid var(--seekora-border-color, #ddd)',
        fontSize: '10px',
        fontFamily: 'monospace',
    },
    loading: {
        padding: '40px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #666)',
        fontSize: '14px',
    },
    empty: {
        padding: '40px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #666)',
        fontSize: '14px',
    },
    highlight: {
        backgroundColor: 'var(--seekora-highlight-bg, #fff3cd)',
        padding: '0 2px',
    },
});
export const MinimalDropdown = forwardRef(function MinimalDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], recentSearches = [], suggestionFields = { query: 'query' }, productFields = { id: 'id', title: 'title' }, productDisplay = {}, theme = {}, showIndices = false, showTypeLabels = false, showSectionDividers = true, width = '100%', maxHeight = '400px', zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onProductClick, onRecentClick, onClose, onSearchSubmit, header, footer, renderEmpty, } = props;
    // Inject global responsive styles
    useInjectResponsiveStyles();
    // Responsive state
    const responsive = useResponsive();
    const { isMobile } = responsive;
    const styles = useMemo(() => createStyles(), []);
    const containerRef = useRef(null);
    const listRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    // Process data
    const processedSuggestions = useMemo(() => suggestions.map(s => extractSuggestion(s, suggestionFields)), [suggestions, suggestionFields]);
    const processedProducts = useMemo(() => products.map(p => extractProduct(p, productFields)), [products, productFields]);
    const recentQueries = useMemo(() => recentSearches.map(r => typeof r === 'string' ? r : r.query).slice(0, 3), [recentSearches]);
    // All items for navigation
    const allItems = useMemo(() => {
        const items = [];
        if (!query && recentQueries.length > 0) {
            recentQueries.forEach(q => items.push({ type: 'recent', data: q }));
        }
        processedSuggestions.forEach(s => items.push({ type: 'suggestion', data: s }));
        processedProducts.forEach(p => items.push({ type: 'product', data: p }));
        return items;
    }, [query, recentQueries, processedSuggestions, processedProducts]);
    // 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(() => {
        const item = allItems[activeIndex];
        if (!item) {
            if (query)
                onSearchSubmit?.(query);
            return;
        }
        switch (item.type) {
            case 'recent':
                onRecentClick?.(item.data);
                break;
            case 'suggestion':
                onSuggestionSelect?.(item.data._raw, activeIndex);
                break;
            case 'product':
                onProductClick?.(item.data._raw, activeIndex);
                break;
        }
    }, [activeIndex, allItems, query, onSearchSubmit, onRecentClick, onSuggestionSelect, onProductClick]);
    // Expose ref
    useImperativeHandle(ref, () => ({
        getActiveIndex: () => activeIndex,
        setActiveIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        focus: () => containerRef.current?.focus(),
        close: () => onClose?.(),
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, onClose]);
    // Scroll active into view
    useEffect(() => {
        if (listRef.current && activeIndex >= 0) {
            const activeEl = listRef.current.querySelector(`[data-index="${activeIndex}"]`);
            if (activeEl) {
                scrollIntoViewIfNeeded(activeEl, listRef.current);
            }
        }
    }, [activeIndex]);
    // Reset on query change
    useEffect(() => {
        setActiveIndex(-1);
    }, [query]);
    if (!isOpen)
        return null;
    const cssVariables = generateCSSVariables(theme);
    const showRecent = !query && recentQueries.length > 0;
    let globalIndex = 0;
    return (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": "Search suggestions", className: cx('seekora-minimal-dropdown', className, classNames.root), style: mergeStyles(styles.root, { width, zIndex }, cssVariables, style), tabIndex: -1 },
        React.createElement("style", null, `
          .seekora-minimal-dropdown mark {
            background-color: var(--seekora-highlight-bg, #fff3cd);
            padding: 0 2px;
          }
        `),
        header,
        React.createElement("div", { ref: listRef, style: { maxHeight, overflowY: 'auto' } }, allItems.length === 0 ? (renderEmpty ? renderEmpty(query) : (React.createElement("div", { style: styles.empty }, query ? `No results for "${query}"` : 'Start typing to search'))) : (React.createElement(React.Fragment, null,
            showRecent && (React.createElement(React.Fragment, null,
                showSectionDividers && (React.createElement("div", { style: styles.divider }, "Recent")),
                recentQueries.map((q, idx) => {
                    const itemIdx = globalIndex++;
                    const isActive = activeIndex === itemIdx;
                    const isLast = idx === recentQueries.length - 1 && !processedSuggestions.length && !processedProducts.length;
                    return (React.createElement("div", { key: `recent-${q}`, "data-index": itemIdx, style: mergeStyles(styles.item, isActive ? styles.itemActive : undefined, isLast ? styles.itemLast : undefined), onClick: () => onRecentClick?.(q), onMouseEnter: () => setActiveIndex(itemIdx) },
                        showIndices && (React.createElement("span", { style: styles.itemIndex }, itemIdx + 1)),
                        React.createElement("div", { style: styles.itemContent },
                            React.createElement("div", { style: styles.itemQuery }, q)),
                        showTypeLabels && (React.createElement("span", { style: styles.itemType }, "Recent"))));
                }))),
            processedSuggestions.length > 0 && (React.createElement(React.Fragment, null,
                showSectionDividers && (showRecent || false) && (React.createElement("div", { style: styles.divider }, "Suggestions")),
                processedSuggestions.map((s, idx) => {
                    const itemIdx = globalIndex++;
                    const isActive = activeIndex === itemIdx;
                    const isLast = idx === processedSuggestions.length - 1 && !processedProducts.length;
                    return (React.createElement("div", { key: s.id || `suggestion-${idx}`, "data-index": itemIdx, style: mergeStyles(styles.item, isActive ? styles.itemActive : undefined, isLast ? styles.itemLast : undefined), onClick: () => onSuggestionSelect?.(s._raw, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                        showIndices && (React.createElement("span", { style: styles.itemIndex }, itemIdx + 1)),
                        React.createElement("div", { style: styles.itemContent },
                            React.createElement("div", { style: styles.itemQuery }, highlightTextReact(s.query, query, { tag: 'mark' })),
                            s.count && (React.createElement("div", { style: styles.itemMeta },
                                s.count.toLocaleString(),
                                " results"))),
                        showTypeLabels && (React.createElement("span", { style: styles.itemType }, "Search"))));
                }))),
            processedProducts.length > 0 && (React.createElement(React.Fragment, null,
                showSectionDividers && (React.createElement("div", { style: styles.divider }, "Products")),
                processedProducts.slice(0, 4).map((p, idx) => {
                    const itemIdx = globalIndex++;
                    const isActive = activeIndex === itemIdx;
                    return (React.createElement("div", { key: p.id, "data-index": itemIdx, style: mergeStyles(styles.productRow, isActive ? styles.productRowActive : undefined), onClick: () => onProductClick?.(p._raw, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                        p.image && (React.createElement("img", { src: p.image, alt: p.title, style: styles.productImage, loading: "lazy" })),
                        React.createElement("div", { style: styles.productContent },
                            React.createElement("div", { style: styles.productTitle }, p.title),
                            p.price !== undefined && (React.createElement("div", { style: styles.productPrice }, formatPrice(p.price, {
                                currency: productDisplay.currency || p.currency || '$'
                            })))),
                        showTypeLabels && (React.createElement("span", { style: styles.itemType }, "Product"))));
                })))))),
        footer !== undefined ? footer : (React.createElement("div", { style: styles.footer },
            React.createElement("div", { style: styles.footerHint },
                React.createElement("span", null,
                    React.createElement("span", { style: styles.kbd }, "\u2191"),
                    " ",
                    React.createElement("span", { style: styles.kbd }, "\u2193"),
                    " navigate"),
                React.createElement("span", null,
                    React.createElement("span", { style: styles.kbd }, "\u21B5"),
                    " select"),
                React.createElement("span", null,
                    React.createElement("span", { style: styles.kbd }, "esc"),
                    " close")),
            React.createElement("span", null,
                allItems.length,
                " results")))));
});
export default MinimalDropdown;
