/**
 * MobileSheetDropdown - Mobile-First Bottom Sheet Style
 *
 * Features:
 * - iOS-style bottom sheet with drag handle
 * - Full-screen overlay with smooth transitions
 * - Touch-friendly large tap targets
 * - Swipe to dismiss
 * - Optimized for small screens
 */
import React, { useState, useRef, useCallback, forwardRef, useImperativeHandle, useMemo, useEffect, } from "react";
import { extractSuggestion, extractProduct, formatPrice, highlightTextReact, cx, generateCSSVariables, scrollIntoViewIfNeeded, } from "./utils";
import { useInjectResponsiveStyles } from "./styles";
import { ensureSeekoraStyles } from "../../styles/inject";
import { useAnchorPortal } from "../../utils/use-anchor-portal";
// ============================================================================
// Icons
// ============================================================================
const SearchIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" },
    React.createElement("circle", { cx: "11", cy: "11", r: "7" }),
    React.createElement("path", { d: "M21 21l-4.35-4.35" })));
const ClockIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" },
    React.createElement("circle", { cx: "12", cy: "12", r: "10" }),
    React.createElement("polyline", { points: "12 6 12 12 16 14" })));
const TrendingIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" },
    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 ChevronIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", width: "20", height: "20" },
    React.createElement("polyline", { points: "9 18 15 12 9 6" })));
const ArrowUpIcon = () => (React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", width: "20", height: "20" },
    React.createElement("path", { d: "M7 17l5-5-5-5M13 17l5-5-5-5" })));
