import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useRef, useCallback, useEffect } from 'react';
import { useReducedMotion, AnimatePresence, motion } from 'motion/react';
import { createPortal } from 'react-dom';
import { cn } from '../../../utils/cn.js';
import { tooltipTheme } from './Tooltip.theme.js';
import { getTooltipVariants } from './Tooltip.animations.js';
import { useSelectPortal } from '../../../hooks/useSelectPortal.js';
import { useIsClient } from '../../../hooks/useIsClient.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();
        // Observe class changes on html and body
        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;
};
const Tooltip = ({ content, children, placement = "top", delay = 300, disabled = false, className, maxWidth = "360px", minWidth = "fit-content", showOnFocus = true, wrapText = false, id, theme: themeOverrides, "aria-label": ariaLabel, role = "tooltip", offset = 8, darkMode = false, }) => {
    const [isVisible, setIsVisible] = useState(false);
    const tooltipRef = useRef(null);
    const triggerRef = useRef(null);
    const timerRef = useRef(null);
    const shouldReduceMotion = useReducedMotion();
    // Detect dark mode for portal content
    const isDarkMode = useDarkMode();
    const isClient = useIsClient();
    // Merge global theme with component-specific overrides
    const theme = {
        ...tooltipTheme,
        ...(themeOverrides || {}),
    };
    // Use the same positioning hook as Popover/Select for consistent behavior
    const { position, cssVariables, contentRef: portalContentRef} = useSelectPortal({
        triggerRef,
        isOpen: isVisible,
        placement: placement,
        offset,
        autoWidth: true,
    });
    // Event handlers - simplified timer management
    const handleShowTooltip = useCallback(() => {
        if (disabled)
            return;
        if (timerRef.current) {
            clearTimeout(timerRef.current);
        }
        timerRef.current = setTimeout(() => {
            setIsVisible(true);
        }, delay);
    }, [disabled, delay]);
    const handleHideTooltip = useCallback(() => {
        if (timerRef.current) {
            clearTimeout(timerRef.current);
        }
        // Immediate hide for better responsiveness
        setIsVisible(false);
    }, []);
    // Clean up timeout on unmount
    useEffect(() => {
        return () => {
            if (timerRef.current) {
                clearTimeout(timerRef.current);
            }
        };
    }, []);
    // Keyboard handler
    const handleKeyDown = useCallback((e) => {
        if (e.key === "Escape") {
            handleHideTooltip();
        }
    }, [handleHideTooltip]);
    // Event handlers for trigger element
    const triggerHandlers = {
        onMouseEnter: handleShowTooltip,
        onMouseLeave: handleHideTooltip,
        ...(showOnFocus && {
            onFocus: handleShowTooltip,
            onBlur: handleHideTooltip,
        }),
        onKeyDown: handleKeyDown,
    };
    // Combine refs for portal positioning
    const handleRef = useCallback((el) => {
        tooltipRef.current = el;
        if (portalContentRef &&
            typeof portalContentRef === "object" &&
            "current" in portalContentRef) {
            portalContentRef.current = el;
        }
    }, [portalContentRef]);
    // Computed values
    const textOverflowClass = wrapText
        ? ""
        : "text-ellipsis overflow-hidden whitespace-nowrap";
    const widthClasses = cn(minWidth === "fit-content" ? "w-fit" : "min-w-fit", textOverflowClass);
    const tooltipContent = (jsx(AnimatePresence, { children: isVisible && (jsx(motion.div, { id: id, role: role, ref: handleRef, style: {
                maxWidth,
                minWidth: minWidth !== "fit-content" ? minWidth : undefined,
                width: "max-content",
                ...cssVariables,
                top: `${position.top}px`,
                left: `${position.left}px`,
            }, className: cn(theme.baseStyle, widthClasses, className), "aria-hidden": !isVisible, "aria-label": ariaLabel, "aria-live": role === "tooltip" ? "polite" : undefined, variants: shouldReduceMotion ? {} : getTooltipVariants(placement), initial: shouldReduceMotion ? undefined : "initial", animate: shouldReduceMotion ? undefined : "animate", exit: shouldReduceMotion ? undefined : "exit", children: content })) }));
    return (jsxs("div", { className: "relative inline-block", ref: triggerRef, ...triggerHandlers, tabIndex: showOnFocus ? 0 : undefined, "aria-describedby": isVisible && id ? id : undefined, children: [children, isClient &&
                createPortal(jsx("div", { className: darkMode || isDarkMode ? "dark" : undefined, children: tooltipContent }), document.body)] }));
};
// Set display name for dev tools and Storybook
Tooltip.displayName = "Tooltip";

export { Tooltip };
