import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useRef, useState, useEffect, useCallback } from "react";
import { Svg, Wrapper } from "./styled";
import * as d3 from "d3";
const D3DonutChart = ({ side, padding, payload, colorRange, thickness, outerBorder, outerBorderColor, annotation, annotations, hasAnnotationHtml, tooltips, ...props }) => {
    const svgRef = useRef(null);
    const [enabledTooltip, setEnabledTooltip] = useState(-1);
    const [tooltipXY, setTooltipXY] = useState({
        x: -Infinity,
        y: -Infinity,
    });
    useEffect(() => {
        const mouseMoveListener = (e) => {
            const chart = svgRef.current;
            if (!chart) {
                return;
            }
            const rect = chart.getBoundingClientRect().toJSON();
            setTooltipXY({
                x: e.clientX - rect.left - 38,
                y: e.clientY - rect.top - 67,
            });
        };
        window.addEventListener("mousemove", mouseMoveListener);
        return () => {
            window.removeEventListener("mousemove", mouseMoveListener);
        };
    }, []);
    const Tooltip = useCallback(({ x, y }) => {
        const CurrentTooltip = tooltips && tooltips.find((_, i) => i === enabledTooltip);
        if (!CurrentTooltip) {
            return null;
        }
        // @ts-ignore
        return _jsx(CurrentTooltip, { left: x, top: y });
    }, [tooltips, enabledTooltip]);
    useEffect(() => {
        if (!svgRef.current)
            return;
        const svg = d3.select(svgRef.current);
        const addonBorder = outerBorder ?? 0;
        // @ts-ignore
        svg.attr("viewBox", [
            -side / 2 - addonBorder,
            -side / 2 - addonBorder,
            side + addonBorder * 2,
            side + addonBorder * 2,
        ]);
        const colorScale = d3
            .scaleOrdinal()
            .domain(payload.map((el) => el.name))
            .range(colorRange);
        const pie = d3
            .pie()
            .padAngle(0.005)
            .sort(null)
            .value((d) => d.value);
        const radius = side / 2;
        const thinknessCoeff = thickness ? (radius - thickness + 1) / radius : 0.67;
        const arc = d3
            .arc()
            .innerRadius(radius * thinknessCoeff)
            .outerRadius(radius - 1);
        const arcs = pie(payload);
        const selection = svg
            .selectAll("path")
            .data(arcs)
            .join("path")
            .attr("fill", (d) => colorScale(d.data.name))
            .attr("d", arc);
        if (tooltips) {
            selection
                .on("mouseenter", (e, d) => {
                setEnabledTooltip(d.index);
            })
                .on("mouseleave", (e, _2) => {
                const isFocusChangedToInnerText = e?.toElement?.localName === "text" ||
                    // if mouse moved to div with % and currency name:
                    (e?.toElement?.childNodes?.length === 2 &&
                        Object.values(e?.toElement?.childNodes)?.filter?.((n) => n?.nodeName === "#text")?.length === 2);
                if (!isFocusChangedToInnerText) {
                    setEnabledTooltip(-1);
                }
            });
        }
        if (annotation) {
            svg
                .selectAll("svg")
                .data(arcs)
                .join("text")[hasAnnotationHtml ? "html" : "text"]((d) => annotation.formatter(d.value))
                .attr("transform", (d) => "translate(" + arc.centroid(d) + ")")
                .style("text-anchor", "middle")
                .style("font-size", annotation.fontSize)
                .style("font-family", annotation.fontFamily)
                .style("line-height", annotation.lineHeight)
                .style("fill", (_, i) => typeof annotation.color === "function"
                ? annotation.color(i)
                : annotation.color);
        }
        if (annotations) {
            const firstAnnotation = annotations[0];
            svg
                .selectAll("svg")
                .data(arcs)
                .join("text")[
            // @ts-ignore
            hasAnnotationHtml ? "html" : "text"]((d) => firstAnnotation.formatter(d.value, d.data.additionalData))
                // @ts-ignore
                .attr("transform", (d) => "translate(" + arc.centroid(d) + ")")
                .style("text-anchor", firstAnnotation.textAnchor ?? "middle")
                .style("font-size", firstAnnotation.fontSize)
                .style("font-family", firstAnnotation.fontFamily)
                .style("line-height", firstAnnotation.lineHeight)
                .style("fill", (_, i) => typeof firstAnnotation.color === "function"
                ? firstAnnotation.color(i)
                : firstAnnotation.color);
            let dy = firstAnnotation.verticalSpace ?? firstAnnotation.lineHeight;
            annotations.slice(1).forEach((annot) => {
                svg
                    .selectAll("svg")
                    .data(arcs)
                    .join("text")[
                // @ts-ignore
                hasAnnotationHtml ? "html" : "text"]((d) => annot.formatter(d.value, d.data.additionalData))
                    // @ts-ignore
                    .attr("transform", (d) => "translate(" + arc.centroid(d) + ")")
                    .attr("dy", dy)
                    .style("text-anchor", annot.textAnchor ?? "middle")
                    .style("font-size", annot.fontSize)
                    .style("font-family", annot.fontFamily)
                    .style("line-height", annot.lineHeight)
                    .style("fill", (_, i) => typeof annot.color === "function" ? annot.color(i) : annot.color);
                dy += annot.verticalSpace ?? annot.lineHeight;
            });
        }
        /*
        if (!annotation.formatters || !annotation.formatters.length) {
          svg
            .selectAll("svg")
            .data(arcs)
            .join("text")
            // @ts-ignore
            .text((d) => annotation.formatter(d.value))
            // @ts-ignore
            .attr("transform", (d) => "translate(" + arc.centroid(d) + ")")
            .style("text-anchor", "middle")
            .style("font-size", annotation.fontSize)
            .style("font-family", annotation.fontFamily)
            .style("line-height", annotation.lineHeight)
            .style("color", annotation.color);
        } else {
          const firstFormatter = annotation.formatters[0];
          const selection = svg
            .selectAll("svg")
            .data(arcs)
            .join("text")
            // @ts-ignore
            .text((d) => firstFormatter(d.value))
            // @ts-ignore
            .attr("transform", (d) => "translate(" + arc.centroid(d) + ")")
            .style("text-anchor", "middle")
            .style("font-size", annotation.fontSize)
            .style("font-family", annotation.fontFamily)
            .style("line-height", annotation.lineHeight)
            .style("color", annotation.color);
    
          let dy = annotation.lineHeight;
          annotation.formatters.slice(1).forEach(fmt => {
            svg
              .selectAll("svg")
              .data(arcs)
              .join("text")
              // @ts-ignore
              .text((d) => fmt(d.value))
              // @ts-ignore
              .attr("transform", (d) => "translate(" + arc.centroid(d) + ")")
              .attr("dy", dy)
              .style("text-anchor", "middle")
              .style("font-size", annotation.fontSize)
              .style("font-family", annotation.fontFamily)
              .style("line-height", annotation.lineHeight)
              .style("color", annotation.color);
          });
    
          dy += annotation.lineHeight;
        }
        */
        if (outerBorder && outerBorderColor) {
            const outerArc = d3
                .arc()
                .innerRadius(radius - 1)
                .outerRadius(radius - 1 + outerBorder);
            svg
                .selectAll("svg")
                .data(arcs)
                .join("path")
                .attr("fill", () => outerBorderColor)
                .attr("d", outerArc);
        }
    }, [svgRef, payload]);
    // @ts-ignore
    return (_jsxs(Wrapper, { className: "ui-d3donutchart__wrapper", children: [_jsx(Svg, { className: "ui-d3donutchart__svg", style: { height: side, width: side }, ref: svgRef }), _jsx(Tooltip, { ...tooltipXY })] }));
};
export default D3DonutChart;
//# sourceMappingURL=index.js.map