/**
 * 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, generateCSSVariables, calculateDiscount, 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 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, 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);
    const [hoveredProduct, setHoveredProduct] = useState(null);
    const [hoveredCollection, setHoveredCollection] = useState(null);
    const [hoveredButton, setHoveredButton] = useState(false);
    // Portal positioning — only active when anchorRef is provided.
    const { portalStyle, wrapWithPortal, dataPosition } = useAnchorPortal(anchorRef, 500, zIndex);
    // 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;
    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--shopify seekora-shopify-dropdown", className, classNames.root), style: containerStyle, 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", { className: "seekora-dropdown--shopify seekora-dropdown__layout" },
            React.createElement("div", { className: "seekora-shopify-dropdown__left-panel" },
                React.createElement("div", { className: "seekora-shopify-dropdown__section" },
                    React.createElement("div", { className: "seekora-shopify-dropdown__section-header" },
                        React.createElement("span", { className: "seekora-shopify-dropdown__section-title" }, "Suggestions"),
                        processedSuggestions.length > 5 && (React.createElement("span", { className: "seekora-shopify-dropdown__view-all-link", 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, className: cx("seekora-shopify-dropdown__suggestion-item", isActive
                                ? "seekora-shopify-dropdown__suggestion-item--active"
                                : ""), onClick: () => onSuggestionSelect?.(suggestion._raw, idx), onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { className: "seekora-shopify-dropdown__suggestion-icon" },
                                React.createElement(SearchIcon, null)),
                            React.createElement("div", { className: "seekora-shopify-dropdown__suggestion-content" },
                                React.createElement("div", { className: "seekora-shopify-dropdown__suggestion-query" }, highlightTextReact(suggestion.query, query, {
                                    tag: "mark",
                                })),
                                suggestion.count && (React.createElement("div", { className: "seekora-shopify-dropdown__suggestion-meta" },
                                    suggestion.count,
                                    " results"))),
                            React.createElement("div", { className: cx("seekora-shopify-dropdown__suggestion-arrow", isActive
                                    ? "seekora-shopify-dropdown__suggestion-arrow--visible"
                                    : "") },
                                React.createElement(ArrowIcon, null))));
                    }),
                    processedSuggestions.length === 0 &&
                        query &&
                        (renderEmpty ? (renderEmpty(query)) : (React.createElement("div", { className: "seekora-shopify-dropdown__empty" },
                            "No suggestions for \"",
                            query,
                            "\"")))),
                showCollections && processedCategories.length > 0 && (React.createElement(React.Fragment, null,
                    React.createElement("div", { className: "seekora-shopify-dropdown__section-header" },
                        React.createElement("span", { className: "seekora-shopify-dropdown__section-title" }, "Collections")),
                    React.createElement("div", { className: "seekora-dropdown--shopify seekora-dropdown__collections-grid" }, processedCategories.slice(0, 4).map((cat) => (React.createElement("div", { key: cat.id, className: cx("seekora-shopify-dropdown__collection-item", hoveredCollection === cat.id
                            ? "seekora-shopify-dropdown__collection-item--hover"
                            : ""), onClick: () => onTabChange?.(cat.id), onMouseEnter: () => setHoveredCollection(cat.id), onMouseLeave: () => setHoveredCollection(null) },
                        React.createElement("div", { className: "seekora-shopify-dropdown__collection-name" }, cat.label),
                        cat.count && (React.createElement("div", { className: "seekora-shopify-dropdown__collection-count" },
                            cat.count,
                            " products"))))))))),
            React.createElement("div", { className: "seekora-shopify-dropdown__right-panel" },
                showHeroProduct && heroProduct && (React.createElement("div", { className: "seekora-shopify-dropdown__hero-product" },
                    heroProduct.image && (React.createElement("img", { src: heroProduct.image, alt: heroProduct.title, className: "seekora-shopify-dropdown__hero-image", loading: "lazy" })),
                    heroProduct.brand && (React.createElement("div", { className: "seekora-shopify-dropdown__hero-brand" }, heroProduct.brand)),
                    React.createElement("div", { className: "seekora-shopify-dropdown__hero-title" }, heroProduct.title),
                    React.createElement("div", { className: "seekora-shopify-dropdown__hero-pricing" },
                        React.createElement("span", { className: "seekora-shopify-dropdown__hero-price" }, formatPrice(heroProduct.price, {
                            currency: productDisplay.currency || heroProduct.currency || "$",
                        })),
                        showComparePrice && heroProduct.comparePrice && (React.createElement("span", { className: "seekora-shopify-dropdown__hero-compare-price" }, formatPrice(heroProduct.comparePrice, {
                            currency: productDisplay.currency ||
                                heroProduct.currency ||
                                "$",
                        }))),
                        heroDiscount && (React.createElement("span", { className: "seekora-shopify-dropdown__hero-discount" },
                            "-",
                            heroDiscount,
                            "%"))),
                    showAddToCart && (React.createElement("button", { className: cx("seekora-shopify-dropdown__hero-button", hoveredButton
                            ? "seekora-shopify-dropdown__hero-button--hover"
                            : ""), onClick: () => onAddToCart?.(heroProduct._raw), onMouseEnter: () => setHoveredButton(true), onMouseLeave: () => setHoveredButton(false) }, addToCartText)))),
                otherProducts.length > 0 && (React.createElement(React.Fragment, null,
                    React.createElement("div", { className: "seekora-dropdown--shopify seekora-dropdown__more-products-label" }, "More Products"),
                    React.createElement("div", { className: "seekora-dropdown--shopify seekora-dropdown__products-scroll" }, otherProducts.map((product, idx) => (React.createElement("div", { key: product.id, className: cx("seekora-shopify-dropdown__product-card", hoveredProduct === product.id
                            ? "seekora-shopify-dropdown__product-card--hover"
                            : ""), onClick: () => onProductClick?.(product._raw, idx + 1), onMouseEnter: () => setHoveredProduct(product.id), onMouseLeave: () => setHoveredProduct(null) },
                        product.image ? (React.createElement("img", { src: product.image, alt: product.title, className: "seekora-shopify-dropdown__product-image", loading: "lazy" })) : (React.createElement("div", { className: "seekora-shopify-dropdown__product-image" })),
                        React.createElement("div", { className: "seekora-shopify-dropdown__product-title" }, product.title),
                        product.price !== undefined && (React.createElement("div", { className: "seekora-shopify-dropdown__product-price" }, formatPrice(product.price, {
                            currency: productDisplay.currency ||
                                product.currency ||
                                "$",
                        }))))))))))),
        footer !== undefined ? (footer) : (React.createElement("div", { className: "seekora-shopify-dropdown__footer" },
            React.createElement("span", null,
                "Press ",
                React.createElement("strong", null, "Enter"),
                " to search, ",
                React.createElement("strong", null, "\u2191\u2193"),
                " to navigate"),
            React.createElement("span", { className: "seekora-shopify-dropdown__footer-link", onClick: () => onViewAll?.("products") }, "View all results")))));
    return wrapWithPortal(dropdownTree);
});
export default ShopifyDropdown;
