/**
 * @file
 * Initializes ECharts donut charts for the Response Time KPI breakdown.
 *
 * Reads settings from drupalSettings.nativeObservabilityDashboard.breakdownDonut
 * and renders a compact donut inside [data-breakdown-chart-id] elements.
 *
 * Completely isolated from initCharts() (canvas sparklines) and
 * initTimelineChart() (timeline ECharts). Does not modify their behavior.
 */

/**
 * Initialises the breakdown donut for the Response Time KPI card.
 *
 * @param {HTMLElement} container - The dashboard wrapper element.
 * @param {object|null} settings - The breakdownDonut drupalSettings payload.
 */
export default function initBreakdownDonut(container, settings) {
  if (!settings || !settings.chart_id || !Array.isArray(settings.series)) {
    return;
  }

  const echartsLib = window.echarts;
  if (!echartsLib) {
    return;
  }

  const element = container.querySelector(
    `[data-breakdown-chart-id="${settings.chart_id}"]`,
  );

  if (!element || element.dataset.breakdownReady === "true") {
    return;
  }

  if (!element.clientWidth || !element.clientHeight) {
    window.requestAnimationFrame(() => initBreakdownDonut(container, settings));
    return;
  }

  const chart = echartsLib.init(element);

  chart.setOption({
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const desc = params.data.description || params.name;
        return `<strong>${params.name}</strong> ${params.percent}%<br/><span style="opacity:.75;font-size:11px">${desc}</span>`;
      },
    },
    series: [
      {
        type: "pie",
        radius: ["52%", "78%"],
        avoidLabelOverlap: false,
        label: { show: false },
        labelLine: { show: false },
        emphasis: {
          scale: true,
          scaleSize: 4,
        },
        data: settings.series,
      },
    ],
  });

  chart.resize();
  element.dataset.breakdownReady = "true";

  const resizeObserver =
    typeof ResizeObserver !== "undefined"
      ? new ResizeObserver(() => chart.resize())
      : null;

  if (resizeObserver) {
    resizeObserver.observe(element);
  } else {
    window.addEventListener("resize", () => chart.resize());
  }
}
