/**
 * 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, generateCSSVariables, scrollIntoViewIfNeeded, } from "./utils";
import { useResponsive } from "./styles/responsive";
import { useInjectResponsiveStyles } from "./styles";
import { ensureSeekoraStyles } from "../../styles/inject";
import { useAnchorPortal } from "../../utils/use-anchor-portal";
// ============================================================================
// 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, anchorRef, } = props;
    // Inject global component styles
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    // Inject global responsive styles
    useInjectResponsiveStyles();
    // Responsive state
    const responsive = useResponsive();
    const { isMobile } = responsive;
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    // Portal positioning — only active when anchorRef is provided.
    const { portalStyle, wrapWithPortal, dataPosition } = useAnchorPortal(anchorRef, 500, zIndex);
    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
    const displayProducts = processedProducts;
    const containerStyle = portalStyle
        ? { ...cssVariables, ...portalStyle, ...style }
        : { width, zIndex, ...cssVariables, ...style };
    const dropdownTree = (React.createElement("div", { ref: containerRef, role: "listbox", "aria-label": "Search suggestions", "data-position": dataPosition, className: cx("seekora-dropdown seekora-dropdown--pinterest seekora-pinterest-dropdown", className, classNames.root), style: containerStyle, 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", { className: "seekora-pinterest-dropdown__header" },
                React.createElement("div", { className: "seekora-pinterest-dropdown__search-info" },
                    React.createElement("span", { className: "seekora-pinterest-dropdown__search-query" }, query ? `"${query}"` : "Explore"),
                    processedProducts.length > 0 && (React.createElement("span", { className: "seekora-pinterest-dropdown__search-count" },
                        processedProducts.length,
                        "+ ideas"))),
                showCategories && (React.createElement("div", { className: "seekora-pinterest-dropdown__categories-scroll categories-scroll" },
                    React.createElement("button", { className: cx("seekora-pinterest-dropdown__category-chip", !activeCategory
                            ? "seekora-pinterest-dropdown__category-chip--active"
                            : ""), onClick: () => {
                            setActiveCategory(null);
                            onTabChange?.("all");
                        }, onMouseEnter: () => setHoveredCategory("all"), onMouseLeave: () => setHoveredCategory(null) }, "All"),
                    processedCategories.map((cat) => (React.createElement("button", { key: cat.id, className: cx("seekora-pinterest-dropdown__category-chip", activeCategory === cat.id
                            ? "seekora-pinterest-dropdown__category-chip--active"
                            : ""), onClick: () => {
                            setActiveCategory(cat.id);
                            onTabChange?.(cat.id);
                        }, onMouseEnter: () => setHoveredCategory(cat.id), onMouseLeave: () => setHoveredCategory(null) },
                        cat.icon && (React.createElement("img", { src: cat.icon, alt: "", className: "seekora-pinterest-dropdown__category-icon" })),
                        cat.label,
                        cat.count && React.createElement("span", null,
                            "(",
                            cat.count,
                            ")"))))))))),
        React.createElement("div", { className: "seekora-dropdown__content", style: { maxHeight } },
            React.createElement(React.Fragment, null,
                processedSuggestions.length > 0 && (React.createElement("div", { className: "seekora-pinterest-dropdown__suggestions-row" }, processedSuggestions.slice(0, 8).map((s, idx) => (React.createElement("button", { key: s.id || idx, "data-index": idx, className: cx("seekora-pinterest-dropdown__suggestion-pill", activeIndex === idx
                        ? "seekora-pinterest-dropdown__suggestion-pill--active"
                        : ""), onClick: () => onSuggestionSelect?.(s._raw, idx), onMouseEnter: () => {
                        setHoveredSuggestion(idx);
                        setActiveIndex(idx);
                    }, onMouseLeave: () => setHoveredSuggestion(-1) },
                    React.createElement("span", { className: "seekora-pinterest-dropdown__suggestion-icon" }, query
                        ? highlightTextReact(s.query, query, { tag: "strong" })
                        : s.query)))))),
                displayProducts.length > 0 && (React.createElement(React.Fragment, null,
                    React.createElement("div", { className: "seekora-pinterest-dropdown__section-title" },
                        React.createElement(TrendingIcon, null),
                        "Ideas for you"),
                    React.createElement("div", { className: "seekora-dropdown__product-grid seekora-pinterest-dropdown__product-grid", style: { gridTemplateColumns: `repeat(${gridColumns}, 1fr)` } }, displayProducts.slice(0, 12).map((product, idx) => (React.createElement("div", { key: product.id, className: cx("seekora-pinterest-dropdown__product-card", hoveredProduct === product.id
                            ? "seekora-pinterest-dropdown__product-card--hover"
                            : ""), onClick: () => onProductClick?.(product._raw, idx), onMouseEnter: () => setHoveredProduct(product.id), onMouseLeave: () => setHoveredProduct(null) },
                        React.createElement("div", { className: "seekora-pinterest-dropdown__product-image-container" },
                            product.image ? (React.createElement("img", { src: product.image, alt: product.title, className: "seekora-pinterest-dropdown__product-image", loading: "lazy" })) : (React.createElement("div", { className: "seekora-pinterest-dropdown__product-image-placeholder" },
                                React.createElement(ImageIcon, null))),
                            showSaveButton && (React.createElement("button", { className: cx("seekora-pinterest-dropdown__product-save-btn", hoveredProduct === product.id
                                    ? "seekora-pinterest-dropdown__product-save-btn--visible"
                                    : ""), onClick: (e) => {
                                    e.stopPropagation();
                                    onSaveProduct?.(product._raw);
                                }, "aria-label": "Save" },
                                React.createElement(HeartIcon, null))),
                            showPriceOverlay && product.price !== undefined && (React.createElement("div", { className: cx("seekora-pinterest-dropdown__product-overlay", hoveredProduct === product.id
                                    ? "seekora-pinterest-dropdown__product-overlay--visible"
                                    : "") },
                                React.createElement("div", { className: "seekora-pinterest-dropdown__product-title-overlay" }, product.title),
                                React.createElement("div", { className: "seekora-pinterest-dropdown__product-price-overlay" }, formatPrice(product.price, {
                                    currency: productDisplay.currency ||
                                        product.currency ||
                                        "$",
                                }))))),
                        !showPriceOverlay && (React.createElement("div", { className: "seekora-pinterest-dropdown__product-info" },
                            React.createElement("div", { className: "seekora-pinterest-dropdown__product-title" }, product.title),
                            product.price !== undefined && (React.createElement("div", { className: "seekora-pinterest-dropdown__product-price" }, formatPrice(product.price, {
                                currency: productDisplay.currency ||
                                    product.currency ||
                                    "$",
                            }))))))))))),
                !loading &&
                    displayProducts.length === 0 &&
                    processedSuggestions.length === 0 &&
                    (renderEmpty ? (renderEmpty(query)) : (React.createElement("div", { className: "seekora-pinterest-dropdown__empty" },
                        React.createElement("div", { className: "seekora-pinterest-dropdown__empty-icon" },
                            React.createElement(SearchIcon, null)),
                        React.createElement("p", null,
                            "No ideas found for \"",
                            query,
                            "\""),
                        React.createElement("p", { className: "seekora-pinterest-dropdown__empty-hint" }, "Try searching for something else")))))),
        footer !== undefined
            ? footer
            : displayProducts.length > 0 && (React.createElement("div", { className: "seekora-pinterest-dropdown__footer" },
                React.createElement("span", { className: "seekora-dropdown__footer-count seekora-pinterest-dropdown__footer-count" },
                    displayProducts.length,
                    "+ more ideas"),
                React.createElement("button", { className: "seekora-pinterest-dropdown__view-all-btn", onClick: () => onViewAll?.("products") }, "Explore all")))));
    return wrapWithPortal(dropdownTree);
});
export default PinterestDropdown;
