import { jsx } from 'react/jsx-runtime';
import React__default, { useRef, useMemo, useImperativeHandle, useState, useEffect } from 'react';
import { cn } from '../../../utils/cn.js';
import { scrollAreaTheme } from './ScrollArea.theme.js';
import { useSmoothScroll } from './smooth/useSmoothScroll.js';

/**
 * ScrollArea provides a custom scrollable container with styled scrollbars.
 * Supports vertical, horizontal, or both scroll directions with configurable
 * scrollbar visibility behavior.
 *
 * Enhanced with optional smooth momentum-based scrolling via the `smooth` prop.
 *
 * @example
 * ```tsx
 * <ScrollArea className="h-72">
 *   <div className="p-4">
 *     {items.map(item => <div key={item.id}>{item.name}</div>)}
 *   </div>
 * </ScrollArea>
 *
 * // With smooth scrolling
 * <ScrollArea smooth smoothConfig={{ lerp: 0.1, elasticEdges: true }}>
 *   {content}
 * </ScrollArea>
 * ```
 */
const ScrollArea = React__default.forwardRef(({ children, type = 'hover', size = 'default', orientation = 'vertical', snap, snapAlign = 'start', smooth = false, smoothConfig, onScrollProgress, onPerformanceUpdate, className, theme, ...props }, ref) => {
    // Internal ref for the scrollable element
    const internalRef = useRef(null);
    // Determine scroll orientation for smooth scroll
    // Note: 'both' defaults to 'vertical' for smooth scroll engine
    const smoothOrientation = orientation === 'horizontal' ? 'horizontal' : 'vertical';
    // Initialize smooth scroll hook if enabled
    const smoothScrollConfig = useMemo(() => {
        var _a;
        if (!smooth)
            return undefined;
        return {
            ...smoothConfig,
            // Automatically respect snap points if snap is enabled
            respectSnapPoints: snap ? true : (_a = smoothConfig === null || smoothConfig === void 0 ? void 0 : smoothConfig.respectSnapPoints) !== null && _a !== void 0 ? _a : true,
            onScroll: onScrollProgress,
            ...(onPerformanceUpdate && {
            // Performance callback needs to be added to config if provided
            // This will be handled by the engine's performance monitor
            }),
        };
    }, [smooth, smoothConfig, snap, onScrollProgress, onPerformanceUpdate]);
    const smoothAPI = useSmoothScroll(smooth ? internalRef : null, smoothScrollConfig, smoothOrientation);
    // Expose extended API via ref
    useImperativeHandle(ref, () => {
        if (!internalRef.current)
            return null;
        const element = internalRef.current;
        // Create extended ref object
        const extendedRef = element;
        // Add smooth scroll methods if smooth is enabled
        if (smooth && smoothAPI) {
            extendedRef.smoothScrollTo = smoothAPI.scrollTo;
            extendedRef.getScrollVelocity = smoothAPI.getVelocity;
            extendedRef.pauseSmoothScroll = smoothAPI.stop;
            extendedRef.resumeSmoothScroll = smoothAPI.start;
            extendedRef.refreshSnapPoints = smoothAPI.refreshSnapPoints;
        }
        return extendedRef;
    }, [smooth, smoothAPI]);
    // Scroll-detection state for type='scroll' (overlay scrollbar)
    const [isScrolling, setIsScrolling] = useState(false);
    const scrollTimerRef = useRef(undefined);
    useEffect(() => {
        if (type !== 'scroll')
            return;
        const el = internalRef.current;
        if (!el)
            return;
        const onScroll = () => {
            setIsScrolling(true);
            clearTimeout(scrollTimerRef.current);
            scrollTimerRef.current = setTimeout(() => setIsScrolling(false), 1000);
        };
        el.addEventListener('scroll', onScroll, { passive: true });
        return () => {
            el.removeEventListener('scroll', onScroll);
            clearTimeout(scrollTimerRef.current);
        };
    }, [type]);
    // Resolve theme with overrides
    const resolvedTheme = useMemo(() => {
        var _a, _b, _c;
        return ({
            baseStyle: (_a = theme === null || theme === void 0 ? void 0 : theme.baseStyle) !== null && _a !== void 0 ? _a : scrollAreaTheme.baseStyle,
            scrollbarStyle: (_b = theme === null || theme === void 0 ? void 0 : theme.scrollbarStyle) !== null && _b !== void 0 ? _b : scrollAreaTheme.scrollbarStyle,
            thumbStyle: (_c = theme === null || theme === void 0 ? void 0 : theme.thumbStyle) !== null && _c !== void 0 ? _c : scrollAreaTheme.thumbStyle,
        });
    }, [theme]);
    // Determine overflow classes based on orientation
    // For type='scroll', use overflow:overlay so scrollbar overlays content
    const overflowClasses = useMemo(() => {
        if (type === 'scroll') {
            switch (orientation) {
                case 'horizontal':
                    return 'overflow-x-[overlay] overflow-y-hidden';
                case 'both':
                    return 'overflow-x-[overlay] overflow-y-[overlay]';
                case 'vertical':
                default:
                    return 'overflow-y-[overlay] overflow-x-hidden';
            }
        }
        switch (orientation) {
            case 'horizontal':
                return 'overflow-x-auto overflow-y-hidden';
            case 'both':
                return 'overflow-x-auto overflow-y-auto';
            case 'vertical':
            default:
                return 'overflow-y-auto overflow-x-hidden';
        }
    }, [orientation, type]);
    // Scroll snap classes
    // When snap is enabled for horizontal/both, the viewport becomes a flex container
    // so that items are direct children of the scrollable element (required for snap-align).
    const snapClasses = useMemo(() => {
        if (!snap)
            return '';
        const axisClass = orientation === 'horizontal'
            ? 'snap-x'
            : orientation === 'both'
                ? 'snap-both'
                : 'snap-y';
        const strictnessClass = snap === 'proximity' ? 'snap-proximity' : 'snap-mandatory';
        const alignClass = snapAlign === 'center'
            ? '[&>*]:snap-center'
            : snapAlign === 'end'
                ? '[&>*]:snap-end'
                : '[&>*]:snap-start';
        const layoutClass = orientation === 'horizontal' || orientation === 'both' ? 'flex' : '';
        return `${axisClass} ${strictnessClass} ${alignClass} ${layoutClass}`;
    }, [snap, orientation, snapAlign]);
    // Base scrollbar styling classes (shared across all types)
    const scrollbarDimension = size === 'thin'
        ? '[&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar]:h-1'
        : '[&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar]:h-2';
    const scrollbarBase = [
        scrollbarDimension,
        '[&::-webkit-scrollbar-track]:bg-transparent',
        '[&::-webkit-scrollbar-thumb]:rounded-full',
        '[&::-webkit-scrollbar-corner]:bg-transparent',
    ].join(' ');
    // Scrollbar visibility classes based on type prop
    const scrollbarVisibility = useMemo(() => {
        switch (type) {
            case 'always':
                return [
                    '[&::-webkit-scrollbar-thumb]:bg-[var(--color-border)]',
                    '[&::-webkit-scrollbar-track]:bg-[var(--color-background-secondary)]',
                ].join(' ');
            case 'scroll':
                return [
                    '[&::-webkit-scrollbar-thumb]:bg-transparent',
                    '[&[data-scrolling]::-webkit-scrollbar-thumb]:bg-black/30',
                    '[&::-webkit-scrollbar-thumb]:transition-colors',
                    '[&::-webkit-scrollbar-thumb]:duration-300',
                ].join(' ');
            case 'hover':
                return [
                    '[&::-webkit-scrollbar-thumb]:bg-transparent',
                    '[&:hover::-webkit-scrollbar-thumb]:bg-[var(--color-border)]',
                ].join(' ');
            case 'none':
                return [
                    '[&::-webkit-scrollbar]:!hidden',
                    '[scrollbar-width:none]',
                ].join(' ');
            case 'auto':
            default:
                return [
                    '[&::-webkit-scrollbar-thumb]:bg-[var(--color-border)]',
                ].join(' ');
        }
    }, [type]);
    return (jsx("div", { ref: internalRef, className: cn(resolvedTheme.baseStyle, overflowClasses, snapClasses, scrollbarBase, scrollbarVisibility, className), "data-orientation": orientation, "data-type": type, "data-smooth": smooth, "data-scrolling": isScrolling || undefined, ...props, children: children }));
});
ScrollArea.displayName = 'ScrollArea';

export { ScrollArea };
