import { jsxs, jsx } from 'react/jsx-runtime';
import { useState } from 'react';
import { convertToCamelCase } from '../../../utils/converToCamelCase.js';

const normalizeStatus = (s) => s?.toLowerCase().trim() || '';
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 useColorMappings = () => ({
    colorMapping: {
        passed: 'var(--status-success-text-color)',
        failed: 'var(--status-rejected-text-color)',
        warning: 'var(--status-warning-text-color)',
        skipped: 'var(--status-skipped-text-color)',
        default: 'var(--brand-color)',
        'on hold': 'var(--ff-onhold-donutchart-color)',
        descoped: 'var(--ff-descope-donutchart-color)',
        'to be validated': 'var(--ff-to-be-validate-donutchart-color)',
        'to be tested': 'var(--status-button-bg-tobetested)',
        terminated: 'var(--ff-terminated-donutchart-color)',
    },
    hoverMapping: {
        passed: 'var(--status-success-bg-color)',
        failed: 'var(--status-rejected-bg-color)',
        warning: 'var(--status-warning-bg-color)',
        skipped: 'var(--status-skipped-bg-color)',
        default: 'var(--status-percentage-growth-bg-color)',
        'on hold': 'var(--ff-onhold-donutchart-color)',
        descoped: 'var(--ff-descope-donutchart-color)',
        'to be validated': 'var(--ff-to-be-validate-donutchart-color)',
        'to be tested': 'var(--status-button-bg-tobetested)',
        terminated: 'var(--ff-terminated-donutchart-color)',
    },
});
const DonutChart = ({ radius = 60, lineWidth = 15, resultStats = [], gapAngle = 0.06, legendDetailsType = '', isLegendDetails = true, totalCount, }) => {
    const [hoveredStatus, setHoveredStatus] = useState(null);
    const { colorMapping, hoverMapping } = useColorMappings();
    const nonZeroValues = resultStats?.filter(({ count }) => count > 0);
    const statusColors = resultStats?.map((status) => status?.status);
    const TOTAL_GAP_ANGLE = gapAngle * nonZeroValues.length;
    let remainingAngle = 2 * Math.PI - TOTAL_GAP_ANGLE;
    let currentAngle = -Math.PI / 2;
    const MIN_PERCENTAGE = 1;
    const MIN_ANGLE = (MIN_PERCENTAGE / 100) * (2 * Math.PI);
    nonZeroValues.forEach(({ count }) => {
        const valuePercentage = count / totalCount;
        const angle = Math.max(valuePercentage * (2 * Math.PI), MIN_ANGLE);
        remainingAngle -= angle;
    });
    const handleMouseEnter = (status) => setHoveredStatus(status);
    const handleMouseLeave = () => setHoveredStatus(null);
    const SVG_PADDING = 4;
    const DONUT_SVG_SIZE = (radius + lineWidth) * 2 + SVG_PADDING * 2;
    const renderArc = (statusValue, endAngle, i) => {
        const normalizedStatus = normalizeStatus(statusValue?.status).toLowerCase();
        const isFullCircle = nonZeroValues.length === 1;
        const foregroundArcPath = isFullCircle
            ? calculateArc(0, 0, radius, 0, 2 * Math.PI)
            : calculateArc(0, 0, radius, currentAngle, endAngle);
        const outerArcRadius = radius + lineWidth - 1;
        const outerArcPath = isFullCircle
            ? calculateArc(0, 0, outerArcRadius, 0, 2 * Math.PI)
            : calculateArc(0, 0, outerArcRadius, currentAngle, endAngle);
        currentAngle = endAngle + gapAngle;
        return (jsxs("g", { children: [jsx("path", { d: foregroundArcPath, fill: "none", stroke: colorMapping[normalizedStatus], strokeWidth: lineWidth, onMouseEnter: () => handleMouseEnter(normalizedStatus), onMouseLeave: handleMouseLeave, strokeOpacity: hoveredStatus === null || hoveredStatus === normalizedStatus
                        ? 0.8
                        : 0.3 }), hoveredStatus === normalizedStatus && (jsx("path", { d: outerArcPath, fill: "none", stroke: colorMapping[normalizedStatus], strokeWidth: 4, strokeOpacity: 0.3 }))] }, i));
    };
    const renderLegendItem = (statusKey) => {
        const normalizedKey = normalizeStatus(statusKey);
        const statusData = resultStats?.find((statusValue) => normalizeStatus(statusValue?.status) === normalizedKey);
        return (jsxs("div", { className: `ff-status-item ${hoveredStatus === null || hoveredStatus === normalizedKey
                ? 'ff-highlighted'
                : 'ff-fade'}`, onMouseEnter: () => handleMouseEnter(normalizedKey), onMouseLeave: handleMouseLeave, children: [jsxs("div", { className: "ff-status-label", children: [jsx("div", { className: "ff-status-color", style: {
                                backgroundColor: colorMapping[normalizedKey],
                            } }), jsx("div", { className: "ff-status-text", children: convertToCamelCase(statusKey) })] }), jsxs("div", { className: "ff-status-details", children: [jsxs("div", { className: "ff-status-details-script-count", children: [statusData?.count || 0, jsx("span", { children: legendDetailsType })] }), jsxs("div", { className: "ff-status-details-script-percentage", children: ["(", statusData?.percentage?.toFixed(2) || 0, "%)"] })] })] }, statusKey));
    };
    return (jsxs("div", { className: "ff-donut-chart-section", children: [jsx("div", { className: "ff-donut-chart-svg-container", children: jsx("svg", { width: DONUT_SVG_SIZE, height: DONUT_SVG_SIZE, viewBox: `0 0 ${DONUT_SVG_SIZE} ${DONUT_SVG_SIZE}`, children: jsxs("g", { transform: `translate(${radius + lineWidth + SVG_PADDING}, ${radius + lineWidth + SVG_PADDING})`, children: [nonZeroValues?.map((status, i) => {
                                const valuePercentage = status.count / totalCount;
                                let angle = Math.max(valuePercentage * (2 * Math.PI), MIN_ANGLE);
                                angle += remainingAngle * valuePercentage;
                                const endAngle = currentAngle + angle;
                                return renderArc(status, endAngle, i);
                            }), jsx("text", { x: "0", y: "-18", textAnchor: "middle", fill: colorMapping.default, children: hoveredStatus ? hoveredStatus?.toUpperCase() : 'TOTAL' }), jsx("text", { x: "0", y: "5", textAnchor: "middle", fill: colorMapping.skipped, children: hoveredStatus
                                    ? `${resultStats?.find((statusValue) => normalizeStatus(statusValue?.status) === hoveredStatus)?.count ?? 0} ${legendDetailsType}`
                                    : `${totalCount} ${legendDetailsType}` }), jsx("rect", { x: -17, y: 14, width: 34, height: 18, fill: hoveredStatus
                                    ? hoverMapping[hoveredStatus]
                                    : hoverMapping.default, rx: "5", ry: "5" }), jsx("text", { x: "0", y: "26", textAnchor: "middle", fill: hoveredStatus
                                    ? colorMapping[hoveredStatus]
                                    : colorMapping['default'], children: hoveredStatus
                                    ? `${(resultStats?.find((statusValue) => normalizeStatus(statusValue?.status) === hoveredStatus)?.percentage || 0)?.toFixed(2)}%`
                                    : '100%' })] }) }) }), isLegendDetails && (jsx("div", { className: "ff-status-container", children: statusColors?.map((status) => renderLegendItem(status)) }))] }));
};

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