import { jsx } from 'react/jsx-runtime';
import React__default, { useMemo, useCallback, useEffect } from 'react';
import { useReducedMotion, motion } from 'motion/react';
import { cn } from '../../../utils/cn.js';
import { tabsTheme } from './Tabs.theme.js';
import { useTabsContext } from './TabsContext.js';
import { getTabsTriggerVariants } from './Tabs.animations.js';

/**
 * TabsTrigger component displays individual tab headers with optional animations
 */
const TabsTrigger = React__default.forwardRef(({ value, disabled = false, children, className, onClick, onKeyDown, ...props }, ref) => {
    const { value: selectedValue, onValueChange, orientation, size, disabled: contextDisabled, registerTrigger, unregisterTrigger } = useTabsContext();
    const shouldReduceMotion = useReducedMotion();
    // Check if we're in Storybook and should disable animations
    const isInStorybook = typeof window !== 'undefined' && window.__STORYBOOK_DISABLE_ANIMATIONS__;
    const shouldDisableAnimations = !!shouldReduceMotion || !!isInStorybook;
    // Memoize derived state flags for performance
    const derivedState = useMemo(() => ({
        isSelected: value === selectedValue,
        isDisabled: disabled || contextDisabled,
    }), [value, selectedValue, disabled, contextDisabled]);
    const { isSelected, isDisabled } = derivedState;
    // Compute animation variants without a global cache (HMR-safe)
    const triggerVariants = useMemo(() => getTabsTriggerVariants(shouldDisableAnimations), [shouldDisableAnimations]);
    // Dev-time a11y warning for icon-only triggers without aria-label
    if (process.env.NODE_ENV !== 'production') {
        if (typeof children === 'object' && React__default.isValidElement(children) && !props["aria-label"]) {
            // If children is just an icon element, warn about missing aria-label
            const childType = children.type;
            if (typeof childType === 'function' && childType.name && childType.name.includes('Icon')) {
                // eslint-disable-next-line no-console
                console.warn("TabsTrigger with icon-only content should have 'aria-label' for accessibility.");
            }
        }
    }
    // Safe onClick handler with error handling
    const handleClick = useCallback((event) => {
        if (isDisabled)
            return;
        try {
            onValueChange(value);
            onClick === null || onClick === void 0 ? void 0 : onClick(event);
        }
        catch (error) {
            if (process.env.NODE_ENV !== 'production') {
                // eslint-disable-next-line no-console
                console.error("Error in tab trigger click handler:", error);
            }
        }
    }, [isDisabled, onValueChange, value, onClick]);
    // Enhanced keyboard navigation handler with error handling
    const handleKeyDown = useCallback((event) => {
        var _a, _b;
        // Handle keyboard navigation for tabs
        if (!isDisabled) {
            try {
                switch (event.key) {
                    case "ArrowLeft":
                    case "ArrowUp":
                        event.preventDefault();
                        // Move to previous tab - focus previous trigger
                        const prevTrigger = event.currentTarget.previousElementSibling;
                        if (prevTrigger && prevTrigger.tagName === 'BUTTON' && !prevTrigger.disabled) {
                            prevTrigger.focus();
                            prevTrigger.click();
                        }
                        break;
                    case "ArrowRight":
                    case "ArrowDown":
                        event.preventDefault();
                        // Move to next tab - focus next trigger
                        const nextTrigger = event.currentTarget.nextElementSibling;
                        if (nextTrigger && nextTrigger.tagName === 'BUTTON' && !nextTrigger.disabled) {
                            nextTrigger.focus();
                            nextTrigger.click();
                        }
                        break;
                    case "Home":
                        event.preventDefault();
                        // Move to first tab
                        const firstTrigger = (_a = event.currentTarget.parentElement) === null || _a === void 0 ? void 0 : _a.firstElementChild;
                        if (firstTrigger && firstTrigger.tagName === 'BUTTON' && !firstTrigger.disabled) {
                            firstTrigger.focus();
                            firstTrigger.click();
                        }
                        break;
                    case "End":
                        event.preventDefault();
                        // Move to last tab
                        const lastTrigger = (_b = event.currentTarget.parentElement) === null || _b === void 0 ? void 0 : _b.lastElementChild;
                        if (lastTrigger && lastTrigger.tagName === 'BUTTON' && !lastTrigger.disabled) {
                            lastTrigger.focus();
                            lastTrigger.click();
                        }
                        break;
                }
            }
            catch (error) {
                if (process.env.NODE_ENV !== 'production') {
                    // eslint-disable-next-line no-console
                    console.error("Error in tab trigger keyboard handler:", error);
                }
            }
        }
        onKeyDown === null || onKeyDown === void 0 ? void 0 : onKeyDown(event);
    }, [isDisabled, onKeyDown]);
    // Memoize theme classes to prevent recalculation on every render
    const themeClasses = useMemo(() => {
        return {
            triggerStyle: tabsTheme.triggerStyle,
            sizeStyle: tabsTheme.triggerSizes[size],
        };
    }, [size]);
    // Generate default aria-label for icon-only triggers if not provided (fallback only)
    const ariaLabel = props["aria-label"] || undefined;
    // Register/unregister this trigger for underline positioning
    useEffect(() => {
        // Register with a slight delay to ensure DOM is ready
        const timeoutId = setTimeout(() => {
            if (ref && typeof ref === 'object' && ref.current) {
                registerTrigger(value, ref.current);
            }
        }, 0);
        return () => {
            clearTimeout(timeoutId);
            unregisterTrigger(value);
        };
    }, [value, registerTrigger, unregisterTrigger, ref]);
    // Determine animation props (user props will override due to spread order)
    const animationProps = shouldDisableAnimations ? {} : {
        whileHover: !isDisabled ? "hover" : undefined,
        whileTap: !isDisabled ? "tap" : undefined,
        variants: triggerVariants,
    };
    return (jsx(motion.button, { ref: ref, type: "button", role: "tab", "aria-selected": isSelected, "aria-controls": `${value}-content`, id: `${value}-tab`, tabIndex: isSelected ? 0 : -1, disabled: isDisabled, className: cn(themeClasses.triggerStyle, themeClasses.sizeStyle, className // User overrides take precedence
        ), onClick: handleClick, onKeyDown: handleKeyDown, "data-value": value, "data-state": isSelected ? "active" : "inactive", "data-disabled": isDisabled, "data-orientation": orientation, "aria-disabled": isDisabled || undefined, "aria-label": ariaLabel, ...animationProps, ...props, children: children }));
});
TabsTrigger.displayName = "TabsTrigger";

export { TabsTrigger };
