import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useState, useEffect, useMemo } from 'react';
import Typography from '../../Typography/Typography.js';
import classNames from '../../../_virtual/index.js';
import { normalizeStorageValue, formatMemoryValue } from '../../../assets/utils/functionUtils.js';
import Tooltip from '../../Tooltip/Tooltip.js';
import Icon from '../../Icon/Icon.js';

const toNumber = (val) => typeof val === 'number' ? val : parseFloat(val) || 0;
const getRandomColor = () => {
    const color = Math.floor(Math.random() * 16777215).toString(16);
    return '#' + ('000000' + color).slice(-6);
};
const getUniqueVersions = (item) => {
    const unique = [];
    if (item.version && Array.isArray(item.version)) {
        const versionColorMap = {};
        item.version.forEach((ver, j) => {
            const verString = String(ver);
            const parts = verString.split('.');
            const major = Number(parts[0]);
            if (!(major in versionColorMap)) {
                const color = item.versionColor?.[j % (item.versionColor?.length || 1)] ||
                    getRandomColor();
                versionColorMap[major] = color;
                unique.push({ major, ver: verString, color });
            }
        });
    }
    return unique;
};
const calculateArc = (x, y, radius, startAngle, endAngle) => {
    const startX = x + radius * Math.cos(startAngle);
    const startY = y + radius * Math.sin(startAngle);
    const endX = x + radius * Math.cos(endAngle);
    const endY = y + radius * Math.sin(endAngle);
    const largeArcFlag = endAngle - startAngle > Math.PI ? 1 : 0;
    return `M ${startX} ${startY} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${endX} ${endY}`;
};
const calculateDonutSegmentBorderPath = (innerR, outerR, startAngle, endAngle) => {
    const startOuterX = innerR * Math.cos(startAngle);
    const startOuterY = innerR * Math.sin(startAngle);
    const endOuterX = innerR * Math.cos(endAngle);
    const endOuterY = innerR * Math.sin(endAngle);
    const endInnerX = outerR * Math.cos(endAngle);
    const endInnerY = outerR * Math.sin(endAngle);
    const startInnerX = outerR * Math.cos(startAngle);
    const startInnerY = outerR * Math.sin(startAngle);
    const largeArcFlag = endAngle - startAngle > Math.PI ? 1 : 0;
    return `
    M ${startOuterX} ${startOuterY}
    A ${innerR} ${innerR} 0 ${largeArcFlag} 1 ${endOuterX} ${endOuterY}
    L ${endInnerX} ${endInnerY}
    A ${outerR} ${outerR} 0 ${largeArcFlag} 0 ${startInnerX} ${startInnerY}
    Z
  `;
};
const colorMapping = [
    'var(--status-success-text-color)',
    'var(--status-rejected-text-color)',
    'var(--status-warning-text-color)',
    'var(--status-button-text-skipped)',
    'var(--brand-color)',
];
const DashboardDonutChart = ({ radius = 60, tableWidth, tableHeight = 120, lineWidth = 15, statusValues = [], gapAngle = 0, legendDetailsType = '', isLegendDetails = true, legendType = 'numberLegend', showOnlyLabel = false, apiDataLabel, unit, showUnit = true, labelFontSize = 24, subLabelFontSize = 14, legendPosition = 'bottom', chartGap = 0, legendGap = 5, legendValueFontSize = 22, legendKeyFontSize = 12, legendWithVersionFontSize = 12, versionErrorText, labelYoffSet = -5, subLabelYoffSet = 20, capsuleStyle = {}, legendTruncate = Infinity, isLegendToolTip = false, containerHeight = '', onSelectedStatus, selectedStatusKey = '', setSelectedStatusKey = (_selectedStatusKey) => { }, isOnClick = false, zIndex = 99, }) => {
    const [hoveredItemIndex, setHoveredItemIndex] = useState(null);
    const [hoveredVersion, setHoveredVersion] = useState(null);
    const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
    const [showTooltip, setShowTooltip] = useState(false);
    const [selectedItemIndex, setSelectedItemIndex] = useState(null);
    const [centerTextTooltip, setCenterTextTooltip] = useState({ show: false, content: '', position: { x: 0, y: 0 } });
    const [isTruncated, setTruncated] = useState(false);
    useEffect(() => {
        if (!selectedStatusKey) {
            setSelectedItemIndex(null);
        }
    }, [selectedStatusKey]);
    const handleCenterTextMouseEnter = (content, event) => {
        setCenterTextTooltip({
            show: true,
            content,
            position: { x: event.clientX + 14, y: event.clientY + 11 },
        });
    };
    const handleCenterTextMouseLeave = () => {
        setCenterTextTooltip({
            show: false,
            content: '',
            position: { x: 0, y: 0 },
        });
    };
    const handleCenterTextMouseMove = (event) => {
        setCenterTextTooltip((prev) => ({
            ...prev,
            position: { x: event.clientX + 14, y: event.clientY + 11 },
        }));
    };
    // Normalize data (and keep versionColor if provided)
    const normalizedStatusValues = legendType === 'memoryLegend'
        ? statusValues.map((item) => {
            if (typeof item.value === 'string') {
                const { normalizedValue, unit, value } = normalizeStorageValue(item.value);
                return { ...item, normalizedValue, unit, labelValue: value };
            }
            return {
                ...item,
                normalizedValue: item.value,
                labelValue: item.value,
                unit: 'B',
            };
        })
        : statusValues.map((item) => {
            if (typeof item.value === 'string') {
                const parsedValue = parseFloat(item.value);
                const normalizedValue = isNaN(parsedValue) ? 0 : parsedValue;
                return {
                    ...item,
                    normalizedValue,
                    unit: '',
                    labelValue: Number.isInteger(normalizedValue)
                        ? normalizedValue
                        : normalizedValue.toFixed(2),
                };
            }
            return {
                ...item,
                normalizedValue: item.value,
                unit: '',
                labelValue: Number.isInteger(item.value)
                    ? item.value
                    : item.value?.toFixed(2),
            };
        });
    const chartValues = normalizedStatusValues?.map((item, index) => ({
        ...item,
        value: item.normalizedValue ?? item.value,
        originalIndex: index,
    }));
    const total = chartValues?.reduce((acc, { value }) => acc + toNumber(value), 0) || 0;
    const nonZeroValues = chartValues?.filter(({ value }) => toNumber(value) > 0) || [];
    const totalMemory = formatMemoryValue(total);
    // Angle constants
    const MIN_PERCENTAGE = 1;
    const MIN_ANGLE = (MIN_PERCENTAGE / 100) * (2 * Math.PI);
    // Compute arc positions only once so that they remain stable.
    const computedArcs = useMemo(() => {
        if (nonZeroValues.length === 0)
            return [];
        const totalAngle = 2 * Math.PI;
        const totalGap = gapAngle * nonZeroValues.length;
        let remainingAngleCalc = totalAngle - totalGap;
        nonZeroValues.forEach(({ value }) => {
            const valuePercentage = toNumber(value) / total;
            const baseAngle = Math.max(valuePercentage * totalAngle, MIN_ANGLE);
            remainingAngleCalc -= baseAngle;
        });
        let currAngle = Math.PI / 2;
        return nonZeroValues.map((item) => {
            const valuePercentage = toNumber(item.value) / total;
            const baseAngle = Math.max(valuePercentage * totalAngle, MIN_ANGLE);
            const extraAngle = remainingAngleCalc * valuePercentage;
            const angle = baseAngle + extraAngle;
            const startAngle = currAngle;
            const endAngle = currAngle + angle;
            currAngle = endAngle + gapAngle;
            let subArcs = null;
            return { item, startAngle, endAngle, subArcs };
        });
    }, [nonZeroValues, total, gapAngle, MIN_ANGLE, versionErrorText]);
    const handleSegmentMouseEnter = (originalIndex) => {
        setHoveredItemIndex(originalIndex);
        setShowTooltip(true);
    };
    const handleSegmentMouseLeave = () => {
        setHoveredItemIndex(null);
        setShowTooltip(false);
    };
    const handleSegmentMouseMove = (event) => {
        setTooltipPosition({ x: event.clientX + 10, y: event.clientY + 10 });
    };
    const handleSelectStatus = (value, originalIndex, data) => {
        if (isOnClick && selectedStatusKey !== value) {
            setSelectedItemIndex(originalIndex);
            setSelectedStatusKey(value);
            onSelectedStatus?.(value, originalIndex, data);
        }
        else {
            setSelectedItemIndex(null);
            setSelectedStatusKey('');
        }
    };
    const SVG_PADDING = 3;
    const DONUT_SVG_SIZE = radius * 2 + lineWidth + SVG_PADDING * 2;
    const LABEL_MAX_WIDTH = radius * 2 - lineWidth - SVG_PADDING * 2;
    const borderGap = 2;
    const borderThickness = 2;
    const containsDots = (array) => array?.some((str) => str?.includes('...'));
    const renderArcSegment = (arcData, _i) => {
        if (arcData.subArcs) {
            // Versioned segment: render each sub-arc with its own event handlers.
            return (jsx("g", { className: "donut-segment version-segment", children: arcData.subArcs.map((sub, j) => {
                    const angleDiff = sub.endAngle - sub.startAngle;
                    const isFullCircle = Math.abs(angleDiff - 2 * Math.PI) < 0.01;
                    const isActive = hoveredVersion !== null
                        ? hoveredVersion.parentIndex === arcData.item.originalIndex &&
                            hoveredVersion.subIndex === j
                        : hoveredItemIndex !== null
                            ? hoveredItemIndex === arcData.item.originalIndex
                            : true;
                    if (isFullCircle) {
                        return (jsxs("g", { className: "sub-arc-group", onMouseEnter: (e) => {
                                setHoveredVersion({
                                    parentIndex: arcData.item.originalIndex,
                                    subIndex: j,
                                });
                                setTooltipPosition({
                                    x: e.clientX + 10,
                                    y: e.clientY + 10,
                                });
                                setShowTooltip(true);
                            }, onMouseLeave: () => {
                                setHoveredVersion(null);
                                setShowTooltip(false);
                            }, onMouseMove: (e) => setTooltipPosition({ x: e.clientX + 10, y: e.clientY + 10 }), children: [jsx("circle", { cx: "0", cy: "0", r: radius, fill: "none", stroke: sub.randomColor, strokeWidth: lineWidth, strokeOpacity: versionErrorText ? 0.2 : isActive ? 1 : 0, style: {
                                        transition: 'stroke-opacity 0.5s ease',
                                    } }), jsx("g", { className: "sub-arc-border-wrapper", style: {
                                        opacity: hoveredVersion &&
                                            hoveredVersion.parentIndex ===
                                                arcData.item.originalIndex &&
                                            hoveredVersion.subIndex === j
                                            ? 1
                                            : 0,
                                        transition: 'opacity 0.5s ease',
                                        overflow: 'visible',
                                    }, children: jsx("circle", { cx: "0", cy: "0", r: radius + lineWidth / 2 + borderGap + borderThickness / 2, fill: "none", stroke: sub.randomColor, strokeWidth: borderThickness, style: { transition: 'stroke 0.5s ease' } }) })] }, j));
                    }
                    else {
                        const arcPath = calculateArc(0, 0, radius, sub.startAngle, sub.endAngle);
                        const subBorderPath = calculateDonutSegmentBorderPath(radius + lineWidth / 2 + borderGap, radius + lineWidth / 2 + borderGap + borderThickness, sub.startAngle, sub.endAngle);
                        const subBorderOpacity = hoveredVersion &&
                            hoveredVersion.parentIndex === arcData.item.originalIndex &&
                            hoveredVersion.subIndex === j
                            ? 1
                            : 0;
                        const isSelected = selectedStatusKey === arcData?.item?.key;
                        return (jsxs("g", { className: "sub-arc-group", onMouseEnter: (e) => {
                                setHoveredVersion({
                                    parentIndex: arcData.item.originalIndex,
                                    subIndex: j,
                                });
                                setTooltipPosition({
                                    x: e.clientX + 10,
                                    y: e.clientY + 10,
                                });
                                setShowTooltip(true);
                            }, onMouseLeave: () => {
                                setHoveredVersion(null);
                                setShowTooltip(false);
                            }, onMouseMove: (e) => setTooltipPosition({ x: e.clientX + 10, y: e.clientY + 10 }), children: [jsx("path", { d: arcPath, fill: "none", stroke: sub.randomColor, strokeWidth: lineWidth, style: {
                                        strokeOpacity: isActive ? 1 : 0.2,
                                        transition: 'stroke-opacity 0.5s ease',
                                    } }), isSelected && isOnClick && (jsx("path", { d: arcPath, fill: "none", stroke: "var(--dotted-border-color)", strokeWidth: lineWidth, strokeOpacity: 0.4, pointerEvents: "none" })), jsx("g", { className: "sub-arc-border-wrapper", style: {
                                        opacity: subBorderOpacity,
                                        transition: 'opacity 0.5s ease',
                                        overflow: 'visible',
                                    }, children: jsx("path", { d: subBorderPath, fill: sub.randomColor, pointerEvents: "none" }) })] }, j));
                    }
                }) }, arcData.item.originalIndex));
        }
        else {
            // Normal (non-version) segment.
            const angleDiff = arcData.endAngle - arcData.startAngle;
            const isFullCircle = Math.abs(angleDiff - 2 * Math.PI) < 0.01;
            const isActive = hoveredItemIndex !== null
                ? hoveredItemIndex === arcData.item.originalIndex
                : hoveredVersion !== null
                    ? hoveredVersion.parentIndex === arcData.item.originalIndex
                    : true;
            const segmentColor = arcData.item.color ||
                colorMapping[arcData.item.originalIndex % colorMapping.length];
            const borderWrapperOpacity = hoveredItemIndex === arcData.item.originalIndex ? 1 : 0;
            const isSelected = selectedStatusKey === arcData?.item?.key;
            if (isFullCircle) {
                return (jsxs("g", { className: "donut-segment", children: [jsx("circle", { cx: "0", cy: "0", r: radius, fill: "none", stroke: segmentColor, strokeWidth: lineWidth, onMouseEnter: () => handleSegmentMouseEnter(arcData.item.originalIndex), onMouseLeave: handleSegmentMouseLeave, onMouseMove: handleSegmentMouseMove, onClick: () => handleSelectStatus(arcData.item.key, arcData.item.originalIndex, arcData.item), style: {
                                cursor: isOnClick ? 'pointer' : 'default',
                                strokeOpacity: isActive ? 1 : 0.2,
                                transition: 'stroke-opacity 0.5s ease',
                            } }), isSelected && isOnClick && (jsx("circle", { cx: "0", cy: "0", r: radius, fill: "none", strokeWidth: lineWidth, stroke: "var(--dotted-border-color)", strokeOpacity: 0.4, pointerEvents: "none" })), jsx("g", { className: "donut-border-wrapper", style: {
                                opacity: borderWrapperOpacity,
                                transition: 'opacity 0.5s ease',
                                overflow: 'visible',
                            }, children: jsx("circle", { cx: "0", cy: "0", r: radius + lineWidth / 2 + borderGap + borderThickness / 2, fill: "none", stroke: segmentColor, strokeWidth: borderThickness, style: { transition: 'stroke 0.5s ease' } }) })] }, arcData.item.originalIndex));
            }
            else {
                const arcPath = calculateArc(0, 0, radius, arcData.startAngle, arcData.endAngle);
                return (jsxs("g", { className: "donut-segment", children: [jsx("path", { d: arcPath, fill: "none", stroke: segmentColor, strokeWidth: lineWidth, onMouseEnter: () => handleSegmentMouseEnter(arcData.item.originalIndex), onMouseLeave: handleSegmentMouseLeave, onMouseMove: handleSegmentMouseMove, onClick: () => handleSelectStatus(arcData.item.key, arcData.item.originalIndex, arcData.item), style: {
                                cursor: isOnClick ? 'pointer' : 'default',
                                strokeOpacity: isActive ? 1 : 0.2,
                                transition: 'stroke-opacity 0.5s ease',
                            } }), isSelected && isOnClick && (jsx("path", { d: arcPath, fill: "none", stroke: "var(--dotted-border-color)", strokeWidth: lineWidth, strokeOpacity: 0.4, pointerEvents: "none" })), jsx("g", { className: "donut-border-wrapper", style: {
                                opacity: borderWrapperOpacity,
                                transition: 'opacity 0.5s ease',
                                overflow: 'visible',
                            }, children: jsx("path", { d: calculateDonutSegmentBorderPath(radius + lineWidth / 2 + borderGap, radius + lineWidth / 2 + borderGap + borderThickness, arcData.startAngle, arcData.endAngle), fill: segmentColor, pointerEvents: "none" }) })] }, arcData.item.originalIndex));
            }
        }
    };
    // Render tooltip using the shared originalIndex.
    const renderTooltip = () => {
        if (hoveredVersion !== null) {
            const parent = computedArcs.find((arc) => arc.item.originalIndex === hoveredVersion.parentIndex);
            const versionVal = Array.isArray(parent?.item?.version)
                ? parent.item.version[hoveredVersion.subIndex]
                : '';
            return (jsx("div", { className: "ff-donut-chart-tooltip", style: { left: tooltipPosition.x, top: tooltipPosition.y }, children: jsx(Typography, { children: `${parent?.item?.key}: ${versionVal}` }) }));
        }
        if (hoveredItemIndex !== null) {
            const hoveredItem = chartValues.find((item) => item.originalIndex === hoveredItemIndex);
            return (jsxs("div", { className: "ff-donut-chart-tooltip", style: { left: tooltipPosition.x, top: tooltipPosition.y }, children: [jsx(Typography, { children: `${hoveredItem?.key} : ` }), jsx(Typography, { children: legendType === 'memoryLegend'
                            ? `${hoveredItem?.labelValue} ${hoveredItem?.unit}`
                            : hoveredItem?.value }), hoveredItem?.version && (jsx(Typography, { children: `Version: ${hoveredItem.version.join(', ')}` }))] }));
        }
        return null;
    };
    // Render legend based on the legend type.
    const renderLegend = (legendData, legendType, legendPosition) => {
        const legendCount = legendData.length;
        const legendCountClass = legendCount > 6 ? 'ff-count-more' : `ff-count-${legendCount}`;
        const isSideLegend = legendPosition === 'left' || legendPosition === 'right';
        const handleToolTip = (legendItem, title, key) => {
            return isLegendToolTip ? (jsx(Tooltip, { placement: "bottom", title: title, children: legendItem }, key)) : (legendItem);
        };
        switch (legendType) {
            case 'numberLegend': {
                return (jsx("div", { className: classNames('ff-legend-container', 'ff-number-legend', legendCountClass, { 'ff-side-legend': isSideLegend }), style: { '--donut-legend-gap': `${legendGap}px` }, children: legendData?.map((item) => {
                        return (jsxs("div", { className: "ff-legend-item ff-d-flex", onMouseEnter: () => {
                                if (toNumber(item.value) > 0) {
                                    setHoveredItemIndex(item.originalIndex);
                                }
                            }, onMouseLeave: () => setHoveredItemIndex(null), children: [jsxs("div", { className: item.osIcon && item.osIcon.length > 0
                                        ? 'ff-legend-item-version'
                                        : 'ff-legend-item', children: [jsxs(Typography, { fontSize: legendValueFontSize, fontWeight: "semi-bold", className: "ff-legend-value", color: item.color
                                                ? item.color
                                                : colorMapping[item.originalIndex % colorMapping.length], children: [item.osIcon && item.osIcon.length > 0 ? (jsx(Icon, { name: item.osIcon })) : (String(item.labelValue || '00').padStart(2, '0') + ' '), showUnit && unit?.toUpperCase()] }), jsx(Typography, { fontSize: legendKeyFontSize, className: "ff-legend-key", textAlign: "center", children: item.key.length > legendTruncate ? (jsx(Tooltip, { placement: "bottom", title: isLegendToolTip ? item.key : '', children: `${item.key.slice(0, legendTruncate)}...` })) : (item.key) })] }), item.osIcon && item.osIcon.length > 0 && (jsx(Typography, { fontSize: legendKeyFontSize, className: "ff-legend-key", textAlign: "center", fontWeight: "semi-bold", children: "OS version" })), item.version && item.version.length > 0 ? (jsx("div", { className: "ff-legend-version-container", children: jsx("div", { className: "ff-legend-version-grid", children: (() => {
                                            const uniqueVersions = getUniqueVersions(item);
                                            return uniqueVersions.map((ver, j) => (jsxs("div", { onMouseEnter: () => setHoveredVersion({
                                                    parentIndex: item.originalIndex,
                                                    subIndex: j,
                                                }), onMouseLeave: () => setHoveredVersion(null), className: "ff-legend-version-item", children: [jsx("div", { className: "ff-legend-version-circle", style: { backgroundColor: ver.color } }), jsx(Typography, { fontSize: legendWithVersionFontSize, children: ver.major })] }, j)));
                                        })() }) })) : versionErrorText ? (jsx(Typography, { textAlign: "center", className: "ff-legend-version-error", fontSize: 14, children: versionErrorText })) : null] }, item.originalIndex));
                    }) }));
            }
            case 'pillLegend': {
                return (jsx("div", { className: "ff-legend-container ff-pill-legend", style: {
                        '--donut-legend-gap': `${legendGap}px`,
                        height: Number(containerHeight) - (DONUT_SVG_SIZE + chartGap),
                    }, children: legendData?.map((item) => {
                        const legendItem = (jsxs("div", { className: "ff-legend-item", children: [jsx(Typography, { as: "span", className: "ff-legend-capsule", fontSize: legendValueFontSize, style: {
                                        backgroundColor: item?.color
                                            ? item.color
                                            : colorMapping[item.originalIndex % colorMapping.length],
                                        ...capsuleStyle,
                                    }, children: item?.labelValue === 0 ? '00' : item?.labelValue }), jsx(Typography, { fontSize: legendKeyFontSize, className: "ff-legend-key", children: item?.key.length > legendTruncate
                                        ? `${item?.key.slice(0, legendTruncate)}...`
                                        : item?.key })] }, item.originalIndex));
                        return handleToolTip(legendItem, item.key, item.originalIndex);
                    }) }));
            }
            case 'memoryLegend': {
                return (jsx("div", { className: classNames('ff-legend-container', 'ff-memory-legend', legendCountClass, { 'ff-side-legend': isSideLegend }), style: { '--donut-legend-gap': `${legendGap}px` }, children: legendData?.map((item) => {
                        const legendItem = (jsxs("div", { className: "ff-legend-item", onMouseEnter: () => {
                                if (toNumber(item.value) > 0) {
                                    setHoveredItemIndex(item.originalIndex);
                                }
                            }, onMouseLeave: () => setHoveredItemIndex(null), children: [jsxs(Typography, { fontSize: legendValueFontSize, fontWeight: "semi-bold", className: "ff-legend-value", color: item.color
                                        ? item.color
                                        : colorMapping[item.originalIndex % colorMapping.length], children: [item.labelValue, " ", item.unit] }), jsx(Typography, { fontSize: legendKeyFontSize, className: "ff-legend-key", textAlign: "center", children: item.key.length > legendTruncate
                                        ? `${item.key.slice(0, legendTruncate)}...`
                                        : item.key })] }, item.originalIndex));
                        return handleToolTip(legendItem, item.key, item.originalIndex);
                    }) }));
            }
            case 'tableLegend': {
                return (jsx("div", { className: "ff-legend-table-wrapper", style: { height: tableHeight }, children: jsxs("table", { className: "ff-legend-table", children: [jsx("thead", { className: "ff-legend-table-thead", children: jsxs("tr", { children: [jsx("th", { className: "ff-table-header", style: { width: tableWidth, textAlign: 'left' }, children: "Name" }), jsx("th", { className: "ff-table-header", style: { textAlign: 'left', paddingLeft: '10px' }, children: "%" }), jsx("th", { className: "ff-table-header", style: { textAlign: 'left' }, children: "Count" })] }) }), jsx("tbody", { className: "ff-legend-table-tbody", children: legendData?.map((item) => (jsxs("tr", { className: "ff-legend-item", onMouseEnter: () => {
                                        setHoveredItemIndex(item.originalIndex);
                                    }, onMouseLeave: () => setHoveredItemIndex(null), children: [jsxs("td", { className: "ff-legend-name", children: [jsxs("span", { className: "ff-legend-capsule", style: {
                                                        backgroundColor: item.color
                                                            ? item.color
                                                            : colorMapping[item.originalIndex % colorMapping.length],
                                                    }, children: [jsx(Typography, { fontSize: 10, children: item?.value === 0 ? '00' : item.value }), ' '] }), jsx(Typography, { fontSize: 10, children: item.key })] }), jsx("td", { className: "ff-legend-percentage", children: item.percentage
                                                ? item.percentage
                                                : typeof item.value === 'string'
                                                    ? Math.round((parseFloat(item.value) / total) * 100)
                                                    : total === 0
                                                        ? 0
                                                        : Math.round((item.value / total) * 100) }), jsx("td", { className: "ff-legend-count", children: item.value })] }, item.originalIndex))) })] }) }));
            }
            default:
                return null;
        }
    };
    // Utility functions for text wrapping (unchanged)
    function wrapText(text, maxWidth, fontSize) {
        const words = text.split(' ');
        const lines = [];
        let currentLine = '';
        words.forEach((word) => {
            const testLine = currentLine ? `${currentLine} ${word}` : word;
            if (measureTextWidth(testLine, fontSize) <= maxWidth) {
                currentLine = testLine;
            }
            else {
                if (currentLine)
                    lines.push(currentLine);
                currentLine = word;
            }
        });
        if (currentLine)
            lines.push(currentLine);
        return lines;
    }
    function measureTextWidth(text, fontSize) {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        if (!context)
            throw new Error('Unable to get canvas context');
        context.font = `${fontSize}px Poppins`;
        return context.measureText(text).width;
    }
    const truncateChartText = (text) => {
        const tempElement = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        tempElement.style.fontSize = `${subLabelFontSize}px`;
        tempElement.style.visibility = 'hidden';
        const svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svgContainer.appendChild(tempElement);
        document.body.appendChild(svgContainer);
        tempElement.textContent = text;
        let textWidth = tempElement.getComputedTextLength();
        if (textWidth <= LABEL_MAX_WIDTH) {
            document.body.removeChild(svgContainer);
            return text;
        }
        let truncatedText = text;
        while (textWidth > LABEL_MAX_WIDTH && truncatedText.length > 0) {
            truncatedText = truncatedText.slice(0, -1);
            tempElement.textContent = `${truncatedText}...`;
            textWidth = tempElement.getComputedTextLength();
        }
        document.body.removeChild(svgContainer);
        return `${truncatedText}...`;
    };
    const getCenterText = () => {
        if (legendType === 'tableLegend' && hoveredItemIndex !== null) {
            const hoveredItem = chartValues.find((item) => item.originalIndex === hoveredItemIndex);
            return total === 0
                ? '0%'
                : `${Math.round(((hoveredItem?.value || 0) / total) * 100)}%`;
        }
        if (legendType === 'memoryLegend') {
            return `${totalMemory}`;
        }
        if (isOnClick && hoveredItemIndex !== null) {
            const hoveredItem = chartValues.find((item) => item.originalIndex === hoveredItemIndex);
            return `${hoveredItem?.value}`;
        }
        return `${legendType === 'tableLegend'
            ? `${chartValues.length}`
            : Number.isInteger(total)
                ? total
                : total?.toFixed(2)} ${showUnit && unit ? unit.toUpperCase() : ''}`;
    };
    const getSubLabelText = () => {
        if (legendType === 'tableLegend' && hoveredItemIndex !== null) {
            const hoveredItem = chartValues.find((item) => item.originalIndex === hoveredItemIndex);
            return truncateChartText(hoveredItem?.key || '');
        }
        if (isOnClick && hoveredItemIndex !== null) {
            const hoveredItem = chartValues.find((item) => item.originalIndex === hoveredItemIndex);
            return truncateChartText(hoveredItem?.key || '');
        }
        return truncateChartText(legendDetailsType);
    };
    const subLabelLines = useMemo(() => {
        return wrapText(getSubLabelText(), LABEL_MAX_WIDTH, subLabelFontSize);
    }, [
        hoveredItemIndex,
        selectedItemIndex,
        legendType,
        legendDetailsType,
        chartValues,
        total,
        isOnClick,
        subLabelFontSize,
    ]);
    useEffect(() => {
        setTruncated(containsDots(subLabelLines));
    }, [subLabelLines]);
    return (jsxs("div", { className: classNames('ff-dashboard-donut-chart-section', {
            'ff-dashboard-donut-chart-section-table-legend': legendType === 'tableLegend',
            'legend-position-bottom': legendPosition === 'bottom',
            'legend-position-left': legendPosition === 'left',
            'ff-overflow-visible': true,
        }), style: { gap: `${chartGap}px` }, children: [jsxs("div", { className: "ff-dashboard-donut-chart-svg-container", style: { zIndex: zIndex }, children: [jsx("svg", { width: DONUT_SVG_SIZE, height: DONUT_SVG_SIZE, viewBox: `0 0 ${DONUT_SVG_SIZE} ${DONUT_SVG_SIZE}`, className: "ff-svg-overflow-visible", children: jsxs("g", { transform: `translate(${radius + lineWidth / 2 + SVG_PADDING}, ${radius + lineWidth / 2 + SVG_PADDING})`, children: [total === 0 || nonZeroValues.length === 0 ? (jsx("circle", { cx: 0, cy: 0, r: radius, fill: "none", stroke: "var(--tooltip-bg-color)", strokeWidth: lineWidth, strokeOpacity: 0.8, opacity: 0.2 })) : (computedArcs.map((arc, i) => renderArcSegment(arc))), showOnlyLabel && (jsx("text", { x: "0", y: "5", className: "ff-svg-label-text", textAnchor: "middle", fill: colorMapping[3], style: { fontSize: `${labelFontSize}px` }, children: wrapText(legendDetailsType, LABEL_MAX_WIDTH, labelFontSize).map((line, index, lines) => (jsx("tspan", { x: "0", dy: index === 0 ? (lines.length > 1 ? -8 : 0) : 24, children: line }, index))) })), !showOnlyLabel && (jsxs(Fragment, { children: [jsx("text", { x: "0", y: labelYoffSet, textAnchor: "middle", fill: colorMapping[3], style: { fontSize: `${labelFontSize}px` }, children: wrapText(getCenterText(), LABEL_MAX_WIDTH, labelFontSize).map((line, index) => (jsx("tspan", { x: "0", dy: index === 0 ? 0 : labelFontSize, children: selectedItemIndex !== null &&
                                                    chartValues.find((item) => item.originalIndex === selectedItemIndex)
                                                    ? index === 0
                                                        ? chartValues.find((item) => item.originalIndex === selectedItemIndex)?.value
                                                        : null
                                                    : apiDataLabel
                                                        ? apiDataLabel
                                                        : line }, index))) }), jsx("text", { x: "0", y: subLabelYoffSet, textAnchor: "middle", fill: "var(--text-color)", style: { fontSize: `${subLabelFontSize}px` }, children: subLabelLines?.map((line, index) => (jsx("tspan", { x: "0", dy: index === 0 ? 0 : subLabelFontSize, fill: (selectedItemIndex !== null &&
                                                    chartValues.find((item) => item.originalIndex === selectedItemIndex)?.color) ||
                                                    (hoveredItemIndex !== null &&
                                                        isOnClick &&
                                                        chartValues.find((item) => item.originalIndex === hoveredItemIndex)?.color) ||
                                                    '', onMouseEnter: (e) => handleCenterTextMouseEnter(legendDetailsType, e), onMouseLeave: handleCenterTextMouseLeave, onMouseMove: handleCenterTextMouseMove, className: "center-text-tooltip", children: line }, index))) })] }))] }) }), showTooltip && renderTooltip(), centerTextTooltip.show && isTruncated && (jsx("div", { className: "ff-donut-chart-tooltip", style: {
                            left: centerTextTooltip.position.x,
                            top: centerTextTooltip.position.y,
                            zIndex: zIndex + 1,
                        }, children: jsx(Typography, { children: centerTextTooltip?.content }) }))] }), isLegendDetails && renderLegend(chartValues, legendType, legendPosition)] }));
};

export { DashboardDonutChart as default };
//# sourceMappingURL=DashboardDonutChart.js.map
