/**
 * MobileFilters Component
 *
 * A full-screen filter drawer optimized for mobile devices
 * Slides in from the side or bottom to display facets and filters
 */
import React, { useEffect, useCallback, useRef } from 'react';
import { useSearchContext } from './SearchProvider';
import { useSearchState } from '../hooks/useSearchState';
import { clsx } from 'clsx';
export const MobileFilters = ({ isOpen, onClose, onApply, title = 'Filters', applyButtonText = 'Apply', clearButtonText = 'Clear all', position = 'right', children, className, theme: customTheme, showHeader = true, showFooter = true, showFilterCount = true, closeOnBackdropClick = true, closeOnEscape = true, }) => {
    const { theme } = useSearchContext();
    const { refinements, clearRefinements } = useSearchState();
    const mobileFiltersTheme = customTheme || {};
    const drawerRef = useRef(null);
    // Lock body scroll when open
    useEffect(() => {
        if (isOpen) {
            document.body.style.overflow = 'hidden';
        }
        else {
            document.body.style.overflow = '';
        }
        return () => {
            document.body.style.overflow = '';
        };
    }, [isOpen]);
    // Handle escape key
    useEffect(() => {
        if (!closeOnEscape)
            return;
        const handleKeyDown = (e) => {
            if (e.key === 'Escape' && isOpen) {
                onClose();
            }
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, onClose, closeOnEscape]);
    // Focus trap
    useEffect(() => {
        if (isOpen && drawerRef.current) {
            const focusableElements = drawerRef.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
            const firstElement = focusableElements[0];
            const lastElement = focusableElements[focusableElements.length - 1];
            const handleTab = (e) => {
                if (e.key !== 'Tab')
                    return;
                if (e.shiftKey) {
                    if (document.activeElement === firstElement) {
                        e.preventDefault();
                        lastElement?.focus();
                    }
                }
                else {
                    if (document.activeElement === lastElement) {
                        e.preventDefault();
                        firstElement?.focus();
                    }
                }
            };
            document.addEventListener('keydown', handleTab);
            firstElement?.focus();
            return () => document.removeEventListener('keydown', handleTab);
        }
    }, [isOpen]);
    const handleBackdropClick = useCallback(() => {
        if (closeOnBackdropClick) {
            onClose();
        }
    }, [closeOnBackdropClick, onClose]);
    const handleApply = useCallback(() => {
        if (onApply) {
            onApply();
        }
        onClose();
    }, [onApply, onClose]);
    const handleClear = useCallback(() => {
        clearRefinements(true);
    }, [clearRefinements]);
    // Get drawer transform based on position
    const getTransform = (isVisible) => {
        if (isVisible)
            return 'translate(0, 0)';
        switch (position) {
            case 'left':
                return 'translateX(-100%)';
            case 'right':
                return 'translateX(100%)';
            case 'bottom':
                return 'translateY(100%)';
            default:
                return 'translateX(100%)';
        }
    };
    // Get drawer styles based on position
    const getDrawerPositionStyles = () => {
        const base = {
            position: 'fixed',
            backgroundColor: theme.colors.background,
            display: 'flex',
            flexDirection: 'column',
            transition: 'transform 300ms ease-in-out',
            transform: getTransform(isOpen),
            zIndex: (theme.zIndex?.modal || 1050) + 1,
        };
        switch (position) {
            case 'left':
                return { ...base, top: 0, left: 0, bottom: 0, width: '80%', maxWidth: '320px' };
            case 'right':
                return { ...base, top: 0, right: 0, bottom: 0, width: '80%', maxWidth: '320px' };
            case 'bottom':
                return { ...base, left: 0, right: 0, bottom: 0, maxHeight: '80vh', borderTopLeftRadius: '16px', borderTopRightRadius: '16px' };
            default:
                return base;
        }
    };
    if (!isOpen)
        return null;
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: mobileFiltersTheme.overlay, onClick: handleBackdropClick, style: {
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.5)',
                zIndex: theme.zIndex?.modal || 1050,
                opacity: isOpen ? 1 : 0,
                transition: 'opacity 300ms ease-in-out',
            }, "aria-hidden": "true" }),
        React.createElement("div", { ref: drawerRef, className: clsx(mobileFiltersTheme.drawer, className), style: getDrawerPositionStyles(), role: "dialog", "aria-modal": "true", "aria-label": title },
            showHeader && (React.createElement("div", { className: mobileFiltersTheme.header, style: {
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: theme.spacing.medium,
                    borderBottom: `1px solid ${theme.colors.border}`,
                } },
                React.createElement("div", { style: { display: 'flex', alignItems: 'center', gap: theme.spacing.small } },
                    React.createElement("h2", { className: mobileFiltersTheme.title, style: {
                            margin: 0,
                            fontSize: theme.typography.fontSize.large,
                            fontWeight: theme.typography.fontWeight?.semibold || 600,
                            color: theme.colors.text,
                        } }, title),
                    showFilterCount && refinements.length > 0 && (React.createElement("span", { className: mobileFiltersTheme.filterCount, style: {
                            display: 'inline-flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            minWidth: '24px',
                            height: '24px',
                            padding: '0 6px',
                            fontSize: theme.typography.fontSize.small,
                            fontWeight: theme.typography.fontWeight?.bold || 700,
                            color: '#ffffff',
                            backgroundColor: theme.colors.primary,
                            borderRadius: '12px',
                        } }, refinements.length))),
                React.createElement("button", { type: "button", onClick: onClose, className: mobileFiltersTheme.closeButton, style: {
                        padding: theme.spacing.small,
                        background: 'none',
                        border: 'none',
                        cursor: 'pointer',
                        fontSize: '1.5rem',
                        color: theme.colors.text,
                    }, "aria-label": "Close filters" }, "\u00D7"))),
            React.createElement("div", { className: mobileFiltersTheme.content, style: {
                    flex: 1,
                    overflow: 'auto',
                    padding: theme.spacing.medium,
                } }, children),
            showFooter && (React.createElement("div", { className: mobileFiltersTheme.footer, style: {
                    display: 'flex',
                    gap: theme.spacing.small,
                    padding: theme.spacing.medium,
                    borderTop: `1px solid ${theme.colors.border}`,
                } },
                React.createElement("button", { type: "button", onClick: handleClear, className: mobileFiltersTheme.clearButton, style: {
                        flex: 1,
                        padding: theme.spacing.medium,
                        fontSize: theme.typography.fontSize.medium,
                        fontWeight: theme.typography.fontWeight?.medium || 500,
                        color: theme.colors.text,
                        backgroundColor: 'transparent',
                        border: `1px solid ${theme.colors.border}`,
                        borderRadius: typeof theme.borderRadius === 'string'
                            ? theme.borderRadius
                            : theme.borderRadius.medium,
                        cursor: 'pointer',
                    } }, clearButtonText),
                React.createElement("button", { type: "button", onClick: handleApply, className: mobileFiltersTheme.applyButton, style: {
                        flex: 2,
                        padding: theme.spacing.medium,
                        fontSize: theme.typography.fontSize.medium,
                        fontWeight: theme.typography.fontWeight?.medium || 500,
                        color: '#ffffff',
                        backgroundColor: theme.colors.primary,
                        border: 'none',
                        borderRadius: typeof theme.borderRadius === 'string'
                            ? theme.borderRadius
                            : theme.borderRadius.medium,
                        cursor: 'pointer',
                    } },
                    applyButtonText,
                    showFilterCount && refinements.length > 0 && ` (${refinements.length})`))))));
};
export const MobileFiltersButton = ({ onClick, text = 'Filters', showCount = true, className, style, }) => {
    const { theme } = useSearchContext();
    const { refinements } = useSearchState();
    return (React.createElement("button", { type: "button", onClick: onClick, className: className, style: {
            display: 'inline-flex',
            alignItems: 'center',
            gap: theme.spacing.small,
            padding: `${theme.spacing.small} ${theme.spacing.medium}`,
            fontSize: theme.typography.fontSize.medium,
            fontWeight: theme.typography.fontWeight?.medium || 500,
            color: theme.colors.text,
            backgroundColor: theme.colors.background,
            border: `1px solid ${theme.colors.border}`,
            borderRadius: typeof theme.borderRadius === 'string'
                ? theme.borderRadius
                : theme.borderRadius.medium,
            cursor: 'pointer',
            ...style,
        } },
        React.createElement("span", null, "\u2630"),
        React.createElement("span", null, text),
        showCount && refinements.length > 0 && (React.createElement("span", { style: {
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                minWidth: '20px',
                height: '20px',
                padding: '0 4px',
                fontSize: theme.typography.fontSize.small,
                fontWeight: theme.typography.fontWeight?.bold || 700,
                color: '#ffffff',
                backgroundColor: theme.colors.primary,
                borderRadius: '10px',
            } }, refinements.length))));
};
