/**
 * AmazonDropdown - Amazon-style Search Suggestions
 *
 * Features:
 * - Department/category scoping in search
 * - Suggestions with category context
 * - Product grid with images
 * - "in Department" suffix for scoped searches
 * - Clean, functional design
 */
import React, { useState, useRef, useEffect, useCallback, forwardRef, useImperativeHandle, useMemo, } from 'react';
import { extractSuggestion, extractProduct, extractCategory, formatPrice, highlightTextReact, cx, mergeStyles, generateCSSVariables, scrollIntoViewIfNeeded, } from './utils';
import { useResponsive, touchTargets } from './styles/responsive';
import { useInjectResponsiveStyles } from './styles';
// ============================================================================
// Styles
// ============================================================================
const createStyles = (theme = {}, isMobile = false) => ({
    root: {
        position: 'absolute',
        top: '100%',
        left: 0,
        right: 0,
        marginTop: '8px',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        color: 'var(--seekora-text-primary, #0f1111)',
        borderRadius: isMobile ? '12px' : '16px',
        boxShadow: '0 4px 6px -1px rgba(0,0,0,0.1), 0 10px 40px -5px rgba(0,0,0,0.15)',
        overflow: 'hidden',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        fontSize: '14px',
        zIndex: 1000,
        // Mobile: full width overlay
        ...(isMobile && {
            position: 'fixed',
            top: '60px',
            bottom: 0,
            left: '8px',
            right: '8px',
            margin: 0,
            borderRadius: '16px 16px 0 0',
        }),
    },
    content: {
        display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
        maxHeight: isMobile ? 'calc(100vh - 140px)' : '480px',
        overflowY: 'auto',
    },
    leftColumn: {
        flex: isMobile ? 'none' : '0 0 55%',
        borderRight: isMobile ? 'none' : '1px solid var(--seekora-border-color, #e8e8e8)',
        borderBottom: isMobile ? '1px solid var(--seekora-border-color, #e8e8e8)' : 'none',
        overflowY: 'auto',
        padding: '8px 0',
    },
    rightColumn: {
        flex: isMobile ? 'none' : '0 0 45%',
        backgroundColor: 'var(--seekora-bg-secondary, #fafafa)',
        overflowY: 'auto',
        padding: '8px 0',
    },
    section: {
        padding: '4px 0',
    },
    sectionHeader: {
        padding: '8px 16px 6px',
        fontSize: '11px',
        fontWeight: 600,
        color: 'var(--seekora-text-secondary, #6b6b6b)',
        textTransform: 'uppercase',
        letterSpacing: '0.05em',
    },
    suggestionItem: {
        display: 'flex',
        alignItems: 'center',
        padding: isMobile ? '12px 16px' : '10px 16px',
        cursor: 'pointer',
        transition: 'all 150ms ease',
        gap: isMobile ? '12px' : '10px',
        minHeight: isMobile ? `${touchTargets.minimum}px` : '40px',
        borderRadius: '8px',
        margin: '2px 8px',
        color: 'var(--seekora-text-primary, #0f1111)',
    },
    suggestionItemActive: {
        backgroundColor: 'var(--seekora-bg-hover, #f5f5f5)',
        color: 'var(--seekora-text-primary, #0f1111)',
    },
    suggestionIcon: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'var(--seekora-text-tertiary, #6b6b6b)',
        flexShrink: 0,
    },
    suggestionContent: {
        flex: 1,
        minWidth: 0,
    },
    suggestionQuery: {
        fontSize: '14px',
        color: 'var(--seekora-text-primary, #0f1111)',
        fontWeight: 400,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    suggestionContext: {
        fontSize: '12px',
        color: 'var(--seekora-text-secondary, #565959)',
        marginTop: '2px',
    },
    suggestionDepartment: {
        color: 'var(--seekora-primary-dark, #c45500)',
        fontStyle: 'italic',
    },
    categoryScoped: {
        backgroundColor: 'var(--seekora-primary-light, #fef8f0)',
        borderRadius: '3px',
        padding: '0 4px',
        marginLeft: '4px',
        fontSize: '11px',
        color: 'var(--seekora-primary-dark, #c45500)',
    },
    productsHeader: {
        padding: '12px 16px 8px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    productsTitle: {
        fontSize: '13px',
        fontWeight: 700,
        color: 'var(--seekora-text-primary, #0f1111)',
    },
    viewAll: {
        fontSize: '12px',
        color: 'var(--seekora-link, #007185)',
        textDecoration: 'none',
        cursor: 'pointer',
        '&:hover': {
            color: 'var(--seekora-link-hover, #c45500)',
            textDecoration: 'underline',
        },
    },
    productsGrid: {
        display: 'grid',
        gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(2, 1fr)',
        gap: '12px',
        padding: '12px 16px 16px',
    },
    productCard: {
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        borderRadius: '12px',
        padding: '10px',
        cursor: 'pointer',
        transition: 'all 200ms ease',
        boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
    },
    productCardHover: {
        boxShadow: '0 4px 12px rgba(0,0,0,0.12)',
        transform: 'translateY(-2px)',
    },
    productImage: {
        width: '100%',
        aspectRatio: '1',
        objectFit: 'contain',
        backgroundColor: 'var(--seekora-bg-tertiary, #f8f8f8)',
        borderRadius: '8px',
        marginBottom: '10px',
    },
    productTitle: {
        fontSize: '12px',
        color: 'var(--seekora-link, #007185)',
        lineHeight: 1.3,
        display: '-webkit-box',
        WebkitLineClamp: 2,
        WebkitBoxOrient: 'vertical',
        overflow: 'hidden',
        marginBottom: '4px',
    },
    productPrice: {
        fontSize: '14px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, #0f1111)',
    },
    productPriceSymbol: {
        fontSize: '11px',
        verticalAlign: 'top',
    },
    productRating: {
        display: 'flex',
        alignItems: 'center',
        gap: '4px',
        marginTop: '4px',
    },
    stars: {
        color: 'var(--seekora-rating, #de7921)',
        fontSize: '12px',
    },
    reviewCount: {
        fontSize: '11px',
        color: 'var(--seekora-link, #007185)',
    },
    prime: {
        height: '16px',
        marginTop: '4px',
    },
    recentHeader: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '8px 16px',
    },
    clearRecent: {
        fontSize: '12px',
        color: 'var(--seekora-link, #007185)',
        cursor: 'pointer',
        background: 'none',
        border: 'none',
        padding: 0,
    },
    highlight: {
        fontWeight: 700,
        color: 'var(--seekora-text-primary, #0f1111)',
    },
    empty: {
        padding: '40px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #565959)',
    },
    footer: {
        padding: '10px 16px',
        borderTop: '1px solid var(--seekora-border-color, #e7e7e7)',
        backgroundColor: 'var(--seekora-bg-secondary, #f7f7f7)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        fontSize: '12px',
        color: 'var(--seekora-text-tertiary, #767676)',
    },
    keyboard: {
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
    },
    key: {
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        minWidth: '20px',
        height: '18px',
        padding: '0 4px',
        backgroundColor: 'var(--seekora-bg-surface, #fff)',
        border: '1px solid var(--seekora-border-color, #ccc)',
        borderRadius: '3px',
        fontSize: '10px',
        fontFamily: 'monospace',
    },
});
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" },
    React.createElement("circle", { cx: "11", cy: "11", r: "8" }),
    React.createElement("line", { x1: "21", y1: "21", x2: "16.65", y2: "16.65" })));