export const MobileSheetDropdown = forwardRef(function MobileSheetDropdown(props, ref) {
    const { query, isOpen = true, loading = false, suggestions = [], products = [], recentSearches = [], trendingSearches = [], suggestionFields = { query: "query" }, productFields = { id: "id", title: "title" }, productDisplay = {}, theme = {}, showSearchInput = true, showCancel = true, cancelText = "Cancel", showDragHandle = true, swipeToDismiss = true, footerButtonText = "Search", showFooterButton = true, width = "100%", maxHeight = "85vh", zIndex = 9999, className, style, classNames = {}, inputRef, onSuggestionSelect, onProductClick, onRecentClick, onRecentClearAll, onSearchSubmit, onClose, header, footer, renderEmpty, anchorRef, } = props;
    // Inject global component styles
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    // Inject global responsive styles
    useInjectResponsiveStyles();
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [inputValue, setInputValue] = useState(query);
    // Portal — escapes stacking-context ancestors. The sheet itself uses CSS
    // fixed positioning, so portalStyle is not applied to the sheet styles.
    const { wrapWithPortal } = useAnchorPortal(anchorRef, 0, zIndex);
    const [dragY, setDragY] = useState(0);
    const [isDragging, setIsDragging] = useState(false);
    const dragStartY = useRef(0);
    // 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, 5), [recentSearches]);
    const trendingQueries = useMemo(() => trendingSearches
        .map((t) => (typeof t === "string" ? t : t.query))
        .slice(0, 5), [trendingSearches]);
    // Navigation
    const allItems = useMemo(() => {
        const items = [];
        recentQueries.forEach((q) => items.push({ type: "recent", data: q }));
        trendingQueries.forEach((q) => items.push({ type: "trending", data: q }));
        processedSuggestions.forEach((s) => items.push({ type: "suggestion", data: s }));
        return items;
    }, [recentQueries, trendingQueries, processedSuggestions]);
    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) {
            if (inputValue.trim())
                onSearchSubmit?.(inputValue.trim());
            return;
        }
        const item = allItems[activeIndex];
        if (item.type === "recent" || item.type === "trending") {
            onRecentClick?.(item.data);
        }
        else if (item.type === "suggestion") {
            onSuggestionSelect?.(item.data._raw, activeIndex);
        }
    }, [
        activeIndex,
        allItems,
        inputValue,
        onSearchSubmit,
        onRecentClick,
        onSuggestionSelect,
    ]);
    // 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 (activeIndex >= 0 && containerRef.current) {
            const activeEl = containerRef.current.querySelector(`[data-index="${activeIndex}"]`);
            if (activeEl) {
                scrollIntoViewIfNeeded(activeEl, containerRef.current);
            }
        }
    }, [activeIndex]);
    // Drag to dismiss
    const handleDragStart = (e) => {
        if (!swipeToDismiss)
            return;
        setIsDragging(true);
        dragStartY.current = e.touches[0].clientY;
    };
    const handleDrag = (e) => {
        if (!isDragging)
            return;
        const deltaY = e.touches[0].clientY - dragStartY.current;
        if (deltaY > 0) {
            setDragY(deltaY);
        }
    };
    const handleDragEnd = () => {
        if (!isDragging)
            return;
        setIsDragging(false);
        if (dragY > 150) {
            onClose?.();
        }
        setDragY(0);
    };
    // Sync input value
    useEffect(() => {
        setInputValue(query);
    }, [query]);
    if (!isOpen)
        return null;
    const cssVariables = generateCSSVariables(theme);
    const showRecent = !inputValue && recentQueries.length > 0;
    const showTrending = !inputValue && trendingQueries.length > 0;
    const showProducts = processedProducts.length > 0;
    const sheetTree = (React.createElement(React.Fragment, null,
        React.createElement("div", { className: "seekora-dropdown--mobile-sheet seekora-dropdown__overlay", style: { opacity: isDragging ? 1 - dragY / 300 : 1 }, onClick: onClose }),
        React.createElement("div", { ref: containerRef, className: cx("seekora-dropdown seekora-dropdown--mobile-sheet seekora-mobile-sheet", className, classNames.root), style: {
                maxHeight,
                zIndex,
                transform: isDragging ? `translateY(${dragY}px)` : "translateY(0)",
                ...cssVariables,
                ...style,
            }, onTouchStart: handleDragStart, onTouchMove: handleDrag, onTouchEnd: handleDragEnd },
            React.createElement("style", null, `
          @keyframes seekora-spin {
            to { transform: rotate(360deg); }
          }
        `),
            showDragHandle && (React.createElement("div", { className: "seekora-mobile-sheet__drag-handle" },
                React.createElement("div", { className: "seekora-mobile-sheet__drag-bar" }))),
            (showSearchInput || header) && (React.createElement("div", { className: "seekora-mobile-sheet__header" }, header || (React.createElement("div", { className: "seekora-mobile-sheet__header-row" },
                React.createElement("div", { className: "seekora-mobile-sheet__search-container" },
                    React.createElement("div", { className: "seekora-mobile-sheet__search-icon" },
                        React.createElement(SearchIcon, null)),
                    React.createElement("input", { ref: inputRef, type: "text", placeholder: "Powered by Seekora", value: inputValue, onChange: (e) => setInputValue(e.target.value), onKeyDown: (e) => {
                            if (e.key === "Enter") {
                                e.preventDefault();
                                if (activeIndex >= 0) {
                                    selectActive();
                                }
                                else if (inputValue.trim()) {
                                    onSearchSubmit?.(inputValue.trim());
                                }
                            }
                            else if (e.key === "ArrowDown") {
                                e.preventDefault();
                                navigateNext();
                            }
                            else if (e.key === "ArrowUp") {
                                e.preventDefault();
                                navigatePrevious();
                            }
                            else if (e.key === "Escape") {
                                onClose?.();
                            }
                        }, className: "seekora-mobile-sheet__search-input", autoFocus: true })),
                showCancel && (React.createElement("button", { className: "seekora-mobile-sheet__cancel-btn", onClick: onClose }, cancelText)))))),
            React.createElement("div", { className: "seekora-mobile-sheet__content" },
                React.createElement(React.Fragment, null,
                    showRecent && (React.createElement("div", { className: "seekora-mobile-sheet__section" },
                        React.createElement("div", { className: "seekora-mobile-sheet__section-header" },
                            React.createElement("span", { className: "seekora-mobile-sheet__section-title" }, "Recent"),
                            React.createElement("button", { className: "seekora-mobile-sheet__clear-btn", onClick: onRecentClearAll }, "Clear")),
                        recentQueries.map((q, idx) => (React.createElement("div", { key: `recent-${q}`, "data-index": idx, className: cx("seekora-mobile-sheet__item", activeIndex === idx
                                ? "seekora-mobile-sheet__item--active"
                                : ""), onClick: () => {
                                onRecentClick?.(q);
                                setInputValue(q);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { className: "seekora-mobile-sheet__item-icon" },
                                React.createElement(ClockIcon, null)),
                            React.createElement("div", { className: "seekora-mobile-sheet__item-content" },
                                React.createElement("div", { className: "seekora-mobile-sheet__item-title" }, q)),
                            React.createElement("div", { className: "seekora-mobile-sheet__item-action" },
                                React.createElement(ArrowUpIcon, null))))))),
                    showTrending && (React.createElement("div", { className: "seekora-mobile-sheet__section" },
                        React.createElement("div", { className: "seekora-mobile-sheet__section-header" },
                            React.createElement("span", { className: "seekora-mobile-sheet__section-title" }, "Trending")),
                        trendingQueries.map((q, idx) => {
                            const globalIdx = recentQueries.length + idx;
                            return (React.createElement("div", { key: `trending-${q}`, "data-index": globalIdx, className: cx("seekora-mobile-sheet__item", activeIndex === globalIdx
                                    ? "seekora-mobile-sheet__item--active"
                                    : ""), onClick: () => {
                                    onRecentClick?.(q);
                                    setInputValue(q);
                                }, onMouseEnter: () => setActiveIndex(globalIdx) },
                                React.createElement("div", { className: "seekora-mobile-sheet__item-icon" },
                                    React.createElement(TrendingIcon, null)),
                                React.createElement("div", { className: "seekora-mobile-sheet__item-content" },
                                    React.createElement("div", { className: "seekora-mobile-sheet__item-title" }, q)),
                                React.createElement("div", { className: "seekora-mobile-sheet__item-action" },
                                    React.createElement(ChevronIcon, null))));
                        }))),
                    inputValue && processedSuggestions.length > 0 && (React.createElement("div", { className: "seekora-mobile-sheet__section" },
                        React.createElement("div", { className: "seekora-mobile-sheet__section-header" },
                            React.createElement("span", { className: "seekora-mobile-sheet__section-title" }, "Suggestions")),
                        processedSuggestions.map((s, idx) => {
                            const globalIdx = recentQueries.length + trendingQueries.length + idx;
                            return (React.createElement("div", { key: s.id || idx, "data-index": globalIdx, className: cx("seekora-mobile-sheet__item", activeIndex === globalIdx
                                    ? "seekora-mobile-sheet__item--active"
                                    : ""), onClick: () => onSuggestionSelect?.(s._raw, idx), onMouseEnter: () => setActiveIndex(globalIdx) },
                                React.createElement("div", { className: "seekora-mobile-sheet__item-icon" },
                                    React.createElement(SearchIcon, null)),
                                React.createElement("div", { className: "seekora-mobile-sheet__item-content" },
                                    React.createElement("div", { className: "seekora-mobile-sheet__item-title" }, highlightTextReact(s.query, inputValue, {
                                        tag: "strong",
                                    })),
                                    s.count && (React.createElement("div", { className: "seekora-mobile-sheet__item-subtitle" },
                                        s.count,
                                        " results"))),
                                React.createElement("div", { className: "seekora-mobile-sheet__item-action" },
                                    React.createElement(ChevronIcon, null))));
                        }))),
                    showProducts && (React.createElement("div", { className: "seekora-mobile-sheet__section" },
                        React.createElement("div", { className: "seekora-mobile-sheet__section-header" },
                            React.createElement("span", { className: "seekora-mobile-sheet__section-title" }, "Products")),
                        React.createElement("div", { className: "seekora-dropdown--mobile-sheet seekora-dropdown__products-scroll" }, processedProducts.slice(0, 8).map((p, idx) => (React.createElement("div", { key: p.id, className: "seekora-mobile-sheet__product-card", onClick: () => onProductClick?.(p._raw, idx) },
                            p.image ? (React.createElement("img", { src: p.image, alt: p.title, className: "seekora-mobile-sheet__product-image", loading: "lazy" })) : (React.createElement("div", { className: "seekora-mobile-sheet__product-image" })),
                            React.createElement("div", { className: "seekora-mobile-sheet__product-title" }, p.title),
                            p.price !== undefined && (React.createElement("div", { className: "seekora-mobile-sheet__product-price" }, formatPrice(p.price, {
                                currency: productDisplay.currency || p.currency || "$",
                            }))))))))),
                    inputValue &&
                        processedSuggestions.length === 0 &&
                        !loading &&
                        (renderEmpty ? (renderEmpty(inputValue)) : (React.createElement("div", { className: "seekora-mobile-sheet__empty" },
                            React.createElement("div", { className: "seekora-mobile-sheet__empty-icon" },
                                React.createElement(SearchIcon, null)),
                            React.createElement("p", null,
                                "No results for \"",
                                inputValue,
                                "\"")))))),
            footer !== undefined
                ? footer
                : showFooterButton &&
                    inputValue && (React.createElement("div", { className: "seekora-dropdown--mobile-sheet seekora-dropdown__footer" },
                    React.createElement("button", { className: "seekora-mobile-sheet__footer-btn", onClick: () => onSearchSubmit?.(inputValue) },
                        footerButtonText,
                        " \"",
                        inputValue,
                        "\""))))));
    return wrapWithPortal(sheetTree);
});
export default MobileSheetDropdown;
