import { jsxs, jsx } from 'react/jsx-runtime';
import React__default, { useCallback, useRef, useState, useEffect, useMemo } from 'react';
import { motion, useReducedMotion } from 'motion/react';
import { cn } from '../../../utils/cn.js';
import { activityRingsTheme } from './ActivityRings.theme.js';
import { ACTIVITY_RINGS_DEFAULTS } from './ActivityRings.types.js';
import { ExclamationTriangleIcon } from '@heroicons/react/20/solid';
import { useTooltipPosition } from '../hooks/useTooltipPosition.js';
import { ChartTooltip } from '../shared/ChartTooltip/ChartTooltip.js';
import { getSpringAnimation, CIRCULAR_CHART_ANIMATIONS, getStaggerDelay } from '../utils/animation-utils.js';

const RingElement = React__default.memo(({ ring, index, radius, center, svgSize, strokeWidth, ringColor, hasAnimated, showAnimation, shouldReduceMotion, animationDelay, handleMouseEnter, handleMouseMove, handleMouseLeave, }) => {
    const circumference = 2 * Math.PI * radius;
    const offset = circumference - (ring.value / 100) * circumference;
    const onMouseEnter = useCallback((e) => {
        const content = {
            category: "",
            series: [
                {
                    key: `ring-${index}`,
                    label: ring.label || `Ring ${index + 1}`,
                    value: ring.value,
                    color: ringColor,
                },
            ],
        };
        const svgCoordinates = {
            x: center,
            y: center - radius,
            dimensions: {
                width: svgSize,
                height: svgSize,
                left: 0,
                top: 0,
            },
        };
        handleMouseEnter(e, content, svgCoordinates);
    }, [index, ring.label, ring.value, ringColor, center, radius, svgSize, handleMouseEnter]);
    const onMouseMove = useCallback((e) => handleMouseMove(e), [handleMouseMove]);
    const onMouseLeave = useCallback(() => handleMouseLeave(), [handleMouseLeave]);
    return (jsxs("g", { children: [jsx("circle", { cx: center, cy: center, r: radius, fill: "none", stroke: "var(--color-chart-track)", strokeWidth: strokeWidth, strokeLinecap: "round", className: "cursor-pointer", transform: `rotate(-90 ${center} ${center})`, onMouseEnter: onMouseEnter, onMouseMove: onMouseMove, onMouseLeave: onMouseLeave }), jsx(motion.circle, { cx: center, cy: center, r: radius, fill: "none", stroke: ringColor, strokeWidth: strokeWidth, strokeLinecap: "round", strokeDasharray: circumference, className: "cursor-pointer transition-opacity duration-200", initial: { strokeDashoffset: circumference }, animate: hasAnimated ? { strokeDashoffset: offset } : {}, transition: showAnimation && !shouldReduceMotion
                    ? getSpringAnimation(CIRCULAR_CHART_ANIMATIONS.activityRings.preset, shouldReduceMotion, animationDelay)
                    : { duration: 0 }, transform: `rotate(-90 ${center} ${center})`, onMouseEnter: onMouseEnter, onMouseMove: onMouseMove, onMouseLeave: onMouseLeave })] }));
});
/**
 * ActivityRings Component
 *
 * Multiple concentric circular progress rings, inspired by Apple Activity.
 * Features smooth animations, accessibility support, and production-ready CSS variables.
 */
