/**
 * GoogleDropdown - Google-style Clean Search Suggestions
 *
 * Features:
 * - Ultra-clean, minimal design
 * - Instant suggestions with smooth animations
 * - Trending searches when empty
 * - "I'm Feeling Lucky" style quick actions
 * - Voice search integration ready
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from "react";
import { extractSuggestion, 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: "20", height: "20", viewBox: "0 0 24 24", fill: "none" },
    React.createElement("path", { d: "M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z", fill: "currentColor" })));
const ClockIcon = () => (React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none" },
    React.createElement("path", { d: "M13 3a9 9 0 00-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0013 21a9 9 0 000-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z", fill: "currentColor" })));
const TrendingIcon = () => (React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none" },
    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", fill: "currentColor" })));
const RemoveIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", width: "18", height: "18" },
    React.createElement("path", { d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z", fill: "currentColor" })));
const ArrowIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", width: "20", height: "20" },
    React.createElement("path", { d: "M9 5l-4 4 4 4", stroke: "currentColor", strokeWidth: "2", fill: "none", transform: "rotate(-90 12 12)" })));
export const GoogleDropdown = forwardRef(function GoogleDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], recentSearches = [], trendingSearches = [], suggestionFields = { query: "query" }, theme = {}, showFeelingLucky = true, feelingLuckyText = "I'm Feeling Lucky", showRemoveRecent = true, showVoiceSearch = false, showTrendingIndicator = true, width = "100%", maxHeight = "400px", zIndex = 1000, className, style, classNames = {}, onSuggestionSelect, onRecentClick, onRecentRemove, onVoiceSearch, onFeelingLucky, 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 [activeIndex, setActiveIndex] = useState(-1);
    const [hoveredIndex, setHoveredIndex] = useState(-1);
    const [hoveredBtn, setHoveredBtn] = useState(null);
    // Portal positioning — only active when anchorRef is provided.
    const { portalStyle, wrapWithPortal, dataPosition } = useAnchorPortal(anchorRef, 400, zIndex);
    // Process suggestions
    const processedSuggestions = useMemo(() => suggestions.map((s) => extractSuggestion(s, suggestionFields)), [suggestions, suggestionFields]);
    const recentQueries = useMemo(() => recentSearches
        .map((r) => (typeof r === "string" ? r : r.query))
        .slice(0, 5), [recentSearches]);
    const trendingQueries = useMemo(() => trendingSearches
        .map((t) => (typeof t === "string" ? t : t.query))
        .slice(0, 5), [trendingSearches]);
    // All items for navigation
    const allItems = useMemo(() => {
        const items = [];
        if (query.length === 0) {
            recentQueries.forEach((q) => items.push({ type: "recent", query: q }));
            trendingQueries.forEach((q) => items.push({ type: "trending", query: q }));
        }
        else {
            processedSuggestions.forEach((s) => items.push({ type: "suggestion", query: s.query, data: s }));
        }
        return items;
    }, [query, recentQueries, trendingQueries, 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) {
            if (query)
                onSearchSubmit?.(query);
            return;
        }
        const item = allItems[activeIndex];
        if (item.type === "recent" || item.type === "trending") {
            onRecentClick?.(item.query);
        }
        else {
            onSuggestionSelect?.(item.data?._raw || { query: item.query }, activeIndex);
        }
    }, [
        activeIndex,
        allItems,
        query,
        onSearchSubmit,
        onRecentClick,
        onSuggestionSelect,
    ]);
    // Expose ref
    useImperativeHandle(ref, () => ({
        getActiveIndex: () => activeIndex,
        setActiveIndex,
        selectActive,
        navigateNext,
        navigatePrevious,
        focus: () => containerRef.current?.focus(),
        close: () => onClose?.(),
    }), [activeIndex, selectActive, navigateNext, navigatePrevious, onClose]);
    // Reset active index when items change
    useEffect(() => {
        setActiveIndex(-1);
    }, [query]);
    // 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 && trendingQueries.length > 0;
    const renderItem = (item, index, globalIndex) => {
        const isActive = activeIndex === globalIndex;
        const isHovered = hoveredIndex === globalIndex;
        const showAction = isActive || isHovered;
        return (React.createElement("li", { key: `${item.type}-${item.query}-${index}`, "data-index": globalIndex, role: "option", "aria-selected": isActive, className: cx("seekora-google-dropdown__item", isActive || isHovered ? "seekora-google-dropdown__item--active" : ""), onClick: () => {
                if (item.type === "recent" || item.type === "trending") {
                    onRecentClick?.(item.query);
                }
                else {
                    onSuggestionSelect?.(item.data?._raw || { query: item.query }, index);
                }
            }, onMouseEnter: () => {
                setHoveredIndex(globalIndex);
                setActiveIndex(globalIndex);
            }, onMouseLeave: () => setHoveredIndex(-1) },
            React.createElement("div", { className: "seekora-google-dropdown__item-icon" }, item.type === "recent" ? (React.createElement(ClockIcon, null)) : item.type === "trending" ? (React.createElement(TrendingIcon, null)) : (React.createElement(SearchIcon, null))),
            React.createElement("div", { className: "seekora-google-dropdown__item-content" },
                React.createElement("span", { className: "seekora-google-dropdown__item-text" }, query
                    ? highlightTextReact(item.query, query, { tag: "b" })
                    : item.query),
                React.createElement("div", { className: "seekora-google-dropdown__item-actions-group" },
                    item.type === "trending" && showTrendingIndicator && (React.createElement("span", { className: "seekora-google-dropdown__trending" },
                        React.createElement(TrendingIcon, null),
                        "Trending")),
                    item.type === "recent" && showRemoveRecent && (React.createElement("button", { className: cx("seekora-google-dropdown__remove-btn", showAction
                            ? "seekora-google-dropdown__remove-btn--visible"
                            : ""), onClick: (e) => {
                            e.stopPropagation();
                            onRecentRemove?.(item.query);
                        }, "aria-label": `Remove ${item.query}` }, "Remove")),
                    React.createElement("span", { className: cx("seekora-google-dropdown__item-action", showAction
                            ? "seekora-google-dropdown__item-action--visible"
                            : "") },
                        React.createElement(ArrowIcon, null))))));
    };
    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--google seekora-google-dropdown", className, classNames.root), style: containerStyle, tabIndex: -1 },
        React.createElement("style", null, `
          @keyframes seekora-spin {
            to { transform: rotate(360deg); }
          }
        `),
        header,
        React.createElement(React.Fragment, null,
            React.createElement("ul", { className: "seekora-dropdown--google seekora-dropdown__list" },
                showRecent && (React.createElement(React.Fragment, null,
                    recentQueries.map((q, idx) => {
                        const item = { type: "recent", query: q };
                        const el = renderItem(item, idx, globalIndex);
                        globalIndex++;
                        return el;
                    }),
                    showTrending && (React.createElement("div", { className: "seekora-google-dropdown__divider" })))),
                showTrending && (React.createElement(React.Fragment, null,
                    !showRecent && (React.createElement("div", { className: "seekora-google-dropdown__section-title" }, "Trending searches")),
                    trendingQueries.map((q, idx) => {
                        const item = { type: "trending", query: q };
                        const el = renderItem(item, idx, globalIndex);
                        globalIndex++;
                        return el;
                    }))),
                query &&
                    processedSuggestions.length > 0 &&
                    processedSuggestions.map((s, idx) => {
                        const item = {
                            type: "suggestion",
                            query: s.query,
                            data: s,
                        };
                        const el = renderItem(item, idx, globalIndex);
                        globalIndex++;
                        return el;
                    }),
                query &&
                    processedSuggestions.length === 0 &&
                    !loading &&
                    (renderEmpty ? (renderEmpty(query)) : (React.createElement("li", { className: "seekora-google-dropdown__empty" },
                        "No suggestions for \"",
                        query,
                        "\"")))),
            (showFeelingLucky || showVoiceSearch) && (React.createElement("div", { className: "seekora-dropdown--google seekora-dropdown__footer" }, showFeelingLucky && (React.createElement(React.Fragment, null,
                React.createElement("button", { className: cx("seekora-google-dropdown__footer-button", hoveredBtn === "search"
                        ? "seekora-google-dropdown__footer-button--hover"
                        : ""), onMouseEnter: () => setHoveredBtn("search"), onMouseLeave: () => setHoveredBtn(null), onClick: () => onSearchSubmit?.(query ||
                        (activeIndex >= 0 ? allItems[activeIndex]?.query : "")) }, "Search"),
                React.createElement("button", { className: cx("seekora-google-dropdown__footer-button", hoveredBtn === "lucky"
                        ? "seekora-google-dropdown__footer-button--hover"
                        : ""), onMouseEnter: () => setHoveredBtn("lucky"), onMouseLeave: () => setHoveredBtn(null), onClick: () => onFeelingLucky?.(query ||
                        (activeIndex >= 0 ? allItems[activeIndex]?.query : "")) }, feelingLuckyText)))))),
        footer));
    return wrapWithPortal(dropdownTree);
});
export default GoogleDropdown;
