/**
 * 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, 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: "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", { className: "seekora-amazon-dropdown__product-rating" },
        React.createElement("div", { className: "seekora-amazon-dropdown__product-stars" },
            "★".repeat(fullStars),
            hasHalf && "½",
            "☆".repeat(5 - fullStars - (hasHalf ? 1 : 0))),
        count !== undefined && (React.createElement("span", { className: "seekora-amazon-dropdown__product-review-count" },
            "(",
            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, anchorRef, } = props;
    // Inject global component styles
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    // Inject global responsive styles
    useInjectResponsiveStyles();
    // Responsive state
    const responsive = useResponsive();
    const { isMobile, isTablet } = responsive;
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [hoveredProduct, setHoveredProduct] = useState(null);
    // Portal positioning — only active when anchorRef is provided.
    const { portalStyle, wrapWithPortal, dataPosition } = useAnchorPortal(anchorRef, 500, zIndex);
    // 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;
    const containerStyle = portalStyle
        ? { ...cssVariables, ...portalStyle, ...style }
        : {
            width: isMobile ? "100%" : width,
            maxHeight: isMobile ? "100vh" : maxHeight,
            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--amazon seekora-amazon-dropdown", className, classNames.root), style: containerStyle, 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", { className: "seekora-dropdown__tabs seekora-amazon-dropdown__tabs" },
                React.createElement("button", { onClick: () => onTabChange?.("all"), className: cx("seekora-dropdown__tab-btn", activeTab === "all"
                        ? "seekora-dropdown__tab-btn--all-active"
                        : "") }, "All"),
                filteredTabs.slice(0, 6).map((tab) => (React.createElement("button", { key: tab.id, onClick: () => onTabChange?.(tab.id), className: cx("seekora-dropdown__tab-btn", activeTab === tab.id
                        ? "seekora-dropdown__tab-btn--category-active"
                        : "") },
                    tab.label,
                    " ",
                    tab.nb_hits ? `(${tab.nb_hits})` : ""))))),
            React.createElement("div", { className: "seekora-amazon-dropdown__content" },
                React.createElement("div", { className: "seekora-amazon-dropdown__left-column" },
                    showRecent && (React.createElement("div", { className: "seekora-amazon-dropdown__section" },
                        React.createElement("div", { className: "seekora-amazon-dropdown__recent-header" },
                            React.createElement("span", { className: "seekora-amazon-dropdown__section-header" }, "Recent Searches"),
                            React.createElement("button", { className: "seekora-amazon-dropdown__clear-recent", 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, className: cx("seekora-amazon-dropdown__suggestion-item", isActive
                                    ? "seekora-amazon-dropdown__suggestion-item--active"
                                    : ""), onClick: () => onRecentClick?.(q), onMouseEnter: () => setActiveIndex(idx) },
                                React.createElement(ClockIcon, null),
                                React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-content" },
                                    React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-query" }, q))));
                        }))),
                    showTrending && (React.createElement("div", { className: "seekora-amazon-dropdown__section" },
                        React.createElement("div", { className: "seekora-amazon-dropdown__section-header" }, "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, className: cx("seekora-amazon-dropdown__suggestion-item", isActive
                                    ? "seekora-amazon-dropdown__suggestion-item--active"
                                    : ""), onClick: () => onSuggestionSelect?.({ query: trendQuery }, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                                React.createElement(TrendingIcon, null),
                                React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-content" },
                                    React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-query" }, trendQuery))));
                        }))),
                    processedSuggestions.length > 0 && (React.createElement("div", { className: "seekora-amazon-dropdown__section" },
                        query && (React.createElement("div", { className: "seekora-amazon-dropdown__section-header" }, "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, className: cx("seekora-amazon-dropdown__suggestion-item", isActive
                                    ? "seekora-amazon-dropdown__suggestion-item--active"
                                    : ""), onClick: () => onSuggestionSelect?.(suggestion._raw, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                                React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-icon" },
                                    React.createElement(SearchIcon, null)),
                                React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-content" },
                                    React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-query" }, highlightTextReact(suggestion.query, query, {
                                        className: "highlight",
                                    })),
                                    showDepartments && firstCategory && (React.createElement("div", { className: "seekora-amazon-dropdown__suggestion-context" },
                                        React.createElement("span", { className: "seekora-amazon-dropdown__suggestion-department" },
                                            "in",
                                            " ",
                                            typeof firstCategory === "string"
                                                ? firstCategory
                                                : firstCategory.value || firstCategory.label)))),
                                suggestion.count && (React.createElement("span", { className: "seekora-amazon-dropdown__category-scoped" }, suggestion.count.toLocaleString()))));
                        }))),
                    query &&
                        processedSuggestions.length === 0 &&
                        !loading &&
                        (renderEmpty ? (renderEmpty(query)) : (React.createElement("div", { className: "seekora-amazon-dropdown__empty" },
                            "No suggestions found for \"",
                            query,
                            "\"")))),
                showProducts && (React.createElement("div", { className: "seekora-amazon-dropdown__right-column" },
                    React.createElement("div", { className: "seekora-amazon-dropdown__products-header" },
                        React.createElement("span", { className: "seekora-amazon-dropdown__products-title" }, "Suggested Products"),
                        React.createElement("a", { className: "seekora-amazon-dropdown__view-all", onClick: () => onViewAll?.("products") }, "View all")),
                    React.createElement("div", { className: "seekora-dropdown__product-grid" }, processedProducts.slice(0, 4).map((product, idx) => (React.createElement("div", { key: product.id, className: cx("seekora-amazon-dropdown__product-card", hoveredProduct === product.id
                            ? "seekora-amazon-dropdown__product-card--hover"
                            : ""), onClick: () => onProductClick?.(product._raw, idx), onMouseEnter: () => setHoveredProduct(product.id), onMouseLeave: () => setHoveredProduct(null) },
                        product.image ? (React.createElement("img", { src: product.image, alt: product.title, className: "seekora-amazon-dropdown__product-image", loading: "lazy" })) : (React.createElement("div", { className: "seekora-amazon-dropdown__product-image seekora-dropdown__placeholder-icon" },
                            React.createElement("span", null, "\uD83D\uDCF7"))),
                        React.createElement("div", { className: "seekora-amazon-dropdown__product-title" }, product.title),
                        product.price !== undefined && (React.createElement("div", { className: "seekora-amazon-dropdown__product-price" },
                            React.createElement("span", { className: "seekora-amazon-dropdown__product-price-symbol" }, 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", { className: "seekora-amazon-dropdown__footer" },
            React.createElement("div", { className: "seekora-amazon-dropdown__keyboard" },
                React.createElement("span", { className: "seekora-amazon-dropdown__key" }, "\u2191"),
                React.createElement("span", { className: "seekora-amazon-dropdown__key" }, "\u2193"),
                React.createElement("span", null, "to navigate"),
                React.createElement("span", { className: "seekora-amazon-dropdown__key" }, "\u21B5"),
                React.createElement("span", null, "to select"),
                React.createElement("span", { className: "seekora-amazon-dropdown__key" }, "esc"),
                React.createElement("span", null, "to close")),
            processedSuggestions.length > 0 && (React.createElement("span", null,
                processedSuggestions.length,
                " suggestions"))))));
    return wrapWithPortal(dropdownTree);
});
export default AmazonDropdown;
