import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import React__default, { useId, useState, useCallback, useMemo } from 'react';
import { cn } from '../../../utils/cn.js';
import { navItemTheme } from './NavItem.theme.js';
import { useSidebarContext, useAccordionNavContext } from '../Sidebar/SidebarContext.js';
import { Tooltip } from '../Tooltip/Tooltip.js';
import '../Tooltip/Tooltip.animations.js';
import { Badge } from '../Badge/Badge.js';
import { ChevronDownIcon } from '@heroicons/react/20/solid';
import { AnimatePresence, motion } from 'motion/react';

const NavItem = React__default.forwardRef(({ children, startContent: propStartContent, endContent: propEndContent, icon, // Legacy
badge, // Legacy
notification, description, shortcut, href, onClick, active = false, disabled = false, isDisabled: propIsDisabled, isDanger = false, hasSubmenu: propHasSubmenu = false, expanded: controlledExpanded, onToggleExpanded, items, defaultExpanded = false, level = 0, showTooltipWhenCollapsed = true, className, theme: customTheme = {}, ...props }, ref) => {
    var _a, _b;
    const sidebarContext = useSidebarContext();
    const accordionNav = useAccordionNavContext();
    const stableId = useId();
    const collapsed = (sidebarContext === null || sidebarContext === void 0 ? void 0 : sidebarContext.collapsed) || false;
    const isInSidebar = !!sidebarContext;
    const isMobile = (sidebarContext === null || sidebarContext === void 0 ? void 0 : sidebarContext.isMobile) || false;
    // Self-managed submenu state
    const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);
    // Determine if this item has a submenu
    const hasSubmenu = propHasSubmenu || (items && items.length > 0);
    // Determine expanded state: controlled vs accordion vs internal
    const isAccordionManaged = !!accordionNav;
    const isControlled = controlledExpanded !== undefined;
    let isExpanded;
    if (isControlled) {
        isExpanded = controlledExpanded;
    }
    else if (isAccordionManaged && hasSubmenu) {
        isExpanded = accordionNav.openId === stableId;
    }
    else {
        isExpanded = internalExpanded;
    }
    const handleToggleExpanded = useCallback(() => {
        if (isControlled) {
            onToggleExpanded === null || onToggleExpanded === void 0 ? void 0 : onToggleExpanded();
        }
        else if (isAccordionManaged) {
            if (isExpanded) {
                accordionNav.unregister(stableId);
            }
            else {
                accordionNav.register(stableId);
            }
        }
        else {
            setInternalExpanded(prev => !prev);
        }
    }, [isControlled, isAccordionManaged, isExpanded, onToggleExpanded, accordionNav, stableId]);
    // Map legacy props
    const startContent = propStartContent || icon;
    const actualIsDisabled = propIsDisabled || disabled;
    // Build end content
    let endContent = propEndContent;
    if (!endContent && badge) {
        endContent = (jsx(Badge, { color: "neutral", variant: "soft", size: "sm", children: badge }));
    }
    // Notification element
    const notificationElement = useMemo(() => {
        if (notification === undefined || notification === false)
            return null;
        if (notification === true) {
            return (jsx("span", { className: cn(navItemTheme.notificationDot, customTheme.notificationDot) }));
        }
        if (typeof notification === "number" && notification > 0) {
            return (jsx("span", { className: cn(navItemTheme.notificationBadge, customTheme.notificationBadge), children: notification > 99 ? "99+" : notification }));
        }
        return null;
    }, [notification, customTheme.notificationDot, customTheme.notificationBadge]);
    const theme = useMemo(() => ({
        ...navItemTheme,
        ...customTheme,
        states: { ...navItemTheme.states, ...customTheme.states },
        iconStates: { ...navItemTheme.iconStates, ...customTheme.iconStates },
        levels: { ...navItemTheme.levels, ...customTheme.levels },
        collapsed: { ...navItemTheme.collapsed, ...customTheme.collapsed },
        danger: customTheme.danger || navItemTheme.danger || "text-[var(--color-danger)] hover:bg-[var(--color-danger-50)]",
    }), [customTheme]);
    // Handle click events
    const handleClick = (e) => {
        if (actualIsDisabled) {
            e.preventDefault();
            return;
        }
        if (hasSubmenu) {
            e.preventDefault();
            handleToggleExpanded();
            return;
        }
        if (onClick) {
            e.preventDefault();
            onClick();
            // Close mobile sidebar after clicking a nav item
            if (isMobile && sidebarContext) {
                sidebarContext.setMobileOpen(false);
            }
            return;
        }
        // Close mobile sidebar after navigation
        if (href && isMobile && sidebarContext) {
            sidebarContext.setMobileOpen(false);
        }
    };
    const isActive = active;
    const isCollapsedView = isInSidebar && collapsed && !isMobile;
    // Get state classes
    const getStateClasses = () => {
        if (actualIsDisabled)
            return theme.states.disabled;
        if (isActive)
            return theme.states.active;
        return theme.states.default;
    };
    // Danger overrides
    const dangerClasses = isDanger ? theme.danger : "";
    // Active indicator
    const activeIndicatorClasses = isActive && level === 0 ? theme.activeIndicator : "";
    // Build container classes
    const containerClasses = cn(theme.baseStyle, getStateClasses(), theme.levels[level], isCollapsedView && ((_a = theme.collapsed) === null || _a === void 0 ? void 0 : _a.container), dangerClasses, activeIndicatorClasses, className);
    // Get icon state classes
    const getIconStateClasses = () => {
        var _a, _b, _c;
        if (actualIsDisabled)
            return (_a = theme.iconStates) === null || _a === void 0 ? void 0 : _a.disabled;
        if (isActive)
            return (_b = theme.iconStates) === null || _b === void 0 ? void 0 : _b.active;
        return (_c = theme.iconStates) === null || _c === void 0 ? void 0 : _c.default;
    };
    // Build icon classes
    const iconClasses = cn(isCollapsedView ? (_b = theme.collapsed) === null || _b === void 0 ? void 0 : _b.icon : theme.icon, getIconStateClasses());
    const textClasses = cn(theme.text);
    // Chevron for submenu
    const chevron = hasSubmenu && !isCollapsedView ? (jsx(ChevronDownIcon, { className: cn("size-4 transition-transform duration-200 text-[var(--color-text-muted)]", isExpanded && "rotate-180") })) : null;
    // Content component
    const content = (jsxs("div", { ref: ref, className: containerClasses, role: href ? "link" : "button", tabIndex: actualIsDisabled ? -1 : 0, "aria-disabled": actualIsDisabled, "aria-expanded": hasSubmenu ? isExpanded : undefined, "data-active": isActive, "data-disabled": actualIsDisabled, "data-level": level, onClick: handleClick, onKeyDown: (e) => {
            if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                handleClick(e);
            }
        }, ...props, children: [startContent && (jsxs("div", { className: "flex items-center justify-center flex-shrink-0 relative", children: [React__default.isValidElement(startContent)
                        ? React__default.cloneElement(startContent, {
                            className: cn(iconClasses, startContent.props.className),
                        })
                        : startContent, isCollapsedView && notificationElement && (jsx("span", { className: "absolute -top-1 -right-1", children: notificationElement }))] })), !isCollapsedView && (jsxs("div", { className: "flex-1 min-w-0", children: [jsxs("div", { className: "flex items-center justify-between gap-2", children: [jsx("span", { className: cn("truncate", textClasses), children: children }), shortcut && (jsx("kbd", { className: "hidden group-hover:inline-block text-sm text-[var(--color-text-muted)] font-sans border border-[var(--color-border)] rounded px-1.5 py-0.5", children: shortcut }))] }), description && (jsx("div", { className: "text-sm text-[var(--color-text-muted)] mt-0.5 truncate", children: description }))] })), !isCollapsedView && (jsxs("div", { className: "flex items-center gap-1.5 flex-shrink-0", children: [notificationElement, endContent, chevron] })), isCollapsedView && (jsx("span", { className: "sr-only", children: children }))] }));
    // Self-contained submenu
    const submenu = hasSubmenu && items && items.length > 0 && !isCollapsedView ? (jsx(AnimatePresence, { initial: false, children: isExpanded && (jsx(motion.div, { initial: "collapsed", animate: "open", exit: "collapsed", variants: {
                open: { opacity: 1, height: "auto" },
                collapsed: { opacity: 0, height: 0 },
            }, transition: { duration: 0.2, ease: "easeInOut" }, className: "overflow-hidden", children: items.map((item, idx) => (jsx(NavItem, { level: Math.min((level + 1), 2), startContent: item.startContent, active: item.active, isDisabled: item.isDisabled, badge: item.badge, notification: item.notification, href: item.href, onClick: item.onClick, children: item.children }, idx))) })) })) : null;
    // Wrap with link if href is provided
    const renderWrapped = (node) => {
        if (href && !actualIsDisabled) {
            return (jsx("a", { href: href, className: "block group", children: node }));
        }
        return node;
    };
    // Show tooltip in collapsed sidebar mode
    const renderWithTooltip = (node) => {
        if (isCollapsedView && showTooltipWhenCollapsed) {
            return (jsx(Tooltip, { content: children, placement: "right", children: node }));
        }
        return node;
    };
    return (jsxs(Fragment, { children: [renderWithTooltip(renderWrapped(content)), submenu] }));
});
NavItem.displayName = "NavItem";

export { NavItem };
