/**
 * SpotlightDropdown - macOS Spotlight / Command Palette Style
 *
 * Features:
 * - Clean, centered modal design
 * - Category grouping with keyboard navigation
 * - Instant preview panel
 * - Actions/commands support
 * - Keyboard-first interaction
 */
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";
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 20 20", fill: "currentColor" },
    React.createElement("path", { fillRule: "evenodd", d: "M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z", clipRule: "evenodd" })));
const CommandIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { d: "M3.5 6A1.5 1.5 0 015 4.5h1.5A1.5 1.5 0 018 6v1.5H5A1.5 1.5 0 013.5 6zM8 6v8H5a1.5 1.5 0 110-3h3V8H5a1.5 1.5 0 010-3h3v1z" }),
    React.createElement("path", { d: "M12 6v8h3a1.5 1.5 0 100-3h-3V8h3a1.5 1.5 0 100-3h-3v1z" }),
    React.createElement("path", { d: "M16.5 6A1.5 1.5 0 0015 4.5h-1.5A1.5 1.5 0 0012 6v1.5h3A1.5 1.5 0 0016.5 6z" })));
const DocumentIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { fillRule: "evenodd", d: "M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z", clipRule: "evenodd" })));
const ShoppingIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { d: "M10 2a4 4 0 00-4 4v1H5a1 1 0 00-.994.89l-1 9A1 1 0 004 18h12a1 1 0 00.994-1.11l-1-9A1 1 0 0015 7h-1V6a4 4 0 00-4-4zm2 5V6a2 2 0 10-4 0v1h4zm-6 3a1 1 0 112 0 1 1 0 01-2 0zm7-1a1 1 0 100 2 1 1 0 000-2z" })));
const ClockIcon = () => (React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", width: "16", height: "16" },
    React.createElement("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z", clipRule: "evenodd" })));
