import { createChartFallback, initResponsiveEchart } from "../services/echarts";

export default function initExternalRequestsPreview(
  container,
  previewSettings,
) {
  if (!previewSettings || !previewSettings.chart_id) {
    return;
  }

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

  if (!chartElement) {
    return;
  }

  const series = Array.isArray(previewSettings.series)
    ? previewSettings.series.filter((item) => Number(item.value || 0) > 0)
    : [];

  if (!series.length) {
    createChartFallback(
      chartElement,
      Drupal.t(
        "No external requests were captured for the selected time range.",
      ),
    );
    return;
  }

  initResponsiveEchart(
    chartElement,
    {
      tooltip: {
        trigger: "item",
      },
      legend: {
        top: 0,
        left: "center",
      },
      series: [
        {
          name: previewSettings.title || Drupal.t("External Requests"),
          type: "pie",
          radius: ["42%", "68%"],
          avoidLabelOverlap: true,
          label: {
            formatter: "{b}: {d}%",
          },
          data: series,
        },
      ],
    },
    Drupal.t("Apache ECharts is not available."),
  );
}
