import { jsx, jsxs } from 'react/jsx-runtime';
import { useContext, useCallback, useState, useEffect } from 'react';
import { AnimatePresence, motion } from 'motion/react';
import { createPortal } from 'react-dom';
import { cn } from '../../../utils/cn.js';
import { TimePickerContext } from './TimePicker.js';
import { useSelectPortal } from '../../../hooks/useSelectPortal.js';
import { createDropdownAnimations } from '../Select/Select.animations.js';
import { useIsClient } from '../../../hooks/useIsClient.js';
import { Button } from '../../core/Button/Button.js';

/**
 * Hook to detect dark mode state from document
 */
const useDarkMode = () => {
    const [isDark, setIsDark] = useState(false);
    useEffect(() => {
        if (typeof document === "undefined")
            return;
        const checkDarkMode = () => {
            const hasDarkClass = document.documentElement.classList.contains("dark") ||
                document.body.classList.contains("dark") ||
                document.querySelector(".dark") !== null;
            setIsDark(hasDarkClass);
        };
        checkDarkMode();
        const observer = new MutationObserver(checkDarkMode);
        observer.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ["class"],
        });
        observer.observe(document.body, {
            attributes: true,
            attributeFilter: ["class"],
        });
        return () => observer.disconnect();
    }, []);
    return isDark;
};
/**
 * TimePickerContent Component - contains the time selector dropdown
 * Uses portal positioning like Select and DatePicker components
 *
 * Features:
 * - Title header "Select time"
 * - Wheel column children (passed as children)
 * - Footer with Cancel and Save buttons
 */
const TimePickerContent = ({ isOpen, onCancel, onSave, portal = true, placement = "bottom-start", offset = 4, children, dropdownRef, }) => {
    var _a, _b;
    const context = useContext(TimePickerContext);
    if (!context) {
        throw new Error("TimePickerContent must be used within a TimePicker");
    }
    const { theme, triggerRef, size } = context;
    // Detect dark mode for portal content
    const isDarkMode = useDarkMode();
    const isClient = useIsClient();
    // Use enhanced dropdown positioning hook with direction-aware animations
    // Pass trigger width so dropdown matches trigger size
    const triggerWidth = ((_a = triggerRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect().width) || 0;
    const { position, cssVariables, contentRef, isFlipped } = useSelectPortal({
        triggerRef,
        isOpen,
        placement,
        offset,
        estimatedWidth: triggerWidth,
    });
    // Create direction-aware animations based on actual placement
    const animations = createDropdownAnimations(isFlipped);
    // Combine refs (including dropdownRef for portal-aware click-outside)
    const combinedRef = useCallback((el) => {
        if (contentRef &&
            typeof contentRef === "object" &&
            "current" in contentRef) {
            contentRef.current = el;
        }
        if (dropdownRef &&
            typeof dropdownRef === "object" &&
            "current" in dropdownRef) {
            dropdownRef.current =
                el;
        }
    }, [contentRef, dropdownRef]);
    // Handle keyboard shortcuts
    const handleKeyDown = useCallback((e) => {
        if (e.key === "Escape") {
            e.preventDefault();
            onCancel();
        }
        else if (e.key === "Enter") {
            e.preventDefault();
            onSave();
        }
    }, [onCancel, onSave]);
    const contentElement = (jsx(AnimatePresence, { mode: "wait", children: isOpen && (jsxs(motion.div, { ref: combinedRef, className: cn(theme.dropdownStyle, (_b = theme.dropdownSizes) === null || _b === void 0 ? void 0 : _b[size]), style: {
                ...cssVariables,
                overscrollBehavior: "contain",
                ...(portal
                    ? {
                        top: `${position.top}px`,
                        left: `${position.left}px`,
                        minWidth: `${position.width}px`,
                    }
                    : {}),
            }, variants: animations, initial: "initial", animate: "visible", exit: "exit", onKeyDown: handleKeyDown, role: "dialog", "aria-modal": "true", "aria-label": "Select time", children: [jsx("div", { className: cn(theme.wheelContainerStyle), style: { height: 200 }, children: children }), jsxs("div", { className: cn(theme.footerStyle), children: [jsx(Button, { size: "sm", variant: "outline", color: "neutral", onClick: onCancel, "aria-label": "Cancel time selection", className: "flex-1", children: "Cancel" }), jsx(Button, { size: "sm", onClick: onSave, "aria-label": "Save selected time", className: "flex-1", children: "Save" })] })] })) }));
    // Use portal if enabled and client-side - wrap with dark class for dark mode support
    return portal && isClient
        ? createPortal(jsx("div", { className: isDarkMode ? "dark" : undefined, children: contentElement }), document.body)
        : contentElement;
};

export { TimePickerContent };