export const SpotlightDropdown = forwardRef(function SpotlightDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], recentSearches = [], suggestionFields = { query: "query" }, productFields = { id: "id", title: "title" }, productDisplay = {}, theme = {}, showPreview = true, asOverlay = true, placeholder = "Powered by Seekora", showShortcuts = true, actions = [], width = "680px", maxHeight = "500px", zIndex = 9999, className, style, classNames = {}, inputRef, 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, 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 recentQueries = useMemo(() => recentSearches
        .map((r) => (typeof r === "string" ? r : r.query))
        .slice(0, 3), [recentSearches]);
    // Build flat list of all items
    const allItems = useMemo(() => {
        const items = [];
        // Actions first
        actions.forEach((action) => {
            items.push({
                type: "action",
                id: action.id,
                title: action.label,
                icon: action.icon,
                data: action,
            });
        });
        // Recent searches
        if (!query && recentQueries.length > 0) {
            recentQueries.forEach((q, idx) => {
                items.push({
                    type: "recent",
                    id: `recent-${idx}`,
                    title: q,
                    icon: React.createElement(ClockIcon, null),
                    data: q,
                });
            });
        }
        // Suggestions
        processedSuggestions.forEach((s, idx) => {
            items.push({
                type: "suggestion",
                id: s.id || `suggestion-${idx}`,
                title: s.query,
                icon: React.createElement(DocumentIcon, null),
                data: s,
            });
        });
        // Products
        processedProducts.forEach((p, idx) => {
            items.push({
                type: "product",
                id: p.id,
                title: p.title,
                subtitle: p.brand,
                icon: React.createElement(ShoppingIcon, null),
                image: p.image,
                price: p.price,
                data: p,
            });
        });
        return items;
    }, [actions, 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(() => {
        if (activeIndex < 0) {
            if (query.trim())
                onSearchSubmit?.(query.trim());
            return;
        }
        const item = allItems[activeIndex];
        if (!item)
            return;
        switch (item.type) {
            case "action":
                item.data.onAction?.();
                break;
            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: () => inputRef?.current?.focus(),
        close: () => onClose?.(),
    }), [
        activeIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        inputRef,
        onClose,
    ]);
    // Scroll active item into view
    useEffect(() => {
        if (listRef.current && activeIndex >= 0) {
            const activeEl = listRef.current.querySelector(`[data-index="${activeIndex}"]`);
            if (activeEl) {
                scrollIntoViewIfNeeded(activeEl, listRef.current);
            }
        }
    }, [activeIndex]);
    // Reset index when query changes
    useEffect(() => {
        setActiveIndex(-1);
    }, [query]);
    if (!isOpen)
        return null;
    const cssVariables = generateCSSVariables(theme);
    const activeItem = allItems[activeIndex];
    const content = (React.createElement("div", { ref: containerRef, className: cx("seekora-spotlight-dropdown__panel", className, classNames.root), style: portalStyle
            ? { ...cssVariables, ...portalStyle, ...style }
            : { width, ...cssVariables, ...style }, "data-position": dataPosition },
        React.createElement("style", null, `
        @keyframes seekora-spin {
          to { transform: rotate(360deg); }
        }
      `),
        React.createElement("div", { className: "seekora-spotlight-dropdown__search-container" },
            React.createElement("div", { className: "seekora-spotlight-dropdown__search-icon" },
                React.createElement(SearchIcon, null)),
            React.createElement("input", { ref: inputRef, type: "text", placeholder: placeholder, defaultValue: query, className: "seekora-spotlight-dropdown__search-input", onChange: (e) => onSearchSubmit?.(e.target.value), onKeyDown: (e) => {
                    if (e.key === "ArrowDown") {
                        e.preventDefault();
                        navigateNext();
                    }
                    else if (e.key === "ArrowUp") {
                        e.preventDefault();
                        navigatePrevious();
                    }
                    else if (e.key === "Enter") {
                        e.preventDefault();
                        selectActive();
                    }
                    else if (e.key === "Escape") {
                        onClose?.();
                    }
                }, autoFocus: true }),
            showShortcuts && (React.createElement("div", { className: "seekora-spotlight-dropdown__shortcut" },
                React.createElement("span", { className: "seekora-spotlight-dropdown__kbd" }, "\u2318"),
                React.createElement("span", { className: "seekora-spotlight-dropdown__kbd" }, "K")))),
        header,
        React.createElement("div", { className: "seekora-dropdown--spotlight seekora-dropdown__overlay-content" },
            React.createElement("div", { ref: listRef, className: "seekora-dropdown--spotlight seekora-dropdown__results-col", style: { maxHeight } }, allItems.length === 0 ? (renderEmpty ? (renderEmpty(query)) : (React.createElement("div", { className: "seekora-spotlight-dropdown__empty" },
                "No results for \"",
                query,
                "\""))) : (React.createElement(React.Fragment, null,
                actions.length > 0 && (React.createElement("div", { className: "seekora-spotlight-dropdown__section" },
                    React.createElement("div", { className: "seekora-spotlight-dropdown__section-title" }, "Actions"),
                    allItems
                        .filter((i) => i.type === "action")
                        .map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, className: cx("seekora-spotlight-dropdown__item", isActive
                                ? "seekora-spotlight-dropdown__item--active"
                                : ""), onClick: () => {
                                setActiveIndex(idx);
                                selectActive();
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-icon", isActive
                                    ? "seekora-spotlight-dropdown__item-icon--active"
                                    : "") }, item.icon),
                            React.createElement("div", { className: "seekora-spotlight-dropdown__item-content" },
                                React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-title", isActive
                                        ? "seekora-spotlight-dropdown__item-title--active"
                                        : "") }, item.title))));
                    }))),
                recentQueries.length > 0 && !query && (React.createElement("div", { className: "seekora-spotlight-dropdown__section" },
                    React.createElement("div", { className: "seekora-spotlight-dropdown__section-title" }, "Recent"),
                    allItems
                        .filter((i) => i.type === "recent")
                        .map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, className: cx("seekora-spotlight-dropdown__item", isActive
                                ? "seekora-spotlight-dropdown__item--active"
                                : ""), onClick: () => {
                                setActiveIndex(idx);
                                onRecentClick?.(item.data);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-icon", isActive
                                    ? "seekora-spotlight-dropdown__item-icon--active"
                                    : "") }, item.icon),
                            React.createElement("div", { className: "seekora-spotlight-dropdown__item-content" },
                                React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-title", isActive
                                        ? "seekora-spotlight-dropdown__item-title--active"
                                        : "") }, item.title))));
                    }))),
                processedSuggestions.length > 0 && (React.createElement("div", { className: "seekora-spotlight-dropdown__section" },
                    React.createElement("div", { className: "seekora-spotlight-dropdown__section-title" }, "Suggestions"),
                    allItems
                        .filter((i) => i.type === "suggestion")
                        .map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, className: cx("seekora-spotlight-dropdown__item", isActive
                                ? "seekora-spotlight-dropdown__item--active"
                                : ""), onClick: () => {
                                setActiveIndex(idx);
                                onSuggestionSelect?.(item.data._raw, idx);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-icon", isActive
                                    ? "seekora-spotlight-dropdown__item-icon--active"
                                    : "") }, item.icon),
                            React.createElement("div", { className: "seekora-spotlight-dropdown__item-content" },
                                React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-title", isActive
                                        ? "seekora-spotlight-dropdown__item-title--active"
                                        : "") }, highlightTextReact(item.title, query, {
                                    tag: "strong",
                                })))));
                    }))),
                processedProducts.length > 0 && (React.createElement("div", { className: "seekora-spotlight-dropdown__section" },
                    React.createElement("div", { className: "seekora-spotlight-dropdown__section-title" }, "Products"),
                    allItems
                        .filter((i) => i.type === "product")
                        .map((item) => {
                        const idx = allItems.indexOf(item);
                        const isActive = activeIndex === idx;
                        return (React.createElement("div", { key: item.id, "data-index": idx, className: cx("seekora-spotlight-dropdown__item", isActive
                                ? "seekora-spotlight-dropdown__item--active"
                                : ""), onClick: () => {
                                setActiveIndex(idx);
                                onProductClick?.(item.data._raw, idx);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-icon", isActive
                                    ? "seekora-spotlight-dropdown__item-icon--active"
                                    : "") }, item.image ? (React.createElement("img", { src: item.image, alt: "", className: "seekora-spotlight-dropdown__item-icon-image" })) : (item.icon)),
                            React.createElement("div", { className: "seekora-spotlight-dropdown__item-content" },
                                React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-title", isActive
                                        ? "seekora-spotlight-dropdown__item-title--active"
                                        : "") }, item.title),
                                item.subtitle && (React.createElement("div", { className: cx("seekora-spotlight-dropdown__item-subtitle", isActive
                                        ? "seekora-spotlight-dropdown__item-subtitle--active"
                                        : "") }, item.subtitle))),
                            item.price !== undefined && (React.createElement("span", { className: cx("seekora-spotlight-dropdown__item-action", "seekora-spotlight-dropdown__item-action--visible", isActive
                                    ? "seekora-spotlight-dropdown__item-action--active"
                                    : "") }, formatPrice(item.price, {
                                currency: productDisplay.currency,
                            })))));
                    })))))),
            showPreview && activeItem && activeItem.type === "product" && (React.createElement("div", { className: "seekora-dropdown--spotlight seekora-dropdown__preview-col" },
                React.createElement("div", { className: "seekora-spotlight-dropdown__preview-content" },
                    activeItem.image && (React.createElement("img", { src: activeItem.image, alt: "", className: "seekora-spotlight-dropdown__preview-image" })),
                    React.createElement("div", { className: "seekora-spotlight-dropdown__preview-title" }, activeItem.title),
                    activeItem.subtitle && (React.createElement("div", { className: "seekora-spotlight-dropdown__preview-subtitle" }, activeItem.subtitle)),
                    activeItem.price !== undefined && (React.createElement("div", { className: "seekora-spotlight-dropdown__preview-price" }, formatPrice(activeItem.price, {
                        currency: productDisplay.currency,
                    }))),
                    React.createElement("div", { className: "seekora-spotlight-dropdown__preview-actions" },
                        React.createElement("button", { className: "seekora-spotlight-dropdown__preview-action seekora-spotlight-dropdown__preview-action--primary", onClick: () => onProductClick?.(activeItem.data._raw, activeIndex) }, "View Product")))))),
        footer !== undefined ? (footer) : (React.createElement("div", { className: "seekora-spotlight-dropdown__footer" },
            React.createElement("div", { className: "seekora-spotlight-dropdown__footer-actions" },
                React.createElement("span", { className: "seekora-spotlight-dropdown__footer-action" },
                    React.createElement("span", { className: "seekora-spotlight-dropdown__kbd" }, "\u2191"),
                    React.createElement("span", { className: "seekora-spotlight-dropdown__kbd" }, "\u2193"),
                    "navigate"),
                React.createElement("span", { className: "seekora-spotlight-dropdown__footer-action" },
                    React.createElement("span", { className: "seekora-spotlight-dropdown__kbd" }, "\u21B5"),
                    "select"),
                React.createElement("span", { className: "seekora-spotlight-dropdown__footer-action" },
                    React.createElement("span", { className: "seekora-spotlight-dropdown__kbd" }, "esc"),
                    "close")),
            React.createElement("span", null,
                allItems.length,
                " results")))));
    if (asOverlay) {
        return (React.createElement("div", { className: "seekora-dropdown seekora-dropdown--spotlight seekora-spotlight-dropdown", style: { zIndex }, onClick: (e) => {
                if (e.target === e.currentTarget)
                    onClose?.();
            } }, content));
    }
    return wrapWithPortal(content);
});
export default SpotlightDropdown;
