import { jsxs, jsx } from 'react/jsx-runtime';
import React__default, { useState, useRef, useEffect, useCallback } from 'react';
import { cn } from '../../../utils/cn.js';
import { avatarTheme } from './Avatar.theme.js';
import { Tooltip } from '../Tooltip/Tooltip.js';
import '../Tooltip/Tooltip.animations.js';
import { UserIcon } from '@heroicons/react/24/solid';

const Avatar = React__default.forwardRef(({ src, name, size = "md", status = "none", fallback, className, role, lazyLoad = true, retryCount = 0, retryDelay = 1000, contextualLabel, groupPosition, showTooltip = false, initialsCount = 2, title, subtitle, ...props }, ref) => {
    const [imageError, setImageError] = useState(false);
    const [retries, setRetries] = useState(0);
    const retryTimerRef = useRef(null);
    // Normalize null to undefined for internal use
    const resolvedName = name !== null && name !== void 0 ? name : undefined;
    // Clear timeout on unmount to prevent memory leaks
    useEffect(() => {
        return () => {
            if (retryTimerRef.current) {
                clearTimeout(retryTimerRef.current);
            }
        };
    }, []);
    // Handle image loading errors with retry functionality
    const handleImageError = useCallback(() => {
        if (retries < retryCount) {
            // Log error and retry
            if (process.env.NODE_ENV !== "production") {
                // eslint-disable-next-line no-console
                console.warn(`Avatar image load failed, retrying (${retries + 1}/${retryCount})...`);
            }
            // Set up retry with delay
            retryTimerRef.current = setTimeout(() => {
                setRetries((prev) => prev + 1);
                setImageError(false); // Reset error state to trigger re-render and retry
            }, retryDelay);
        }
        else {
            // Max retries reached, show fallback
            if (process.env.NODE_ENV !== "production") {
                // eslint-disable-next-line no-console
                console.warn("Avatar image load failed after maximum retries");
            }
            setImageError(true);
        }
    }, [retries, retryCount, retryDelay]);
    // Handle fallback content
    const getFallbackContent = () => {
        // 1. Explicit fallback always wins
        if (fallback) {
            return fallback;
        }
        // 2. Generate initials from name
        if (resolvedName) {
            const maxInitials = size === "xs" ? 1 : initialsCount;
            const initials = resolvedName
                .split(" ")
                .map((part) => part[0])
                .slice(0, maxInitials)
                .join("")
                .toUpperCase();
            return jsx("span", { "aria-hidden": "true", children: initials });
        }
        // 3. Default placeholder icon
        return jsx(UserIcon, { className: "w-1/2 h-1/2" });
    };
    // Determine status indicator size based on avatar size
    const getStatusSize = () => {
        switch (size) {
            case "xs":
                return "size-1.5 left-0 bottom-0.5";
            case "sm":
                return "size-2 left-0 bottom-0";
            case "md":
                return "size-2 left-0 bottom-0";
            case "lg":
                return "size-2.5 left-0 bottom-0";
            case "xl":
                return "size-3 left-0 bottom-0";
            default:
                return "size-2 left-0 bottom-0";
        }
    };
    // Create full accessibility label including context if provided
    const accessibilityLabel = contextualLabel
        ? `${resolvedName !== null && resolvedName !== void 0 ? resolvedName : "Avatar"}${contextualLabel}`
        : (resolvedName !== null && resolvedName !== void 0 ? resolvedName : "Avatar");
    // Determine appropriate ARIA role
    const ariaRole = role || (src ? undefined : "img");
    const resolvedTitle = title !== null && title !== void 0 ? title : (subtitle ? resolvedName : undefined);
    const hasTextSection = !!(resolvedTitle || subtitle);
    // The avatar circle with status indicator
    const avatarCircle = (jsxs("div", { className: cn("relative inline-flex avatar-wrapper shrink-0", groupPosition), children: [jsx("div", { className: cn(avatarTheme.baseStyle, avatarTheme.sizes[size], className), "aria-hidden": ariaRole === "presentation" ? "true" : undefined, "data-size": size, children: src && !imageError ? (jsx("img", { src: src, alt: resolvedName !== null && resolvedName !== void 0 ? resolvedName : "Avatar", className: "size-full object-cover object-top", onError: handleImageError, loading: lazyLoad ? "lazy" : undefined, "aria-hidden": ariaRole === "presentation" ? "true" : undefined, "data-loaded": "true" })) : (jsx("div", { className: "avatar-fallback flex items-center justify-center size-full", children: getFallbackContent() })) }), status !== "none" && (jsx("span", { className: cn("absolute rounded-full ring-2 ring-[var(--color-background)]", getStatusSize(), avatarTheme.statuses[status]), "aria-label": `Status: ${status}`, role: "status", "data-status": status }))] }));
    // Wrap circle in tooltip if needed
    const avatarWithTooltip = showTooltip && resolvedName ? (jsx(Tooltip, { content: resolvedName, placement: "top", children: avatarCircle })) : (avatarCircle);
    // If no text section, render just the avatar
    if (!hasTextSection) {
        return (jsx("div", { ref: ref, role: ariaRole === "presentation" ? "presentation" : undefined, "aria-label": ariaRole === "presentation" ? undefined : accessibilityLabel, "data-size": size, "data-status": status, "data-error": imageError ? "true" : "false", ...props, children: avatarWithTooltip }));
    }
    // Render avatar with text section
    return (jsxs("div", { ref: ref, className: cn("inline-flex items-center", avatarTheme.gapSizes[size]), role: ariaRole === "presentation" ? "presentation" : undefined, "aria-label": ariaRole === "presentation" ? undefined : accessibilityLabel, "data-size": size, "data-status": status, "data-error": imageError ? "true" : "false", ...props, children: [avatarWithTooltip, jsxs("div", { className: "min-w-0", children: [resolvedTitle && (jsx("div", { className: cn(avatarTheme.titleStyle, avatarTheme.textSizes[size]), children: resolvedTitle })), subtitle && (jsx("div", { className: cn(avatarTheme.subtitleStyle, avatarTheme.textSizes[size]), children: subtitle }))] })] }));
});
// Set display name for dev tools and Storybook
Avatar.displayName = "Avatar";

export { Avatar };