const ClockIcon = () => (React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" },
    React.createElement("circle", { cx: "12", cy: "12", r: "10" }),
    React.createElement("polyline", { points: "12 6 12 12 16 14" })));
const TrendingIcon = () => (React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" },
    React.createElement("polyline", { points: "23 6 13.5 15.5 8.5 10.5 1 18" }),
    React.createElement("polyline", { points: "17 6 23 6 23 12" })));
const StarIcon = ({ filled = false }) => (React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: filled ? 'currentColor' : 'none', stroke: "currentColor", strokeWidth: "2" },
    React.createElement("polygon", { points: "12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" })));
// ============================================================================
// Sub-components
// ============================================================================
const RatingStars = ({ rating, count }) => {
    const fullStars = Math.floor(rating);
    const hasHalf = rating % 1 >= 0.5;
    return (React.createElement("div", { style: createStyles().productRating },
        React.createElement("div", { style: createStyles().stars },
            '★'.repeat(fullStars),
            hasHalf && '½',
            '☆'.repeat(5 - fullStars - (hasHalf ? 1 : 0))),
        count !== undefined && (React.createElement("span", { style: createStyles().reviewCount },
            "(",
            count.toLocaleString(),
            ")"))));
};
export const AmazonDropdown = forwardRef(function AmazonDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], categories = [], recentSearches = [], trendingSearches = [], filteredTabs = [], activeTab = 'all', suggestionFields = { query: 'query' }, productFields = { id: 'id', title: 'title' }, categoryFields = { id: 'id', label: 'label' }, productDisplay = {}, theme = {}, showDepartments = true, currentDepartment, departments = [], showPrime = false, width = '700px', maxHeight = '500px', zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onProductClick, onCategoryClick, onTabChange, onRecentClick, onRecentRemove, onRecentClearAll, onViewAll, onClose, header, footer, renderEmpty, } = props;
    // Inject global responsive styles
    useInjectResponsiveStyles();
    // Responsive state
    const responsive = useResponsive();
    const { isMobile, isTablet } = responsive;
    const styles = useMemo(() => createStyles(theme, isMobile), [theme, isMobile]);
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [hoveredProduct, setHoveredProduct] = useState(null);
    // Process data through field mappings
    const processedSuggestions = useMemo(() => suggestions.map(s => extractSuggestion(s, suggestionFields)), [suggestions, suggestionFields]);
    // Get products from active tab or default products
    const currentProducts = useMemo(() => {
        if (activeTab === 'all' || filteredTabs.length === 0) {
            return products;
        }
        const tab = filteredTabs.find(t => t.id === activeTab);
        return tab?.products || products;
    }, [activeTab, filteredTabs, products]);
    const processedProducts = useMemo(() => currentProducts.map(p => extractProduct(p, productFields)), [currentProducts, productFields]);
    const processedCategories = useMemo(() => categories.map(c => extractCategory(c, categoryFields)), [categories, categoryFields]);
    // Recent searches as strings
    const recentQueries = useMemo(() => recentSearches.map(r => typeof r === 'string' ? r : r.query), [recentSearches]);
    // All navigable items
    const allItems = useMemo(() => {
        const items = [];
        let idx = 0;
        if (query.length === 0) {
            recentQueries.slice(0, 5).forEach(q => {
                items.push({ type: 'recent', data: q, index: idx++ });
            });
        }
        processedSuggestions.forEach(s => {
            items.push({ type: 'suggestion', data: s, index: idx++ });
        });
        return items;
    }, [query, recentQueries, 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 || activeIndex >= allItems.length)
            return;
        const item = allItems[activeIndex];
        if (item.type === 'recent') {
            onRecentClick?.(item.data);
        }
        else if (item.type === 'suggestion') {
            onSuggestionSelect?.(item.data._raw, item.index);
        }
    }, [activeIndex, allItems, onRecentClick, onSuggestionSelect]);
    // Expose ref
    useImperativeHandle(ref, () => ({
        getActiveIndex: () => activeIndex,
        setActiveIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        focus: () => containerRef.current?.focus(),
        close: () => onClose?.(),
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, onClose]);
    // 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 && trendingSearches.length > 0;
    const showProducts = processedProducts.length > 0;
    return (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": "Search suggestions", className: cx('seekora-amazon-dropdown', className, classNames.root), style: mergeStyles(styles.root, {
            width: isMobile ? '100%' : width,
            maxHeight: isMobile ? '100vh' : maxHeight,
            zIndex
        }, cssVariables, style), tabIndex: -1 },
        React.createElement("style", null, `
          @keyframes seekora-spin {
            to { transform: rotate(360deg); }
          }
          .seekora-amazon-dropdown mark {
            background: transparent;
            font-weight: 700;
            color: inherit;
          }
        `),
        header,
        React.createElement(React.Fragment, null,
            filteredTabs.length > 0 && (React.createElement("div", { style: {
                    display: 'flex',
                    gap: '8px',
                    padding: isMobile ? '12px' : '12px 16px',
                    overflowX: 'auto',
                    borderBottomWidth: '1px',
                    borderBottomStyle: 'solid',
                    borderBottomColor: 'var(--seekora-border-color, #e7e7e7)',
                    background: 'var(--seekora-bg-secondary, #f5f5f5)',
                    WebkitOverflowScrolling: 'touch',
                } },
                React.createElement("button", { onClick: () => onTabChange?.('all'), style: {
                        padding: '8px 16px',
                        borderWidth: 0,
                        borderStyle: 'none',
                        background: activeTab === 'all' ? 'var(--seekora-text-primary, #232f3e)' : 'var(--seekora-bg-surface, #ffffff)',
                        color: activeTab === 'all' ? 'var(--seekora-bg-surface, #ffffff)' : 'var(--seekora-text-primary, #0f1111)',
                        borderRadius: '20px',
                        fontSize: '13px',
                        fontWeight: 600,
                        cursor: 'pointer',
                        whiteSpace: 'nowrap',
                        minHeight: '36px',
                        boxShadow: activeTab === 'all' ? 'none' : '0 1px 3px rgba(0,0,0,0.1)',
                        transition: 'all 150ms ease',
                    } }, "All"),
                filteredTabs.slice(0, 6).map(tab => (React.createElement("button", { key: tab.id, onClick: () => onTabChange?.(tab.id), style: {
                        padding: '8px 16px',
                        borderWidth: 0,
                        borderStyle: 'none',
                        background: activeTab === tab.id ? 'var(--seekora-primary, #ff9900)' : 'var(--seekora-bg-surface, #ffffff)',
                        color: activeTab === tab.id ? 'var(--seekora-text-on-primary, #0f1111)' : 'var(--seekora-text-primary, #0f1111)',
                        borderRadius: '20px',
                        fontSize: '13px',
                        fontWeight: activeTab === tab.id ? 700 : 500,
                        cursor: 'pointer',
                        whiteSpace: 'nowrap',
                        minHeight: '36px',
                        boxShadow: activeTab === tab.id ? '0 2px 4px rgba(255,153,0,0.3)' : '0 1px 3px rgba(0,0,0,0.1)',
                        transition: 'all 150ms ease',
                    } },
                    tab.label,
                    " ",
                    tab.nb_hits ? `(${tab.nb_hits})` : ''))))),
            React.createElement("div", { style: styles.content },
                React.createElement("div", { style: styles.leftColumn },
                    showRecent && (React.createElement("div", { style: styles.section },
                        React.createElement("div", { style: styles.recentHeader },
                            React.createElement("span", { style: styles.sectionHeader }, "Recent Searches"),
                            React.createElement("button", { style: styles.clearRecent, onClick: onRecentClearAll }, "Clear all")),
                        recentQueries.slice(0, 5).map((q, idx) => {
                            const isActive = activeIndex === idx;
                            return (React.createElement("div", { key: `recent-${q}`, "data-index": idx, role: "option", "aria-selected": isActive, style: mergeStyles(styles.suggestionItem, isActive ? styles.suggestionItemActive : undefined), onClick: () => onRecentClick?.(q), onMouseEnter: () => setActiveIndex(idx) },
                                React.createElement(ClockIcon, null),
                                React.createElement("div", { style: styles.suggestionContent },
                                    React.createElement("div", { style: styles.suggestionQuery }, q))));
                        }))),
                    showTrending && (React.createElement("div", { style: styles.section },
                        React.createElement("div", { style: styles.sectionHeader }, "Trending Searches"),
                        trendingSearches.slice(0, 5).map((t, idx) => {
                            const trendQuery = typeof t === 'string' ? t : t.query;
                            const itemIdx = recentQueries.length + idx;
                            const isActive = activeIndex === itemIdx;
                            return (React.createElement("div", { key: `trending-${trendQuery}`, "data-index": itemIdx, role: "option", "aria-selected": isActive, style: mergeStyles(styles.suggestionItem, isActive ? styles.suggestionItemActive : undefined), onClick: () => onSuggestionSelect?.({ query: trendQuery }, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                                React.createElement(TrendingIcon, null),
                                React.createElement("div", { style: styles.suggestionContent },
                                    React.createElement("div", { style: styles.suggestionQuery }, trendQuery))));
                        }))),
                    processedSuggestions.length > 0 && (React.createElement("div", { style: styles.section },
                        query && React.createElement("div", { style: styles.sectionHeader }, "Suggestions"),
                        processedSuggestions.map((suggestion, idx) => {
                            const itemIdx = showRecent ? recentQueries.length + idx : idx;
                            const isActive = activeIndex === itemIdx;
                            const categories = suggestion.categories || [];
                            const firstCategory = categories[0];
                            return (React.createElement("div", { key: suggestion.id || `suggestion-${idx}`, "data-index": itemIdx, role: "option", "aria-selected": isActive, style: mergeStyles(styles.suggestionItem, isActive ? styles.suggestionItemActive : undefined), onClick: () => onSuggestionSelect?.(suggestion._raw, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                                React.createElement("div", { style: styles.suggestionIcon },
                                    React.createElement(SearchIcon, null)),
                                React.createElement("div", { style: styles.suggestionContent },
                                    React.createElement("div", { style: styles.suggestionQuery }, highlightTextReact(suggestion.query, query, { className: 'highlight' })),
                                    showDepartments && firstCategory && (React.createElement("div", { style: styles.suggestionContext },
                                        React.createElement("span", { style: styles.suggestionDepartment },
                                            "in ",
                                            typeof firstCategory === 'string' ? firstCategory : firstCategory.value || firstCategory.label)))),
                                suggestion.count && (React.createElement("span", { style: styles.categoryScoped }, suggestion.count.toLocaleString()))));
                        }))),
                    query && processedSuggestions.length === 0 && !loading && (renderEmpty ? renderEmpty(query) : (React.createElement("div", { style: styles.empty },
                        "No suggestions found for \"",
                        query,
                        "\"")))),
                showProducts && (React.createElement("div", { style: styles.rightColumn },
                    React.createElement("div", { style: styles.productsHeader },
                        React.createElement("span", { style: styles.productsTitle }, "Suggested Products"),
                        React.createElement("a", { style: styles.viewAll, onClick: () => onViewAll?.('products') }, "View all")),
                    React.createElement("div", { style: styles.productsGrid }, processedProducts.slice(0, 4).map((product, idx) => (React.createElement("div", { key: product.id, style: mergeStyles(styles.productCard, hoveredProduct === product.id ? styles.productCardHover : undefined), onClick: () => onProductClick?.(product._raw, idx), onMouseEnter: () => setHoveredProduct(product.id), onMouseLeave: () => setHoveredProduct(null) },
                        product.image ? (React.createElement("img", { src: product.image, alt: product.title, style: styles.productImage, loading: "lazy" })) : (React.createElement("div", { style: { ...styles.productImage, display: 'flex', alignItems: 'center', justifyContent: 'center' } },
                            React.createElement("span", { style: { color: 'var(--seekora-text-tertiary, #999)', fontSize: '32px' } }, "\uD83D\uDCF7"))),
                        React.createElement("div", { style: styles.productTitle }, product.title),
                        product.price !== undefined && (React.createElement("div", { style: styles.productPrice },
                            React.createElement("span", { style: styles.productPriceSymbol }, productDisplay.currency || '$'),
                            formatPrice(product.price, {
                                currency: '',
                                priceDecimals: productDisplay.priceDecimals
                            }))),
                        product.rating && (React.createElement(RatingStars, { rating: parseFloat(String(product.rating)), count: product.reviewCount ? parseInt(String(product.reviewCount)) : undefined })))))))))),
        footer !== undefined ? footer : (React.createElement("div", { style: styles.footer },
            React.createElement("div", { style: styles.keyboard },
                React.createElement("span", { style: styles.key }, "\u2191"),
                React.createElement("span", { style: styles.key }, "\u2193"),
                React.createElement("span", null, "to navigate"),
                React.createElement("span", { style: styles.key }, "\u21B5"),
                React.createElement("span", null, "to select"),
                React.createElement("span", { style: styles.key }, "esc"),
                React.createElement("span", null, "to close")),
            processedSuggestions.length > 0 && (React.createElement("span", null,
                processedSuggestions.length,
                " suggestions"))))));
});
export default AmazonDropdown;
