import { jsx } from 'react/jsx-runtime';
import React__default, { useRef, useCallback, useEffect } from 'react';
import { useReducedMotion, motion, AnimatePresence } from 'motion/react';
import { cn } from '../../../utils/cn.js';
import { ScrollArea } from '../ScrollArea/ScrollArea.js';
import '../ScrollArea/smooth/SmoothScrollEngine.js';
import { messageListTheme } from './MessageList.theme.js';
import { getMessageItemVariants } from './MessageList.animations.js';

const MessageList = React__default.forwardRef(({ children, autoScroll = true, scrollThreshold = 100, shouldAnimate = true, className, theme: customTheme, ...props }, ref) => {
    var _a, _b;
    const shouldReduceMotion = useReducedMotion();
    const itemVariants = getMessageItemVariants(shouldReduceMotion, shouldAnimate);
    const scrollAreaRef = useRef(null);
    const userHasScrolledRef = useRef(false);
    const childCountRef = useRef(0);
    const scrollToBottom = useCallback(() => {
        const el = scrollAreaRef.current;
        if (!el)
            return;
        el.scrollTop = el.scrollHeight;
    }, []);
    const handleScroll = useCallback(() => {
        const el = scrollAreaRef.current;
        if (!el)
            return;
        const { scrollTop, scrollHeight, clientHeight } = el;
        const isAtBottom = scrollHeight - scrollTop - clientHeight < scrollThreshold;
        userHasScrolledRef.current = !isAtBottom;
    }, [scrollThreshold]);
    const childCount = React__default.Children.count(children);
    // Auto-scroll when new children are added
    useEffect(() => {
        if (!autoScroll)
            return;
        if (childCount > childCountRef.current && !userHasScrolledRef.current) {
            // rAF ensures AnimatePresence has mounted the new child before measuring
            requestAnimationFrame(scrollToBottom);
        }
        childCountRef.current = childCount;
    }, [childCount, autoScroll, scrollToBottom]);
    // Scroll to bottom on initial mount
    useEffect(() => {
        scrollToBottom();
    }, [scrollToBottom]);
    // Dev warning for missing keys
    if (process.env.NODE_ENV !== 'production') {
        React__default.Children.forEach(children, (child) => {
            if (React__default.isValidElement(child) && child.key === null) {
                console.warn('[Message.List]: Each child must have a stable key prop for animations to work correctly.');
            }
        });
    }
    const baseStyle = (_a = customTheme === null || customTheme === void 0 ? void 0 : customTheme.baseStyle) !== null && _a !== void 0 ? _a : messageListTheme.baseStyle;
    const innerStyle = (_b = customTheme === null || customTheme === void 0 ? void 0 : customTheme.innerStyle) !== null && _b !== void 0 ? _b : messageListTheme.innerStyle;
    const wrappedChildren = React__default.Children.map(children, (child) => {
        if (!React__default.isValidElement(child))
            return child;
        if (itemVariants) {
            return (jsx(motion.div, { layout: true, variants: itemVariants, initial: "initial", animate: "animate", exit: "exit", children: child }, child.key));
        }
        return jsx("div", { children: child }, child.key);
    });
    // Merge internal ref with forwarded ref
    const setRefs = useCallback((node) => {
        scrollAreaRef.current = node;
        if (typeof ref === 'function') {
            ref(node);
        }
        else if (ref) {
            ref.current = node;
        }
    }, [ref]);
    return (jsx(ScrollArea, { ref: setRefs, type: "hover", orientation: "vertical", className: cn(baseStyle, className), onScroll: handleScroll, role: "log", "aria-live": "polite", ...props, children: jsx("div", { className: innerStyle, children: jsx(AnimatePresence, { mode: "popLayout", initial: false, children: wrappedChildren }) }) }));
});
MessageList.displayName = 'Message.List';

export { MessageList };
