/**
 * MinimalDropdown - Ultra-Clean Minimalist Style
 *
 * Features:
 * - Stripped-down, distraction-free design
 * - Focus on typography and whitespace
 * - Subtle animations
 * - Perfect for editorial/content sites
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from "react";
import { extractSuggestion, extractProduct, 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";
export const MinimalDropdown = forwardRef(function MinimalDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], recentSearches = [], suggestionFields = { query: "query" }, productFields = { id: "id", title: "title" }, productDisplay = {}, theme = {}, showIndices = false, showTypeLabels = false, showSectionDividers = true, width = "100%", maxHeight = "400px", zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onProductClick, onRecentClick, onClose, onSearchSubmit, 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 listRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    // Portal positioning — only active when anchorRef is provided.
    const { portalStyle, wrapWithPortal, dataPosition } = useAnchorPortal(anchorRef, 400, 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 recentQueries = useMemo(() => recentSearches
        .map((r) => (typeof r === "string" ? r : r.query))
        .slice(0, 3), [recentSearches]);
    // All items for navigation
    const allItems = useMemo(() => {
        const items = [];
        if (!query && recentQueries.length > 0) {
            recentQueries.forEach((q) => items.push({ type: "recent", data: q }));
        }
        processedSuggestions.forEach((s) => items.push({ type: "suggestion", data: s }));
        processedProducts.forEach((p) => items.push({ type: "product", data: p }));
        return items;
    }, [query, recentQueries, processedSuggestions, processedProducts]);
    // 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(() => {
        const item = allItems[activeIndex];
        if (!item) {
            if (query)
                onSearchSubmit?.(query);
            return;
        }
        switch (item.type) {
            case "recent":
                onRecentClick?.(item.data);
                break;
            case "suggestion":
                onSuggestionSelect?.(item.data._raw, activeIndex);
                break;
            case "product":
                onProductClick?.(item.data._raw, activeIndex);
                break;
        }
    }, [
        activeIndex,
        allItems,
        query,
        onSearchSubmit,
        onRecentClick,
        onSuggestionSelect,
        onProductClick,
    ]);
    // Expose ref
    useImperativeHandle(ref, () => ({
        getActiveIndex: () => activeIndex,
        setActiveIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        focus: () => containerRef.current?.focus(),
        close: () => onClose?.(),
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, onClose]);
    // Scroll active into view
    useEffect(() => {
        if (listRef.current && activeIndex >= 0) {
            const activeEl = listRef.current.querySelector(`[data-index="${activeIndex}"]`);
            if (activeEl) {
                scrollIntoViewIfNeeded(activeEl, listRef.current);
            }
        }
    }, [activeIndex]);
    // Reset on query change
    useEffect(() => {
        setActiveIndex(-1);
    }, [query]);
    if (!isOpen)
        return null;
    const cssVariables = generateCSSVariables(theme);
    const showRecent = !query && recentQueries.length > 0;
    let globalIndex = 0;
    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--minimal seekora-minimal-dropdown", className, classNames.root), style: containerStyle, tabIndex: -1 },
        React.createElement("style", null, `
          .seekora-minimal-dropdown mark {
            background-color: var(--seekora-highlight-bg, #fff3cd);
            padding: 0 2px;
          }
        `),
        header,
        React.createElement("div", { ref: listRef, className: "seekora-dropdown--minimal seekora-dropdown__list-wrapper", style: { maxHeight } }, allItems.length === 0 ? (renderEmpty ? (renderEmpty(query)) : (React.createElement("div", { className: "seekora-minimal-dropdown__empty" }, query ? `No results for "${query}"` : "Start typing to search"))) : (React.createElement(React.Fragment, null,
            showRecent && (React.createElement(React.Fragment, null,
                showSectionDividers && (React.createElement("div", { className: "seekora-minimal-dropdown__divider" }, "Recent")),
                recentQueries.map((q, idx) => {
                    const itemIdx = globalIndex++;
                    const isActive = activeIndex === itemIdx;
                    const isLast = idx === recentQueries.length - 1 &&
                        !processedSuggestions.length &&
                        !processedProducts.length;
                    return (React.createElement("div", { key: `recent-${q}`, "data-index": itemIdx, className: cx("seekora-minimal-dropdown__item", isActive
                            ? "seekora-minimal-dropdown__item--active"
                            : "", isLast ? "seekora-minimal-dropdown__item--last" : ""), onClick: () => onRecentClick?.(q), onMouseEnter: () => setActiveIndex(itemIdx) },
                        showIndices && (React.createElement("span", { className: "seekora-minimal-dropdown__item-index" }, itemIdx + 1)),
                        React.createElement("div", { className: "seekora-minimal-dropdown__item-content" },
                            React.createElement("div", { className: "seekora-minimal-dropdown__item-query" }, q)),
                        showTypeLabels && (React.createElement("span", { className: "seekora-minimal-dropdown__item-type" }, "Recent"))));
                }))),
            processedSuggestions.length > 0 && (React.createElement(React.Fragment, null,
                showSectionDividers && (showRecent || false) && (React.createElement("div", { className: "seekora-minimal-dropdown__divider" }, "Suggestions")),
                processedSuggestions.map((s, idx) => {
                    const itemIdx = globalIndex++;
                    const isActive = activeIndex === itemIdx;
                    const isLast = idx === processedSuggestions.length - 1 &&
                        !processedProducts.length;
                    return (React.createElement("div", { key: s.id || `suggestion-${idx}`, "data-index": itemIdx, className: cx("seekora-minimal-dropdown__item", isActive
                            ? "seekora-minimal-dropdown__item--active"
                            : "", isLast ? "seekora-minimal-dropdown__item--last" : ""), onClick: () => onSuggestionSelect?.(s._raw, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                        showIndices && (React.createElement("span", { className: "seekora-minimal-dropdown__item-index" }, itemIdx + 1)),
                        React.createElement("div", { className: "seekora-minimal-dropdown__item-content" },
                            React.createElement("div", { className: "seekora-minimal-dropdown__item-query" }, highlightTextReact(s.query, query, {
                                tag: "mark",
                            })),
                            s.count && (React.createElement("div", { className: "seekora-minimal-dropdown__item-meta" },
                                s.count.toLocaleString(),
                                " results"))),
                        showTypeLabels && (React.createElement("span", { className: "seekora-minimal-dropdown__item-type" }, "Search"))));
                }))),
            processedProducts.length > 0 && (React.createElement(React.Fragment, null,
                showSectionDividers && (React.createElement("div", { className: "seekora-minimal-dropdown__divider" }, "Products")),
                processedProducts.slice(0, 4).map((p, idx) => {
                    const itemIdx = globalIndex++;
                    const isActive = activeIndex === itemIdx;
                    return (React.createElement("div", { key: p.id, "data-index": itemIdx, className: cx("seekora-minimal-dropdown__product-row", isActive
                            ? "seekora-minimal-dropdown__product-row--active"
                            : ""), onClick: () => onProductClick?.(p._raw, idx), onMouseEnter: () => setActiveIndex(itemIdx) },
                        p.image && (React.createElement("img", { src: p.image, alt: p.title, className: "seekora-minimal-dropdown__product-image", loading: "lazy" })),
                        React.createElement("div", { className: "seekora-minimal-dropdown__product-content" },
                            React.createElement("div", { className: "seekora-minimal-dropdown__product-title" }, p.title),
                            p.price !== undefined && (React.createElement("div", { className: "seekora-minimal-dropdown__product-price" }, formatPrice(p.price, {
                                currency: productDisplay.currency || p.currency || "$",
                            })))),
                        showTypeLabels && (React.createElement("span", { className: "seekora-minimal-dropdown__item-type" }, "Product"))));
                })))))),
        footer !== undefined ? (footer) : (React.createElement("div", { className: "seekora-dropdown--minimal seekora-dropdown__footer" },
            React.createElement("div", { className: "seekora-minimal-dropdown__footer-hint" },
                React.createElement("span", null,
                    React.createElement("span", { className: "seekora-minimal-dropdown__kbd" }, "\u2191"),
                    " ",
                    React.createElement("span", { className: "seekora-minimal-dropdown__kbd" }, "\u2193"),
                    " ",
                    "navigate"),
                React.createElement("span", null,
                    React.createElement("span", { className: "seekora-minimal-dropdown__kbd" }, "\u21B5"),
                    " select"),
                React.createElement("span", null,
                    React.createElement("span", { className: "seekora-minimal-dropdown__kbd" }, "esc"),
                    " close")),
            React.createElement("span", null,
                allItems.length,
                " results")))));
    return wrapWithPortal(dropdownTree);
});
export default MinimalDropdown;
