/**
 * SpotlightDropdown - macOS Spotlight / Command Palette Style
 *
 * Features:
 * - Clean, centered modal design
 * - Category grouping with keyboard navigation
 * - Instant preview panel
 * - Actions/commands support
 * - Keyboard-first interaction
 */
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 = () => ({
    overlay: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        backdropFilter: 'blur(4px)',
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'center',
        paddingTop: '15vh',
        zIndex: 9999,
    },
    root: {
        backgroundColor: 'var(--seekora-bg-surface, rgba(255, 255, 255, 0.95))',
        borderRadius: 'var(--seekora-border-radius, 12px)',
        boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255,255,255,0.1)',
        overflow: 'hidden',
        fontFamily: 'var(--seekora-font-family, -apple-system, BlinkMacSystemFont, "SF Pro Display", sans-serif)',
        fontSize: 'var(--seekora-font-size, 14px)',
        backdropFilter: 'blur(20px)',
    },
    searchContainer: {
        display: 'flex',
        alignItems: 'center',
        padding: '12px 16px',
        gap: '12px',
        borderBottom: '1px solid var(--seekora-border-color, rgba(0,0,0,0.1))',
    },
    searchIcon: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'var(--seekora-text-tertiary, #86868b)',
        flexShrink: 0,
    },
    searchInput: {
        flex: 1,
        border: 'none',
        background: 'transparent',
        fontSize: '17px',
        fontWeight: 300,
        color: 'var(--seekora-text-primary, #1d1d1f)',
        outline: 'none',
        fontFamily: 'inherit',
    },
    shortcut: {
        display: 'flex',
        alignItems: 'center',
        gap: '4px',
        fontSize: '12px',
        color: 'var(--seekora-text-tertiary, #86868b)',
    },
    kbd: {
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        minWidth: '20px',
        height: '20px',
        padding: '0 4px',
        backgroundColor: 'var(--seekora-bg-tertiary, rgba(0,0,0,0.05))',
        borderRadius: '4px',
        fontSize: '11px',
        fontFamily: 'SF Mono, Monaco, monospace',
    },
    content: {
        display: 'flex',
        maxHeight: '400px',
    },
    resultsColumn: {
        flex: 1,
        overflowY: 'auto',
        minWidth: '300px',
    },
    previewColumn: {
        width: '280px',
        borderLeft: '1px solid var(--seekora-border-color, rgba(0,0,0,0.1))',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(0,0,0,0.02))',
        display: 'flex',
        flexDirection: 'column',
    },
    section: {
        padding: '8px 0',
    },
    sectionTitle: {
        padding: '8px 16px 6px',
        fontSize: '11px',
        fontWeight: 600,
        color: 'var(--seekora-text-tertiary, #86868b)',
        textTransform: 'uppercase',
        letterSpacing: '0.5px',
    },
    item: {
        display: 'flex',
        alignItems: 'center',
        padding: '8px 16px',
        gap: '12px',
        cursor: 'pointer',
        transition: 'background-color 50ms',
        margin: '0 8px',
        borderRadius: '6px',
    },
    itemActive: {
        backgroundColor: 'var(--seekora-primary, #007aff)',
        color: 'var(--seekora-text-inverse, #ffffff)',
    },
    itemIcon: {
        width: '32px',
        height: '32px',
        borderRadius: '6px',
        backgroundColor: 'var(--seekora-bg-tertiary, #f5f5f7)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'var(--seekora-text-secondary, #515154)',
        flexShrink: 0,
    },
    itemIconActive: {
        backgroundColor: 'rgba(255,255,255,0.2)',
        color: 'var(--seekora-text-inverse, #ffffff)',
    },
    itemIconImage: {
        width: '100%',
        height: '100%',
        objectFit: 'cover',
        borderRadius: '6px',
    },
    itemContent: {
        flex: 1,
        minWidth: 0,
    },
    itemTitle: {
        fontSize: '13px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, #1d1d1f)',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    itemTitleActive: {
        color: 'var(--seekora-text-inverse, #ffffff)',
    },
    itemSubtitle: {
        fontSize: '11px',
        color: 'var(--seekora-text-secondary, #86868b)',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        marginTop: '2px',
    },
    itemSubtitleActive: {
        color: 'var(--seekora-text-inverse, #ffffff)',
        opacity: 0.9,
    },
    itemAction: {
        fontSize: '11px',
        color: 'var(--seekora-text-tertiary, #86868b)',
        opacity: 0,
        transition: 'opacity 100ms',
    },
    itemActionVisible: {
        opacity: 1,
    },
    itemActionActive: {
        color: 'var(--seekora-text-inverse, #ffffff)',
        opacity: 0.8,
    },
    previewContent: {
        flex: 1,
        padding: '16px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
    },
    previewImage: {
        width: '160px',
        height: '160px',
        objectFit: 'contain',
        borderRadius: '8px',
        marginBottom: '16px',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
    },
    previewTitle: {
        fontSize: '14px',
        fontWeight: 600,
        color: 'var(--seekora-text-primary, #1d1d1f)',
        textAlign: 'center',
        marginBottom: '4px',
    },
    previewSubtitle: {
        fontSize: '12px',
        color: 'var(--seekora-text-secondary, #86868b)',
        textAlign: 'center',
        marginBottom: '8px',
    },
    previewPrice: {
        fontSize: '18px',
        fontWeight: 700,
        color: 'var(--seekora-primary, #007aff)',
    },
    previewActions: {
        display: 'flex',
        gap: '8px',
        marginTop: '16px',
    },
    previewAction: {
        padding: '6px 12px',
        fontSize: '12px',
        fontWeight: 500,
        borderRadius: '6px',
        border: 'none',
        cursor: 'pointer',
        transition: 'all 100ms',
    },
    previewActionPrimary: {
        backgroundColor: 'var(--seekora-primary, #007aff)',
        color: 'var(--seekora-text-inverse, #ffffff)',
    },
    previewActionSecondary: {
        backgroundColor: 'var(--seekora-bg-tertiary, #f5f5f7)',
        color: 'var(--seekora-text-primary, #1d1d1f)',
    },
    footer: {
        padding: '8px 16px',
        borderTop: '1px solid var(--seekora-border-color, rgba(0,0,0,0.1))',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(0,0,0,0.02))',
        fontSize: '11px',
        color: 'var(--seekora-text-tertiary, #86868b)',
    },
    footerActions: {
        display: 'flex',
        alignItems: 'center',
        gap: '16px',
    },
    footerAction: {
        display: 'flex',
        alignItems: 'center',
        gap: '4px',
    },
    loading: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '40px',
        color: 'var(--seekora-text-secondary, #86868b)',
    },
    spinner: {
        width: '24px',
        height: '24px',
        border: '2px solid var(--seekora-border-color, #e5e5e5)',
        borderTopColor: 'var(--seekora-primary, #007aff)',
        borderRadius: '50%',
        animation: 'seekora-spin 0.8s linear infinite',
    },
    empty: {
        padding: '40px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #86868b)',
    },
});
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 20 20", fill: "currentColor" },
    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 CommandIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { d: "M3.5 6A1.5 1.5 0 015 4.5h1.5A1.5 1.5 0 018 6v1.5H5A1.5 1.5 0 013.5 6zM8 6v8H5a1.5 1.5 0 110-3h3V8H5a1.5 1.5 0 010-3h3v1z" }),
    React.createElement("path", { d: "M12 6v8h3a1.5 1.5 0 100-3h-3V8h3a1.5 1.5 0 100-3h-3v1z" }),
    React.createElement("path", { d: "M16.5 6A1.5 1.5 0 0015 4.5h-1.5A1.5 1.5 0 0012 6v1.5h3A1.5 1.5 0 0016.5 6z" })));
const DocumentIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { fillRule: "evenodd", d: "M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z", clipRule: "evenodd" })));
const ShoppingIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { d: "M10 2a4 4 0 00-4 4v1H5a1 1 0 00-.994.89l-1 9A1 1 0 004 18h12a1 1 0 00.994-1.11l-1-9A1 1 0 0015 7h-1V6a4 4 0 00-4-4zm2 5V6a2 2 0 10-4 0v1h4zm-6 3a1 1 0 112 0 1 1 0 01-2 0zm7-1a1 1 0 100 2 1 1 0 000-2z" })));
const ClockIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    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" })));
export const SpotlightDropdown = forwardRef(function SpotlightDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], recentSearches = [], suggestionFields = { query: 'query' }, productFields = { id: 'id', title: 'title' }, productDisplay = {}, theme = {}, showPreview = true, asOverlay = true, placeholder = 'Powered by Seekora', showShortcuts = true, actions = [], width = '680px', maxHeight = '500px', zIndex = 9999, className, style, classNames = {}, inputRef, 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]);
    // Build flat list of all items
    const allItems = useMemo(() => {
        const items = [];
        // Actions first
        actions.forEach(action => {
            items.push({
                type: 'action',
                id: action.id,
                title: action.label,
                icon: action.icon,
                data: action,
            });
        });
        // Recent searches
        if (!query && recentQueries.length > 0) {
            recentQueries.forEach((q, idx) => {
                items.push({
                    type: 'recent',
                    id: `recent-${idx}`,
                    title: q,
                    icon: React.createElement(ClockIcon, null),
                    data: q,
                });
            });
        }
        // Suggestions
        processedSuggestions.forEach((s, idx) => {
            items.push({
                type: 'suggestion',
                id: s.id || `suggestion-${idx}`,
                title: s.query,
                icon: React.createElement(DocumentIcon, null),
                data: s,
            });
        });
        // Products
        processedProducts.forEach((p, idx) => {
            items.push({
                type: 'product',
                id: p.id,
                title: p.title,
                subtitle: p.brand,
                icon: React.createElement(ShoppingIcon, null),
                image: p.image,
                price: p.price,
                data: p,
            });
        });
        return items;
    }, [actions, 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(() => {
        if (activeIndex < 0) {
            // No selection, submit current query
            if (query.trim())
                onSearchSubmit?.(query.trim());
            return;
        }
        const item = allItems[activeIndex];
        if (!item)
            return;
        switch (item.type) {
            case 'action':
                item.data.onAction?.();
                break;
            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: () => inputRef?.current?.focus(),
        close: () => onClose?.(),
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, inputRef, onClose]);
    // Scroll active item into view
    useEffect(() => {
        if (listRef.current && activeIndex >= 0) {
            const activeEl = listRef.current.querySelector(`[data-index="${activeIndex}"]`);
            if (activeEl) {
                scrollIntoViewIfNeeded(activeEl, listRef.current);
            }
        }
    }, [activeIndex]);
    // Reset index when query changes
    useEffect(() => {
        setActiveIndex(-1);
    }, [query]);
    if (!isOpen)
        return null;
    const cssVariables = generateCSSVariables(theme);
    const activeItem = allItems[activeIndex];
    const content = (React.createElement("div", { ref: containerRef, className: cx('seekora-spotlight-dropdown', className, classNames.root), style: mergeStyles(styles.root, { width, zIndex: asOverlay ? undefined : zIndex }, cssVariables, style) },
        React.createElement("style", null, `
          @keyframes seekora-spin {
            to { transform: rotate(360deg); }
          }
        `),
        React.createElement("div", { style: styles.searchContainer },
            React.createElement("div", { style: styles.searchIcon },
                React.createElement(SearchIcon, null)),
            React.createElement("input", { ref: inputRef, type: "text", placeholder: placeholder, defaultValue: query, style: styles.searchInput, onChange: (e) => onSearchSubmit?.(e.target.value), onKeyDown: (e) => {
                    if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        navigateNext();
                    }
                    else if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        navigatePrevious();
                    }
                    else if (e.key === 'Enter') {
                        e.preventDefault();
                        selectActive();
                    }
                    else if (e.key === 'Escape') {
                        onClose?.();
                    }
                }, autoFocus: true }),
            showShortcuts && (React.createElement("div", { style: styles.shortcut },
                React.createElement("span", { style: styles.kbd }, "\u2318"),
                React.createElement("span", { style: styles.kbd }, "K")))),
        header,
        React.createElement("div", { style: styles.content },
            React.createElement("div", { ref: listRef, style: { ...styles.resultsColumn, maxHeight } }, allItems.length === 0 ? (renderEmpty ? renderEmpty(query) : (React.createElement("div", { style: styles.empty },
                "No results for \"",
                query,
                "\""))) : (React.createElement(React.Fragment, null,
                actions.length > 0 && (React.createElement("div", { style: styles.section },
                    React.createElement("div", { style: styles.sectionTitle }, "Actions"),
                    allItems.filter(i => i.type === 'action').map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, style: mergeStyles(styles.item, isActive ? styles.itemActive : undefined), onClick: () => {
                                setActiveIndex(idx);
                                selectActive();
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { style: mergeStyles(styles.itemIcon, isActive ? styles.itemIconActive : undefined) }, item.icon),
                            React.createElement("div", { style: styles.itemContent },
                                React.createElement("div", { style: mergeStyles(styles.itemTitle, isActive ? styles.itemTitleActive : undefined) }, item.title))));
                    }))),
                recentQueries.length > 0 && !query && (React.createElement("div", { style: styles.section },
                    React.createElement("div", { style: styles.sectionTitle }, "Recent"),
                    allItems.filter(i => i.type === 'recent').map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, style: mergeStyles(styles.item, isActive ? styles.itemActive : undefined), onClick: () => {
                                setActiveIndex(idx);
                                onRecentClick?.(item.data);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { style: mergeStyles(styles.itemIcon, isActive ? styles.itemIconActive : undefined) }, item.icon),
                            React.createElement("div", { style: styles.itemContent },
                                React.createElement("div", { style: mergeStyles(styles.itemTitle, isActive ? styles.itemTitleActive : undefined) }, item.title))));
                    }))),
                processedSuggestions.length > 0 && (React.createElement("div", { style: styles.section },
                    React.createElement("div", { style: styles.sectionTitle }, "Suggestions"),
                    allItems.filter(i => i.type === 'suggestion').map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, style: mergeStyles(styles.item, isActive ? styles.itemActive : undefined), onClick: () => {
                                setActiveIndex(idx);
                                onSuggestionSelect?.(item.data._raw, idx);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { style: mergeStyles(styles.itemIcon, isActive ? styles.itemIconActive : undefined) }, item.icon),
                            React.createElement("div", { style: styles.itemContent },
                                React.createElement("div", { style: mergeStyles(styles.itemTitle, isActive ? styles.itemTitleActive : undefined) }, highlightTextReact(item.title, query, { tag: 'strong' })))));
                    }))),
                processedProducts.length > 0 && (React.createElement("div", { style: styles.section },
                    React.createElement("div", { style: styles.sectionTitle }, "Products"),
                    allItems.filter(i => i.type === 'product').map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, style: mergeStyles(styles.item, isActive ? styles.itemActive : undefined), onClick: () => {
                                setActiveIndex(idx);
                                onProductClick?.(item.data._raw, idx);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { style: mergeStyles(styles.itemIcon, isActive ? styles.itemIconActive : undefined) }, item.image ? (React.createElement("img", { src: item.image, alt: "", style: styles.itemIconImage })) : (item.icon)),
                            React.createElement("div", { style: styles.itemContent },
                                React.createElement("div", { style: mergeStyles(styles.itemTitle, isActive ? styles.itemTitleActive : undefined) }, item.title),
                                item.subtitle && (React.createElement("div", { style: mergeStyles(styles.itemSubtitle, isActive ? styles.itemSubtitleActive : undefined) }, item.subtitle))),
                            item.price !== undefined && (React.createElement("span", { style: mergeStyles(styles.itemAction, styles.itemActionVisible, isActive ? styles.itemActionActive : undefined) }, formatPrice(item.price, { currency: productDisplay.currency })))));
                    })))))),
            showPreview && activeItem && activeItem.type === 'product' && (React.createElement("div", { style: styles.previewColumn },
                React.createElement("div", { style: styles.previewContent },
                    activeItem.image && (React.createElement("img", { src: activeItem.image, alt: "", style: styles.previewImage })),
                    React.createElement("div", { style: styles.previewTitle }, activeItem.title),
                    activeItem.subtitle && (React.createElement("div", { style: styles.previewSubtitle }, activeItem.subtitle)),
                    activeItem.price !== undefined && (React.createElement("div", { style: styles.previewPrice }, formatPrice(activeItem.price, { currency: productDisplay.currency }))),
                    React.createElement("div", { style: styles.previewActions },
                        React.createElement("button", { style: { ...styles.previewAction, ...styles.previewActionPrimary }, onClick: () => onProductClick?.(activeItem.data._raw, activeIndex) }, "View Product")))))),
        footer !== undefined ? footer : (React.createElement("div", { style: styles.footer },
            React.createElement("div", { style: styles.footerActions },
                React.createElement("span", { style: styles.footerAction },
                    React.createElement("span", { style: styles.kbd }, "\u2191"),
                    React.createElement("span", { style: styles.kbd }, "\u2193"),
                    "navigate"),
                React.createElement("span", { style: styles.footerAction },
                    React.createElement("span", { style: styles.kbd }, "\u21B5"),
                    "select"),
                React.createElement("span", { style: styles.footerAction },
                    React.createElement("span", { style: styles.kbd }, "esc"),
                    "close")),
            React.createElement("span", null,
                allItems.length,
                " results")))));
    if (asOverlay) {
        return (React.createElement("div", { style: { ...styles.overlay, zIndex }, onClick: (e) => {
                if (e.target === e.currentTarget)
                    onClose?.();
            } }, content));
    }
    return content;
});
export default SpotlightDropdown;