const ActivityRings = ({ rings, centerLabel, centerSuffix, size = ACTIVITY_RINGS_DEFAULTS.size, strokeWidth: propStrokeWidth, gap: propGap, showAnimation = ACTIVITY_RINGS_DEFAULTS.showAnimation, colors, theme: themeOverrides, className, title, description, darkMode = false, showValidationWarnings = process.env.NODE_ENV === "development", ...props }) => {
    var _a, _b, _c, _d, _e, _f;
    const theme = { ...activityRingsTheme, ...(themeOverrides || {}) };
    const shouldReduceMotion = useReducedMotion();
    const containerRef = useRef(null);
    // Use theme defaults if not provided
    const strokeWidth = (_b = propStrokeWidth !== null && propStrokeWidth !== void 0 ? propStrokeWidth : (_a = theme.ringDefaults) === null || _a === void 0 ? void 0 : _a.strokeWidth) !== null && _b !== void 0 ? _b : ACTIVITY_RINGS_DEFAULTS.strokeWidth;
    const gap = (_d = propGap !== null && propGap !== void 0 ? propGap : (_c = theme.ringDefaults) === null || _c === void 0 ? void 0 : _c.gap) !== null && _d !== void 0 ? _d : ACTIVITY_RINGS_DEFAULTS.gap;
    // Detect mobile
    const isMobile = typeof window !== "undefined" &&
        ("ontouchstart" in window || navigator.maxTouchPoints > 0);
    // Tooltip hook
    const { tooltipData, tooltipRef, handleMouseEnter, handleMouseMove, handleMouseLeave, } = useTooltipPosition({
        containerRef,
        isMobile,
    });
    // Validation
    if (process.env.NODE_ENV !== "production") {
        if (!Array.isArray(rings) || rings.length === 0) {
            console.error("[ActivityRings]: rings must be a non-empty array");
        }
        if (rings.length > 5) {
            console.warn("[ActivityRings]: More than 5 rings may cause visual overlap. Recommended: 3-5 rings.");
        }
        rings.forEach((ring, i) => {
            if (!Number.isFinite(ring.value)) {
                console.error(`[ActivityRings]: Ring ${i} value must be a finite number. Got: ${ring.value}`);
            }
            if (showValidationWarnings && (ring.value > 100 || ring.value < 0)) {
                console.warn(`[ActivityRings]: Ring ${i} value (${ring.value}) outside 0-100 range. Clamping.`);
            }
        });
    }
    // Early return for invalid configuration
    if (!Array.isArray(rings) || rings.length === 0) {
        return (jsxs("div", { className: cn("flex items-center justify-center p-6 border border-[var(--color-border)] rounded-lg", className), role: "alert", ...props, children: [jsx(ExclamationTriangleIcon, { className: "size-5 text-[var(--color-danger)] mr-2" }), jsx("span", { className: "text-base text-[var(--color-text-secondary)]", children: "Invalid ActivityRings: rings array is required" })] }));
    }
    // State for controlling initial animation
    const [hasAnimated, setHasAnimated] = useState(false);
    useEffect(() => {
        if (showAnimation && !shouldReduceMotion) {
            setHasAnimated(true);
        }
        else {
            // If animations disabled, immediately show final state
            setHasAnimated(true);
        }
    }, [showAnimation, shouldReduceMotion]);
    // Normalize ring values (clamp to 0-100)
    const normalizedRings = useMemo(() => rings.map((ring) => ({
        ...ring,
        value: Math.min(Math.max(ring.value, 0), 100),
    })), [rings]);
    // SVG parameters
    const svgSize = 100;
    const center = 50;
    // Calculate ring radii based on count
    const ringRadii = useMemo(() => {
        normalizedRings.length;
        const maxRadius = center - strokeWidth / 2 - 2; // Leave 2px padding
        return normalizedRings.map((_, index) => {
            // index 0 (outer) = largest radius, index N-1 (inner) = smallest
            return maxRadius - index * (strokeWidth + gap);
        });
    }, [normalizedRings.length, strokeWidth, gap, center]);
    // Get color for a ring by index
    // Priority: ring.color > colors prop > theme colors > fallback
    const getRingColor = (ring, index) => {
        var _a;
        // 1. Individual ring color override (highest priority)
        if (ring.color)
            return ring.color;
        // 2. Component-level colors prop (overrides theme defaults)
        if (colors && colors.length > 0) {
            return colors[index % colors.length];
        }
        // 3. Theme colors
        const themeColors = ((_a = theme.ringDefaults) === null || _a === void 0 ? void 0 : _a.colors) || [];
        if (themeColors.length > 0) {
            return themeColors[index % themeColors.length];
        }
        // 4. Fallback
        return "var(--color-primary)";
    };
    // Container size
    const containerSize = typeof size === "number" ? `${size}px` : size;
    // Calculate average progress for ARIA
    const averageProgress = useMemo(() => {
        const sum = normalizedRings.reduce((acc, ring) => acc + ring.value, 0);
        return Math.round(sum / normalizedRings.length);
    }, [normalizedRings]);
    return (jsxs("div", { ref: containerRef, className: cn(theme.baseStyle, darkMode && "dark", className), style: { width: containerSize, height: containerSize }, role: "progressbar", "aria-valuenow": averageProgress, "aria-valuemin": 0, "aria-valuemax": 100, "aria-label": title ||
            `Activity rings: ${normalizedRings
                .map((r, i) => `${r.label || `Ring ${i + 1}`} ${r.value}%`)
                .join(", ")}`, "aria-describedby": description ? "rings-description" : undefined, tabIndex: 0, ...props, children: [description && (jsx("span", { id: "rings-description", className: "sr-only", children: description })), jsx("svg", { className: cn(theme.svgStyle), viewBox: `0 0 ${svgSize} ${svgSize}`, width: containerSize, height: containerSize, preserveAspectRatio: "xMidYMid meet", role: "presentation", "aria-hidden": "true", children: normalizedRings.map((ring, index) => {
                    const radius = ringRadii[index];
                    const ringColor = getRingColor(ring, index);
                    const animationDelay = getStaggerDelay(index, CIRCULAR_CHART_ANIMATIONS.activityRings.staggerDelay);
                    // Check if radius is valid (prevent negative or zero radius)
                    if (radius <= 0) {
                        if (process.env.NODE_ENV !== "production") {
                            console.warn(`[ActivityRings]: Ring ${index} has invalid radius (${radius}). Too many rings or strokeWidth/gap too large.`);
                        }
                        return null;
                    }
                    return (jsx(RingElement, { ring: ring, index: index, radius: radius, center: center, svgSize: svgSize, strokeWidth: strokeWidth, ringColor: ringColor, hasAnimated: hasAnimated, showAnimation: showAnimation, shouldReduceMotion: shouldReduceMotion, animationDelay: animationDelay, handleMouseEnter: handleMouseEnter, handleMouseMove: handleMouseMove, handleMouseLeave: handleMouseLeave }, index));
                }) }), (centerLabel || centerSuffix) && (jsx(motion.div, { className: "absolute inset-0 flex flex-col items-center justify-center pointer-events-none", initial: { opacity: 0, scale: 0.8 }, animate: hasAnimated ? { opacity: 1, scale: 1 } : {}, transition: showAnimation && !shouldReduceMotion
                    ? {
                        delay: CIRCULAR_CHART_ANIMATIONS.activityRings.centerLabelDelay,
                        duration: 0.4,
                    }
                    : { duration: 0 }, children: centerLabel && (jsxs("div", { className: cn((_e = theme.centerText) === null || _e === void 0 ? void 0 : _e.label, "flex  flex-col items-center"), children: [jsx("span", { children: centerLabel }), centerSuffix && (jsx("span", { className: (_f = theme.centerText) === null || _f === void 0 ? void 0 : _f.suffix, children: centerSuffix }))] })) })), jsx(ChartTooltip, { tooltipRef: tooltipRef, content: tooltipData === null || tooltipData === void 0 ? void 0 : tooltipData.content, active: !!tooltipData, position: tooltipData ? { x: tooltipData.x, y: tooltipData.y } : { x: 0, y: 0 } })] }));
};
ActivityRings.displayName = "ActivityRings";

export { ActivityRings };
