import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import './DonutChart.scss';
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)',
    },
    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)',
    },
});
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 = ['passed', 'failed', 'warning', 'skipped'];
    // Calculate angles and gaps
    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);
    let minAngleTotal = 0;
    // Adjust for small angles
    nonZeroValues.forEach(({ count }) => {
        const valuePercentage = count / totalCount;
        const angle = Math.max(valuePercentage * (2 * Math.PI), MIN_ANGLE);
        minAngleTotal += 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 = statusValue?.status?.toLowerCase();
        const isFullCircle = nonZeroValues.length === 1;
        // Full circle handling
        const foregroundArcPath = isFullCircle
            ? calculateArc(0, 0, radius, 0, 2 * Math.PI)
            : calculateArc(0, 0, radius, currentAngle, endAngle);
        // Outer arc for hover effect
        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 statusData = resultStats?.find((s) => s.status?.toLowerCase() === statusKey?.toLowerCase());
        return (_jsxs("div", { className: `ff-status-item ${hoveredStatus === null || hoveredStatus === statusKey
                ? 'ff-highlighted'
                : 'ff-fade'}`, onMouseEnter: () => handleMouseEnter(statusKey), onMouseLeave: handleMouseLeave, children: [_jsxs("div", { className: "ff-status-label", children: [_jsx("div", { className: "ff-status-color", style: {
                                backgroundColor: colorMapping[statusKey],
                            } }), _jsx("div", { className: "ff-status-text", children: statusKey?.charAt(0)?.toUpperCase() +
                                statusKey?.slice(1)?.toLowerCase() })] }), _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) => statusValue?.status?.toLowerCase() === hoveredStatus)?.count ?? 0} ${legendDetailsType}`
                                    : `${totalCount} ${legendDetailsType}` }), _jsx("rect", { x: -17, y: 14, width: 34, height: 18, fill: hoveredStatus
                                    ? hoverMapping[hoveredStatus?.toLowerCase()]
                                    : hoverMapping.default, rx: "5", ry: "5" }), _jsx("text", { x: "0", y: "26", textAnchor: "middle", fill: hoveredStatus
                                    ? colorMapping[hoveredStatus?.toLowerCase()]
                                    : colorMapping['default'], children: hoveredStatus
                                    ? `${(resultStats?.find((statusValue) => statusValue?.status?.toLowerCase() === hoveredStatus)?.percentage || 0)?.toFixed(2)}%`
                                    : '100%' })] }) }) }), isLegendDetails && (_jsx("div", { className: "ff-status-container", children: statusColors?.map((status) => renderLegendItem(status)) }))] }));
};
export default DonutChart;
//# sourceMappingURL=DonutChart.js.map