/**
 * ShopifyDropdown - Modern E-commerce Style Suggestions
 *
 * Features:
 * - Hero product with large image
 * - Horizontal product scroll
 * - Collection/category links
 * - Clean, modern design
 * - Quick add to cart
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from 'react';
import { extractSuggestion, extractProduct, extractCategory, formatPrice, highlightTextReact, cx, mergeStyles, generateCSSVariables, calculateDiscount, 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 : '8px',
        backgroundColor: 'var(--seekora-bg-surface, transparent)',
        color: 'var(--seekora-text-primary, inherit)',
        borderRadius: isMobile ? 0 : '16px',
        boxShadow: isMobile ? 'none' : '0 4px 30px rgba(0, 0, 0, 0.12)',
        overflow: 'hidden',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        fontSize: isMobile ? '16px' : '14px',
        display: 'flex',
        flexDirection: 'column',
    },
    layout: {
        display: isMobile ? 'flex' : 'grid',
        flexDirection: 'column',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
        minHeight: isMobile ? 'auto' : '400px',
        flex: 1,
        overflowY: 'auto',
    },
    leftPanel: {
        backgroundColor: 'var(--seekora-bg-surface, transparent)',
        borderRight: isMobile ? 'none' : '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderBottom: isMobile ? '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))' : 'none',
        display: 'flex',
        flexDirection: 'column',
    },
    rightPanel: {
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
        padding: isMobile ? '16px' : '24px',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
    },
    section: {
        flex: 1,
        overflowY: 'auto',
    },
    sectionHeader: {
        padding: '16px 20px 12px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottom: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
    },
    sectionTitle: {
        fontSize: '11px',
        fontWeight: 600,
        color: 'var(--seekora-text-secondary, #666)',
        textTransform: 'uppercase',
        letterSpacing: '0.1em',
    },
    viewAllLink: {
        fontSize: '12px',
        color: 'var(--seekora-text-primary, inherit)',
        textDecoration: 'underline',
        cursor: 'pointer',
    },
    suggestionItem: {
        display: 'flex',
        alignItems: 'center',
        padding: isMobile ? '14px 16px' : '12px 16px',
        gap: '12px',
        cursor: 'pointer',
        transition: 'all 150ms ease',
        minHeight: '48px',
        margin: '4px 8px',
        borderRadius: '10px',
        color: 'var(--seekora-text-primary, inherit)',
    },
    suggestionItemActive: {
        backgroundColor: 'var(--seekora-bg-hover, rgba(255, 255, 255, 0.1))',
        color: 'var(--seekora-text-primary, inherit)',
    },
    suggestionIcon: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'var(--seekora-text-tertiary, #999999)',
        flexShrink: 0,
    },
    suggestionContent: {
        flex: 1,
        minWidth: 0,
    },
    suggestionQuery: {
        fontSize: '14px',
        color: 'var(--seekora-text-primary, inherit)',
        fontWeight: 400,
    },
    suggestionMeta: {
        fontSize: '12px',
        color: 'var(--seekora-text-secondary, inherit)',
        marginTop: '2px',
    },
    suggestionArrow: {
        width: '16px',
        height: '16px',
        color: 'var(--seekora-text-tertiary, #ccc)',
        transform: 'rotate(-45deg)',
        opacity: 0,
        transition: 'opacity 150ms',
    },
    suggestionArrowVisible: {
        opacity: 1,
    },
    collectionsGrid: {
        display: 'grid',
        gridTemplateColumns: 'repeat(2, 1fr)',
        gap: '1px',
        backgroundColor: 'var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderTop: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
    },
    collectionItem: {
        backgroundColor: 'var(--seekora-bg-surface, transparent)',
        color: 'var(--seekora-text-primary, inherit)',
        padding: '16px 20px',
        cursor: 'pointer',
        transition: 'background-color 150ms',
    },
    collectionItemHover: {
        backgroundColor: 'var(--seekora-bg-hover, rgba(255, 255, 255, 0.1))',
        color: 'var(--seekora-text-primary, inherit)',
    },
    collectionName: {
        fontSize: '13px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, inherit)',
        marginBottom: '4px',
    },
    collectionCount: {
        fontSize: '11px',
        color: 'var(--seekora-text-secondary, inherit)',
    },
    heroProduct: {
        marginBottom: '24px',
    },
    heroImage: {
        width: '100%',
        aspectRatio: '1',
        objectFit: 'cover',
        borderRadius: '2px',
        marginBottom: '16px',
        backgroundColor: 'var(--seekora-bg-tertiary, #f5f5f5)',
    },
    heroTitle: {
        fontSize: '16px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, inherit)',
        marginBottom: '8px',
        lineHeight: 1.3,
    },
    heroBrand: {
        fontSize: '12px',
        color: 'var(--seekora-text-secondary, inherit)',
        marginBottom: '12px',
        textTransform: 'uppercase',
        letterSpacing: '0.05em',
    },
    heroPricing: {
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        marginBottom: '16px',
    },
    heroPrice: {
        fontSize: '18px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, inherit)',
    },
    heroComparePrice: {
        fontSize: '14px',
        color: 'var(--seekora-text-tertiary, #999)',
        textDecoration: 'line-through',
    },
    heroDiscount: {
        fontSize: '12px',
        fontWeight: 600,
        color: 'var(--seekora-error, #d02e2e)',
        backgroundColor: 'var(--seekora-error-light, #fdf2f2)',
        padding: '2px 8px',
        borderRadius: '2px',
    },
    heroButton: {
        width: '100%',
        padding: '14px 20px',
        backgroundColor: 'var(--seekora-text-primary, inherit)',
        color: 'var(--seekora-bg-surface, transparent)',
        border: 'none',
        borderRadius: '2px',
        fontSize: '13px',
        fontWeight: 500,
        textTransform: 'uppercase',
        letterSpacing: '0.1em',
        cursor: 'pointer',
        transition: 'background-color 150ms',
    },
    heroButtonHover: {
        backgroundColor: 'var(--seekora-text-secondary, inherit)',
        color: 'var(--seekora-bg-surface, transparent)',
    },
    productsScroll: {
        flex: 1,
        overflowX: 'auto',
        overflowY: 'hidden',
        display: 'flex',
        gap: '16px',
        paddingBottom: '8px',
        scrollbarWidth: 'thin',
    },
    productCard: {
        flex: '0 0 140px',
        cursor: 'pointer',
        transition: 'opacity 150ms',
    },
    productCardHover: {
        opacity: 0.7,
    },
    productImage: {
        width: '140px',
        height: '175px',
        objectFit: 'cover',
        backgroundColor: 'var(--seekora-bg-tertiary, #f5f5f5)',
        marginBottom: '10px',
    },
    productTitle: {
        fontSize: '12px',
        color: 'var(--seekora-text-primary, inherit)',
        marginBottom: '4px',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    productPrice: {
        fontSize: '12px',
        fontWeight: 500,
        color: 'var(--seekora-text-primary, inherit)',
    },
    footer: {
        padding: '12px 20px',
        borderTop: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        fontSize: '11px',
        color: 'var(--seekora-text-secondary, inherit)',
    },
    footerLink: {
        color: 'var(--seekora-text-primary, inherit)',
        textDecoration: 'underline',
        cursor: 'pointer',
    },
    loading: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px',
        color: 'var(--seekora-text-secondary, inherit)',
    },
    spinner: {
        width: '24px',
        height: '24px',
        border: '2px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderTopColor: 'var(--seekora-text-primary, inherit)',
        borderRadius: '50%',
        animation: 'seekora-spin 0.8s linear infinite',
    },
    empty: {
        padding: '60px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #666)',
    },
    highlight: {
        fontWeight: 600,
        textDecoration: 'underline',
        textDecorationColor: 'var(--seekora-text-primary, #121212)',
    },
});
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: "1.5" },
    React.createElement("path", { d: "M14.386 14.386l4.0877 4.0877-4.0877-4.0877c-2.9418 2.9419-7.7115 2.9419-10.6533 0-2.9419-2.9418-2.9419-7.7115 0-10.6533 2.9418-2.9419 7.7115-2.9419 10.6533 0 2.9419 2.9418 2.9419 7.7115 0 10.6533z" })));
const ArrowIcon = () => (React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 20 20", fill: "currentColor" },
    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" })));
export const ShopifyDropdown = forwardRef(function ShopifyDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], categories = [], suggestionFields = { query: 'query' }, productFields = { id: 'id', title: 'title' }, categoryFields = { id: 'id', label: 'label' }, productDisplay = {}, theme = {}, showHeroProduct = true, showCollections = true, showAddToCart = true, addToCartText = 'Quick Add', showComparePrice = true, width = '100%', maxHeight = '500px', zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onProductClick, onCategoryClick, onTabChange, onAddToCart, onViewAll, onClose, 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 [hoveredProduct, setHoveredProduct] = useState(null);
    const [hoveredCollection, setHoveredCollection] = useState(null);
    const [hoveredButton, setHoveredButton] = useState(false);
    // 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 processedCategories = useMemo(() => categories.map(c => extractCategory(c, categoryFields)), [categories, categoryFields]);
    // Hero product (first product)
    const heroProduct = processedProducts[0];
    const otherProducts = processedProducts.slice(1, 7);
    // Navigation
    const navigateNext = useCallback(() => {
        setActiveIndex(prev => Math.min(prev + 1, processedSuggestions.length - 1));
    }, [processedSuggestions.length]);
    const navigatePrevious = useCallback(() => {
        setActiveIndex(prev => Math.max(prev - 1, -1));
    }, []);
    const selectActive = useCallback(() => {
        if (activeIndex >= 0 && processedSuggestions[activeIndex]) {
            onSuggestionSelect?.(processedSuggestions[activeIndex]._raw, activeIndex);
        }
    }, [activeIndex, processedSuggestions, 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 heroDiscount = heroProduct
        ? calculateDiscount(heroProduct.price, heroProduct.comparePrice)
        : undefined;
    return (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": "Search suggestions", className: cx('seekora-shopify-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-shopify-dropdown mark {
            background: transparent;
            text-decoration: underline;
            font-weight: 600;
          }
        `),
        header,
        React.createElement("div", { style: styles.layout },
            React.createElement("div", { style: styles.leftPanel },
                React.createElement("div", { style: styles.section },
                    React.createElement("div", { style: styles.sectionHeader },
                        React.createElement("span", { style: styles.sectionTitle }, "Suggestions"),
                        processedSuggestions.length > 5 && (React.createElement("span", { style: styles.viewAllLink, onClick: () => onViewAll?.('suggestions') }, "View all"))),
                    processedSuggestions.slice(0, 5).map((suggestion, idx) => {
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: suggestion.id || idx, "data-index": idx, role: "option", "aria-selected": isActive, style: mergeStyles(styles.suggestionItem, isActive ? styles.suggestionItemActive : undefined), onClick: () => onSuggestionSelect?.(suggestion._raw, idx), onMouseEnter: () => setActiveIndex(idx) },
                            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, { tag: 'mark' })),
                                suggestion.count && (React.createElement("div", { style: styles.suggestionMeta },
                                    suggestion.count,
                                    " results"))),
                            React.createElement("div", { style: mergeStyles(styles.suggestionArrow, isActive ? styles.suggestionArrowVisible : undefined) },
                                React.createElement(ArrowIcon, null))));
                    }),
                    processedSuggestions.length === 0 && query && (renderEmpty ? renderEmpty(query) : (React.createElement("div", { style: { padding: '20px', textAlign: 'center', color: '#666' } },
                        "No suggestions for \"",
                        query,
                        "\"")))),
                showCollections && processedCategories.length > 0 && (React.createElement(React.Fragment, null,
                    React.createElement("div", { style: styles.sectionHeader },
                        React.createElement("span", { style: styles.sectionTitle }, "Collections")),
                    React.createElement("div", { style: styles.collectionsGrid }, processedCategories.slice(0, 4).map(cat => (React.createElement("div", { key: cat.id, style: mergeStyles(styles.collectionItem, hoveredCollection === cat.id ? styles.collectionItemHover : undefined), onClick: () => onTabChange?.(cat.id), onMouseEnter: () => setHoveredCollection(cat.id), onMouseLeave: () => setHoveredCollection(null) },
                        React.createElement("div", { style: styles.collectionName }, cat.label),
                        cat.count && (React.createElement("div", { style: styles.collectionCount },
                            cat.count,
                            " products"))))))))),
            React.createElement("div", { style: styles.rightPanel },
                showHeroProduct && heroProduct && (React.createElement("div", { style: styles.heroProduct },
                    heroProduct.image && (React.createElement("img", { src: heroProduct.image, alt: heroProduct.title, style: styles.heroImage, loading: "lazy" })),
                    heroProduct.brand && (React.createElement("div", { style: styles.heroBrand }, heroProduct.brand)),
                    React.createElement("div", { style: styles.heroTitle }, heroProduct.title),
                    React.createElement("div", { style: styles.heroPricing },
                        React.createElement("span", { style: styles.heroPrice }, formatPrice(heroProduct.price, {
                            currency: productDisplay.currency || heroProduct.currency || '$'
                        })),
                        showComparePrice && heroProduct.comparePrice && (React.createElement("span", { style: styles.heroComparePrice }, formatPrice(heroProduct.comparePrice, {
                            currency: productDisplay.currency || heroProduct.currency || '$'
                        }))),
                        heroDiscount && (React.createElement("span", { style: styles.heroDiscount },
                            "-",
                            heroDiscount,
                            "%"))),
                    showAddToCart && (React.createElement("button", { style: mergeStyles(styles.heroButton, hoveredButton ? styles.heroButtonHover : undefined), onClick: () => onAddToCart?.(heroProduct._raw), onMouseEnter: () => setHoveredButton(true), onMouseLeave: () => setHoveredButton(false) }, addToCartText)))),
                otherProducts.length > 0 && (React.createElement(React.Fragment, null,
                    React.createElement("div", { style: { ...styles.sectionTitle, marginBottom: '12px' } }, "More Products"),
                    React.createElement("div", { style: styles.productsScroll }, otherProducts.map((product, idx) => (React.createElement("div", { key: product.id, style: mergeStyles(styles.productCard, hoveredProduct === product.id ? styles.productCardHover : undefined), onClick: () => onProductClick?.(product._raw, idx + 1), 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 })),
                        React.createElement("div", { style: styles.productTitle }, product.title),
                        product.price !== undefined && (React.createElement("div", { style: styles.productPrice }, formatPrice(product.price, {
                            currency: productDisplay.currency || product.currency || '$'
                        }))))))))))),
        footer !== undefined ? footer : (React.createElement("div", { style: styles.footer },
            React.createElement("span", null,
                "Press ",
                React.createElement("strong", null, "Enter"),
                " to search, ",
                React.createElement("strong", null, "\u2191\u2193"),
                " to navigate"),
            React.createElement("span", { style: styles.footerLink, onClick: () => onViewAll?.('products') }, "View all results")))));
});
export default ShopifyDropdown;
