/**
 * PinterestDropdown - Visual Discovery Style Suggestions
 *
 * Features:
 * - Visually-driven masonry/grid product display
 * - Large hero images
 * - Category chips/pills for filtering
 * - Smooth hover effects with quick preview
 * - Color palette extraction ready
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from 'react';
import { extractSuggestion, extractProduct, extractCategory, 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: '8px',
        backgroundColor: 'var(--seekora-bg-surface, #ffffff)',
        color: 'var(--seekora-text-primary, #111111)',
        borderRadius: '20px',
        boxShadow: '0 4px 30px rgba(0,0,0,0.12)',
        overflow: 'hidden',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        fontSize: '15px',
    },
    header: {
        padding: '16px 20px 14px',
        borderBottom: '1px solid var(--seekora-border-color, #e8e8e8)',
    },
    searchInfo: {
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        marginBottom: '14px',
    },
    searchQuery: {
        fontSize: '16px',
        fontWeight: 600,
        color: '#111111',
    },
    searchCount: {
        fontSize: '13px',
        color: '#767676',
    },
    categoriesScroll: {
        display: 'flex',
        gap: '8px',
        overflowX: 'auto',
        paddingBottom: '4px',
        scrollbarWidth: 'none',
        msOverflowStyle: 'none',
    },
    categoryChip: {
        display: 'inline-flex',
        alignItems: 'center',
        gap: '6px',
        padding: '8px 16px',
        backgroundColor: 'var(--seekora-bg-secondary, #f0f0f0)',
        borderRadius: '20px',
        fontSize: '13px',
        fontWeight: 500,
        color: '#111111',
        cursor: 'pointer',
        transition: 'all 150ms ease',
        whiteSpace: 'nowrap',
        borderWidth: 0,
        borderStyle: 'none',
    },
    categoryChipActive: {
        backgroundColor: 'var(--seekora-primary, #e60023)',
        color: 'var(--seekora-bg-surface, #ffffff)',
    },
    categoryChipHover: {
        backgroundColor: 'var(--seekora-bg-hover, #e0e0e0)',
        color: 'var(--seekora-text-primary, #111111)',
    },
    categoryIcon: {
        width: '16px',
        height: '16px',
        borderRadius: '4px',
        objectFit: 'cover',
    },
    content: {
        padding: '16px',
        overflowY: 'auto',
    },
    suggestionsRow: {
        display: 'flex',
        gap: '8px',
        marginBottom: '16px',
        flexWrap: 'wrap',
    },
    suggestionPill: {
        display: 'inline-flex',
        alignItems: 'center',
        gap: '6px',
        padding: '8px 14px',
        backgroundColor: 'var(--seekora-bg-secondary, #f5f5f5)',
        borderRadius: '20px',
        fontSize: '13px',
        fontWeight: 500,
        color: '#111111',
        cursor: 'pointer',
        transition: 'all 150ms ease',
        borderWidth: 0,
        borderStyle: 'none',
    },
    suggestionPillActive: {
        backgroundColor: 'var(--seekora-text-primary, #111111)',
        color: 'var(--seekora-bg-surface, #ffffff)',
    },
    suggestionPillHover: {
        backgroundColor: 'var(--seekora-bg-hover, #e8e8e8)',
        color: 'var(--seekora-text-primary, #111111)',
    },
    suggestionIcon: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#767676',
        flexShrink: 0,
    },
    productsGrid: {
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
        gap: '16px',
    },
    productCard: {
        position: 'relative',
        borderRadius: '16px',
        overflow: 'hidden',
        cursor: 'pointer',
        backgroundColor: 'var(--seekora-bg-secondary, #f5f5f5)',
        transition: 'transform 150ms, box-shadow 150ms',
    },
    productCardHover: {
        transform: 'scale(1.02)',
        boxShadow: '0 4px 20px rgba(0,0,0,0.15)',
    },
    productImageContainer: {
        position: 'relative',
        paddingBottom: '133%', // 3:4 aspect ratio
        overflow: 'hidden',
    },
    productImage: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        objectFit: 'cover',
    },
    productImagePlaceholder: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'var(--seekora-bg-tertiary, #e9e9e9)',
        color: 'var(--seekora-text-tertiary, #aaa)',
    },
    productOverlay: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        padding: '40px 12px 12px',
        background: 'linear-gradient(to top, rgba(0,0,0,0.7), transparent)',
        opacity: 0,
        transition: 'opacity 200ms',
    },
    productOverlayVisible: {
        opacity: 1,
    },
    productInfo: {
        padding: '12px',
    },
    productTitle: {
        fontSize: '14px',
        fontWeight: 600,
        color: 'var(--seekora-text-primary, #111)',
        lineHeight: 1.3,
        display: '-webkit-box',
        WebkitLineClamp: 2,
        WebkitBoxOrient: 'vertical',
        overflow: 'hidden',
        marginBottom: '4px',
    },
    productTitleOverlay: {
        color: 'var(--seekora-text-inverse, #ffffff)',
        marginBottom: '4px',
    },
    productPrice: {
        fontSize: '14px',
        fontWeight: 600,
        color: 'var(--seekora-text-primary, #111)',
    },
    productPriceOverlay: {
        color: 'var(--seekora-text-inverse, #ffffff)',
    },
    productSaveBtn: {
        position: 'absolute',
        top: '12px',
        right: '12px',
        width: '36px',
        height: '36px',
        borderRadius: '50%',
        backgroundColor: 'var(--seekora-primary, #e60023)',
        color: 'var(--seekora-text-inverse, #ffffff)',
        border: 'none',
        cursor: 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        opacity: 0,
        transform: 'scale(0.8)',
        transition: 'all 150ms',
    },
    productSaveBtnVisible: {
        opacity: 1,
        transform: 'scale(1)',
    },
    sectionTitle: {
        fontSize: '18px',
        fontWeight: 700,
        color: 'var(--seekora-text-primary, #111)',
        marginBottom: '16px',
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
    },
    loading: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px',
        color: 'var(--seekora-text-secondary, #767676)',
    },
    spinner: {
        width: '32px',
        height: '32px',
        border: '3px solid var(--seekora-border-color, #efefef)',
        borderTopColor: 'var(--seekora-primary, #e60023)',
        borderRadius: '50%',
        animation: 'seekora-spin 0.8s linear infinite',
    },
    empty: {
        padding: '60px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, #767676)',
    },
    emptyIcon: {
        width: '64px',
        height: '64px',
        margin: '0 auto 16px',
        color: 'var(--seekora-text-tertiary, #8c8c8c)',
    },
    footer: {
        padding: '16px 20px',
        borderTop: '1px solid var(--seekora-border-color, #efefef)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    viewAllBtn: {
        padding: '12px 20px',
        backgroundColor: 'var(--seekora-primary, #e60023)',
        color: 'var(--seekora-text-inverse, #ffffff)',
        border: 'none',
        borderRadius: '24px',
        fontSize: '15px',
        fontWeight: 600,
        cursor: 'pointer',
        transition: 'background 150ms',
    },
    viewAllBtnHover: {
        backgroundColor: 'var(--seekora-primary-dark, #ad081b)',
    },
});
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "currentColor" },
    React.createElement("path", { d: "M10 16c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6m13.12 2.88l-4.26-4.26A9.842 9.842 0 0020 10c0-5.52-4.48-10-10-10S0 4.48 0 10s4.48 10 10 10c1.67 0 3.24-.41 4.62-1.14l4.26 4.26a3 3 0 004.24-4.24z" })));
const HeartIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", width: "18", height: "18" },
    React.createElement("path", { d: "M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" })));
const TrendingIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", width: "18", height: "18" },
    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" })));
const ImageIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", width: "48", height: "48" },
    React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }),
    React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5" }),
    React.createElement("polyline", { points: "21 15 16 10 5 21" })));
export const PinterestDropdown = forwardRef(function PinterestDropdown(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 = {}, showSaveButton = true, activeCategory: initialActiveCategory, activeTab, // From BaseDropdownProps
    showPriceOverlay = true, gridColumns = 4, width = '800px', maxHeight = '600px', zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onProductClick, onCategoryClick, onTabChange, onSaveProduct, onViewAll, onClose, 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 [activeIndex, setActiveIndex] = useState(-1);
    const [hoveredProduct, setHoveredProduct] = useState(null);
    const [hoveredCategory, setHoveredCategory] = useState(null);
    const [hoveredSuggestion, setHoveredSuggestion] = useState(-1);
    const [activeCategory, setActiveCategory] = useState(initialActiveCategory || null);
    const [hoveredViewAll, setHoveredViewAll] = useState(false);
    // Sync internal activeCategory with parent prop (activeTab or activeCategory)
    useEffect(() => {
        const propValue = activeTab ?? initialActiveCategory;
        if (propValue !== undefined) {
            setActiveCategory(propValue === 'all' ? null : propValue);
        }
    }, [activeTab, initialActiveCategory]);
    // 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]);
    // 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 showCategories = processedCategories.length > 0;
    // Products are already filtered by parent based on activeTab
    // No additional filtering needed here
    const displayProducts = processedProducts;
    return (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": "Search suggestions", className: cx('seekora-pinterest-dropdown', className, classNames.root), style: mergeStyles(styles.root, { width, zIndex }, cssVariables, style), tabIndex: -1 },
        React.createElement("style", null, `
          @keyframes seekora-spin {
            to { transform: rotate(360deg); }
          }
          .seekora-pinterest-dropdown .categories-scroll::-webkit-scrollbar {
            display: none;
          }
        `),
        header || (query && (React.createElement("div", { style: styles.header },
            React.createElement("div", { style: styles.searchInfo },
                React.createElement("span", { style: styles.searchQuery }, query ? `"${query}"` : 'Explore'),
                processedProducts.length > 0 && (React.createElement("span", { style: styles.searchCount },
                    processedProducts.length,
                    "+ ideas"))),
            showCategories && (React.createElement("div", { style: styles.categoriesScroll, className: "categories-scroll" },
                React.createElement("button", { style: mergeStyles(styles.categoryChip, !activeCategory ? styles.categoryChipActive : undefined, hoveredCategory === 'all' && activeCategory ? styles.categoryChipHover : undefined), onClick: () => {
                        setActiveCategory(null);
                        onTabChange?.('all');
                    }, onMouseEnter: () => setHoveredCategory('all'), onMouseLeave: () => setHoveredCategory(null) }, "All"),
                processedCategories.map(cat => (React.createElement("button", { key: cat.id, style: mergeStyles(styles.categoryChip, activeCategory === cat.id ? styles.categoryChipActive : undefined, hoveredCategory === cat.id && activeCategory !== cat.id ? styles.categoryChipHover : undefined), onClick: () => {
                        setActiveCategory(cat.id);
                        // Call onTabChange to update products in parent
                        onTabChange?.(cat.id);
                    }, onMouseEnter: () => setHoveredCategory(cat.id), onMouseLeave: () => setHoveredCategory(null) },
                    cat.icon && (React.createElement("img", { src: cat.icon, alt: "", style: styles.categoryIcon })),
                    cat.label,
                    cat.count && React.createElement("span", null,
                        "(",
                        cat.count,
                        ")"))))))))),
        React.createElement("div", { style: { ...styles.content, maxHeight } },
            React.createElement(React.Fragment, null,
                processedSuggestions.length > 0 && (React.createElement("div", { style: styles.suggestionsRow }, processedSuggestions.slice(0, 8).map((s, idx) => (React.createElement("button", { key: s.id || idx, "data-index": idx, style: mergeStyles(styles.suggestionPill, activeIndex === idx ? styles.suggestionPillActive : undefined, hoveredSuggestion === idx && activeIndex !== idx ? styles.suggestionPillHover : undefined), onClick: () => onSuggestionSelect?.(s._raw, idx), onMouseEnter: () => {
                        setHoveredSuggestion(idx);
                        setActiveIndex(idx);
                    }, onMouseLeave: () => setHoveredSuggestion(-1) },
                    React.createElement("span", { style: styles.suggestionIcon }, query ? highlightTextReact(s.query, query, { tag: 'strong' }) : s.query)))))),
                displayProducts.length > 0 && (React.createElement(React.Fragment, null,
                    React.createElement("div", { style: styles.sectionTitle },
                        React.createElement(TrendingIcon, null),
                        "Ideas for you"),
                    React.createElement("div", { style: {
                            ...styles.productsGrid,
                            gridTemplateColumns: `repeat(${gridColumns}, 1fr)`,
                        } }, displayProducts.slice(0, 12).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) },
                        React.createElement("div", { style: styles.productImageContainer },
                            product.image ? (React.createElement("img", { src: product.image, alt: product.title, style: styles.productImage, loading: "lazy" })) : (React.createElement("div", { style: styles.productImagePlaceholder },
                                React.createElement(ImageIcon, null))),
                            showSaveButton && (React.createElement("button", { style: mergeStyles(styles.productSaveBtn, hoveredProduct === product.id ? styles.productSaveBtnVisible : undefined), onClick: (e) => {
                                    e.stopPropagation();
                                    onSaveProduct?.(product._raw);
                                }, "aria-label": "Save" },
                                React.createElement(HeartIcon, null))),
                            showPriceOverlay && product.price !== undefined && (React.createElement("div", { style: mergeStyles(styles.productOverlay, hoveredProduct === product.id ? styles.productOverlayVisible : undefined) },
                                React.createElement("div", { style: styles.productTitleOverlay }, product.title),
                                React.createElement("div", { style: styles.productPriceOverlay }, formatPrice(product.price, {
                                    currency: productDisplay.currency || product.currency || '$'
                                }))))),
                        !showPriceOverlay && (React.createElement("div", { style: styles.productInfo },
                            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 || '$'
                            }))))))))))),
                !loading && displayProducts.length === 0 && processedSuggestions.length === 0 && (renderEmpty ? renderEmpty(query) : (React.createElement("div", { style: styles.empty },
                    React.createElement("div", { style: styles.emptyIcon },
                        React.createElement(SearchIcon, null)),
                    React.createElement("p", null,
                        "No ideas found for \"",
                        query,
                        "\""),
                    React.createElement("p", { style: { fontSize: '14px', marginTop: '8px' } }, "Try searching for something else")))))),
        footer !== undefined ? footer : (displayProducts.length > 0 && (React.createElement("div", { style: styles.footer },
            React.createElement("span", { style: { color: 'var(--seekora-text-secondary, #767676)', fontSize: '14px' } },
                displayProducts.length,
                "+ more ideas"),
            React.createElement("button", { style: mergeStyles(styles.viewAllBtn, hoveredViewAll ? styles.viewAllBtnHover : undefined), onClick: () => onViewAll?.('products'), onMouseEnter: () => setHoveredViewAll(true), onMouseLeave: () => setHoveredViewAll(false) }, "Explore all"))))));
});
export default PinterestDropdown;
