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

/**
 * Builds the series definitions for the cache runtime chart.
 *
 * All translated labels are read from DOM data attributes so that the JS layer
 * never hardcodes user-facing strings.
 *
 * @param {HTMLElement} host
 *   The chart surface host element.
 * @param {Object} settings
 *   The chart settings from drupalSettings.
 *
 * @return {Array}
 *   The resolved series definitions.
 */
function buildSeriesDefinitions(host, settings) {
  const definitions = [];

  if (Array.isArray(settings.series?.response_cache_events)) {
    definitions.push({
      key: "response_cache_events",
      name: host.dataset.seriesResponseLabel || "",
    });
  }

  if (Array.isArray(settings.series?.cacheability_events)) {
    definitions.push({
      key: "cacheability_events",
      name: host.dataset.seriesCacheabilityLabel || "",
    });
  }

  if (Array.isArray(settings.series?.invalidation_events)) {
    definitions.push({
      key: "invalidation_events",
      name: host.dataset.seriesInvalidationLabel || "",
    });
  }

  return definitions;
}

/**
 * Builds the cache activity trend chart option.
 *
 * @param {HTMLElement} host
 *   The chart host element.
 * @param {Object} settings
 *   The chart settings from drupalSettings.
 * @param {Array} definitions
 *   The resolved series definitions.
 *
 * @return {Object}
 *   The ECharts option object.
 */
function buildChartOption(host, settings, definitions) {
  const firstSeries = settings.series?.[definitions[0].key] || [];
  const labels = firstSeries.map((item) => item.label ?? "");

  return {
    animation: true,
    tooltip: {
      trigger: "axis",
      confine: true,
    },
    legend: {
      top: 8,
      left: "center",
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 12,
      },
      data: definitions.map((definition) => definition.name),
    },
    grid: {
      top: 56,
      right: 24,
      bottom: 36,
      left: 56,
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: labels,
      axisLabel: {
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      name: host.dataset.axisEventsLabel || "",
      nameGap: 18,
      axisLabel: {
        fontSize: 12,
      },
    },
    series: definitions.map((definition) => ({
      name: definition.name,
      type: "line",
      smooth: true,
      symbol: "none",
      lineStyle: {
        width: 2,
      },
      ...(definition.key !== "invalidation_events"
        ? {
            areaStyle: {
              opacity: 0.08,
            },
          }
        : {}),
      data: (settings.series?.[definition.key] || []).map((item) =>
        Number(item.value ?? 0),
      ),
    })),
  };
}

/**
 * Initializes a single cache activity chart.
 *
 * @param {HTMLElement} host
 *   The chart surface host element.
 * @param {Object} settings
 *   The chart settings from drupalSettings.
 */
function initCacheActivityChart(host, settings) {
  if (host.dataset.chartReady === "true") {
    return;
  }

  const chartElement = host.querySelector(".no-cache-activity-trend__chart");
  if (!chartElement) {
    return;
  }

  const definitions = buildSeriesDefinitions(host, settings);

  if (!definitions.length) {
    createChartFallback(host, host.dataset.chartEmptyMessage || "");
    return;
  }

  initResponsiveEchart(
    chartElement,
    buildChartOption(host, settings, definitions),
    host.dataset.chartLibraryMessage || "",
  );

  host.dataset.chartReady = "true";
}

/**
 * Initializes cache runtime health charts.
 *
 * @param {HTMLElement} container
 *   The dashboard root element.
 * @param {Object} chartSettings
 *   The cache observability chart settings.
 */
export default function initCacheRuntimeHealth(container, chartSettings = {}) {
  const chartHosts = container.querySelectorAll(
    "[data-no-cache-runtime-chart]",
  );

  chartHosts.forEach((host) => {
    const chartId = host.dataset.chartId || "";

    if (!chartId || !chartSettings[chartId]) {
      return;
    }

    initCacheActivityChart(host, chartSettings[chartId]);
  });
}
