/**
 * 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, mergeStyles, generateCSSVariables, scrollIntoViewIfNeeded, } from './utils';
import { useInjectResponsiveStyles } from './styles';
// ============================================================================
// Styles
// ============================================================================
const createStyles = () => ({
    overlay: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.4)',
        zIndex: 9998,
        transition: 'opacity 200ms ease',
    },
    root: {
        position: 'fixed',
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'var(--seekora-bg-surface, transparent)',
        borderRadius: '16px 16px 0 0',
        boxShadow: '0 -4px 20px rgba(0, 0, 0, 0.15)',
        fontFamily: 'var(--seekora-font-family, -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif)',
        fontSize: 'var(--seekora-font-size, 16px)',
        zIndex: 9999,
        transform: 'translateY(0)',
        transition: 'transform 300ms cubic-bezier(0.32, 0.72, 0, 1)',
        maxHeight: '90vh',
        display: 'flex',
        flexDirection: 'column',
    },
    rootHidden: {
        transform: 'translateY(100%)',
    },
    dragHandle: {
        display: 'flex',
        justifyContent: 'center',
        padding: '12px',
        cursor: 'grab',
    },
    dragBar: {
        width: '36px',
        height: '5px',
        backgroundColor: 'var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderRadius: '3px',
    },
    header: {
        padding: '0 16px 16px',
        borderBottom: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
    },
    searchContainer: {
        display: 'flex',
        alignItems: 'center',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
        borderRadius: '12px',
        padding: '12px 16px',
        gap: '12px',
    },
    searchIcon: {
        width: '20px',
        height: '20px',
        color: 'var(--seekora-text-tertiary, #8e8e93)',
        flexShrink: 0,
    },
    searchInput: {
        flex: 1,
        border: 'none',
        background: 'transparent',
        fontSize: '17px',
        color: 'var(--seekora-text-primary, inherit)',
        outline: 'none',
    },
    cancelBtn: {
        padding: '8px',
        background: 'none',
        border: 'none',
        color: 'var(--seekora-primary, #007aff)',
        fontSize: '17px',
        cursor: 'pointer',
    },
    content: {
        flex: 1,
        overflowY: 'auto',
        overscrollBehavior: 'contain',
        WebkitOverflowScrolling: 'touch',
    },
    section: {
        padding: '8px 0',
    },
    sectionHeader: {
        padding: '16px 16px 8px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    sectionTitle: {
        fontSize: '13px',
        fontWeight: 600,
        color: 'var(--seekora-text-secondary, #8e8e93)',
        textTransform: 'uppercase',
        letterSpacing: '0.5px',
    },
    clearBtn: {
        fontSize: '15px',
        color: 'var(--seekora-primary, #007aff)',
        background: 'none',
        border: 'none',
        cursor: 'pointer',
    },
    item: {
        display: 'flex',
        alignItems: 'center',
        padding: '14px 16px',
        gap: '14px',
        cursor: 'pointer',
        transition: 'background-color 100ms',
        minHeight: '56px', // Touch-friendly
        color: 'var(--seekora-text-primary, inherit)',
    },
    itemActive: {
        backgroundColor: 'var(--seekora-bg-hover, rgba(255, 255, 255, 0.1))',
        color: 'var(--seekora-text-primary, inherit)',
    },
    itemIcon: {
        width: '24px',
        height: '24px',
        color: 'var(--seekora-text-tertiary, #8e8e93)',
        flexShrink: 0,
    },
    itemImage: {
        width: '48px',
        height: '48px',
        borderRadius: '8px',
        objectFit: 'cover',
        backgroundColor: 'var(--seekora-bg-secondary, #f5f5f5)',
        flexShrink: 0,
    },
    itemContent: {
        flex: 1,
        minWidth: 0,
    },
    itemTitle: {
        fontSize: '17px',
        color: 'var(--seekora-text-primary, inherit)',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    itemSubtitle: {
        fontSize: '15px',
        color: 'var(--seekora-text-secondary, inherit)',
        marginTop: '2px',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    itemAction: {
        color: 'var(--seekora-text-tertiary, #c7c7cc)',
        flexShrink: 0,
    },
    productsScroll: {
        display: 'flex',
        gap: '12px',
        padding: '0 16px 16px',
        overflowX: 'auto',
        scrollSnapType: 'x mandatory',
        WebkitOverflowScrolling: 'touch',
    },
    productCard: {
        flex: '0 0 140px',
        scrollSnapAlign: 'start',
        cursor: 'pointer',
    },
    productImage: {
        width: '140px',
        height: '140px',
        borderRadius: '12px',
        objectFit: 'cover',
        backgroundColor: 'var(--seekora-bg-secondary, #f5f5f5)',
        marginBottom: '8px',
    },
    productTitle: {
        fontSize: '15px',
        color: 'var(--seekora-text-primary, inherit)',
        marginBottom: '4px',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
    },
    productPrice: {
        fontSize: '15px',
        fontWeight: 600,
        color: 'var(--seekora-text-primary, inherit)',
    },
    footer: {
        padding: '12px 16px',
        paddingBottom: 'calc(12px + env(safe-area-inset-bottom, 0px))',
        borderTop: '1px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        backgroundColor: 'var(--seekora-bg-secondary, rgba(255, 255, 255, 0.1))',
    },
    footerBtn: {
        width: '100%',
        padding: '16px',
        backgroundColor: 'var(--seekora-primary, #007aff)',
        color: 'var(--seekora-text-inverse, transparent)',
        border: 'none',
        borderRadius: '12px',
        fontSize: '17px',
        fontWeight: 600,
        cursor: 'pointer',
    },
    loading: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px',
        color: 'var(--seekora-text-secondary, inherit)',
    },
    spinner: {
        width: '28px',
        height: '28px',
        border: '3px solid var(--seekora-border-color, rgba(128,128,128,0.2))',
        borderTopColor: 'var(--seekora-primary, #007aff)',
        borderRadius: '50%',
        animation: 'seekora-spin 0.8s linear infinite',
    },
    empty: {
        padding: '60px 20px',
        textAlign: 'center',
        color: 'var(--seekora-text-secondary, inherit)',
        fontSize: '17px',
    },
    emptyIcon: {
        width: '48px',
        height: '48px',
        margin: '0 auto 16px',
        color: 'var(--seekora-text-tertiary, #c7c7cc)',
    },
});
// ============================================================================
// 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, } = props;
    // Inject global responsive styles
    useInjectResponsiveStyles();
    const styles = useMemo(() => createStyles(), []);
    const containerRef = useRef(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [inputValue, setInputValue] = useState(query);
    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
    // Build all navigable items
    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) {
            // No selection, submit current query
            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;
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { style: {
                ...styles.overlay,
                opacity: isDragging ? 1 - (dragY / 300) : 1,
            }, onClick: onClose }),
        React.createElement("div", { ref: containerRef, className: cx('seekora-mobile-sheet', className, classNames.root), style: mergeStyles(styles.root, {
                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", { style: styles.dragHandle },
                React.createElement("div", { style: styles.dragBar }))),
            (showSearchInput || header) && (React.createElement("div", { style: styles.header }, header || (React.createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '12px' } },
                React.createElement("div", { style: styles.searchContainer },
                    React.createElement("div", { style: styles.searchIcon },
                        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?.();
                            }
                        }, style: styles.searchInput, autoFocus: true })),
                showCancel && (React.createElement("button", { style: styles.cancelBtn, onClick: onClose }, cancelText)))))),
            React.createElement("div", { style: styles.content },
                React.createElement(React.Fragment, null,
                    showRecent && (React.createElement("div", { style: styles.section },
                        React.createElement("div", { style: styles.sectionHeader },
                            React.createElement("span", { style: styles.sectionTitle }, "Recent"),
                            React.createElement("button", { style: styles.clearBtn, onClick: onRecentClearAll }, "Clear")),
                        recentQueries.map((q, idx) => (React.createElement("div", { key: `recent-${q}`, "data-index": idx, style: mergeStyles(styles.item, activeIndex === idx ? styles.itemActive : undefined), onClick: () => {
                                onRecentClick?.(q);
                                setInputValue(q);
                            }, onMouseEnter: () => setActiveIndex(idx) },
                            React.createElement("div", { style: styles.itemIcon },
                                React.createElement(ClockIcon, null)),
                            React.createElement("div", { style: styles.itemContent },
                                React.createElement("div", { style: styles.itemTitle }, q)),
                            React.createElement("div", { style: styles.itemAction },
                                React.createElement(ArrowUpIcon, null))))))),
                    showTrending && (React.createElement("div", { style: styles.section },
                        React.createElement("div", { style: styles.sectionHeader },
                            React.createElement("span", { style: styles.sectionTitle }, "Trending")),
                        trendingQueries.map((q, idx) => {
                            const globalIdx = recentQueries.length + idx;
                            return (React.createElement("div", { key: `trending-${q}`, "data-index": globalIdx, style: mergeStyles(styles.item, activeIndex === globalIdx ? styles.itemActive : undefined), onClick: () => {
                                    onRecentClick?.(q);
                                    setInputValue(q);
                                }, onMouseEnter: () => setActiveIndex(globalIdx) },
                                React.createElement("div", { style: styles.itemIcon },
                                    React.createElement(TrendingIcon, null)),
                                React.createElement("div", { style: styles.itemContent },
                                    React.createElement("div", { style: styles.itemTitle }, q)),
                                React.createElement("div", { style: styles.itemAction },
                                    React.createElement(ChevronIcon, null))));
                        }))),
                    inputValue && processedSuggestions.length > 0 && (React.createElement("div", { style: styles.section },
                        React.createElement("div", { style: styles.sectionHeader },
                            React.createElement("span", { style: styles.sectionTitle }, "Suggestions")),
                        processedSuggestions.map((s, idx) => {
                            const globalIdx = recentQueries.length + trendingQueries.length + idx;
                            return (React.createElement("div", { key: s.id || idx, "data-index": globalIdx, style: mergeStyles(styles.item, activeIndex === globalIdx ? styles.itemActive : undefined), onClick: () => onSuggestionSelect?.(s._raw, idx), onMouseEnter: () => setActiveIndex(globalIdx) },
                                React.createElement("div", { style: styles.itemIcon },
                                    React.createElement(SearchIcon, null)),
                                React.createElement("div", { style: styles.itemContent },
                                    React.createElement("div", { style: styles.itemTitle }, highlightTextReact(s.query, inputValue, { tag: 'strong' })),
                                    s.count && (React.createElement("div", { style: styles.itemSubtitle },
                                        s.count,
                                        " results"))),
                                React.createElement("div", { style: styles.itemAction },
                                    React.createElement(ChevronIcon, null))));
                        }))),
                    showProducts && (React.createElement("div", { style: styles.section },
                        React.createElement("div", { style: styles.sectionHeader },
                            React.createElement("span", { style: styles.sectionTitle }, "Products")),
                        React.createElement("div", { style: styles.productsScroll }, processedProducts.slice(0, 8).map((p, idx) => (React.createElement("div", { key: p.id, style: styles.productCard, onClick: () => onProductClick?.(p._raw, idx) },
                            p.image ? (React.createElement("img", { src: p.image, alt: p.title, style: styles.productImage, loading: "lazy" })) : (React.createElement("div", { style: styles.productImage })),
                            React.createElement("div", { style: styles.productTitle }, p.title),
                            p.price !== undefined && (React.createElement("div", { style: styles.productPrice }, formatPrice(p.price, {
                                currency: productDisplay.currency || p.currency || '$'
                            }))))))))),
                    inputValue && processedSuggestions.length === 0 && !loading && (renderEmpty ? renderEmpty(inputValue) : (React.createElement("div", { style: styles.empty },
                        React.createElement("div", { style: styles.emptyIcon },
                            React.createElement(SearchIcon, null)),
                        React.createElement("p", null,
                            "No results for \"",
                            inputValue,
                            "\"")))))),
            footer !== undefined ? footer : (showFooterButton && inputValue && (React.createElement("div", { style: styles.footer },
                React.createElement("button", { style: styles.footerBtn, onClick: () => onSearchSubmit?.(inputValue) },
                    footerButtonText,
                    " \"",
                    inputValue,
                    "\"")))))));
});
export default MobileSheetDropdown;
