/**
 * Creates a chart fallback message inside the provided element.
 *
 * @param {HTMLElement} element
 *   The target element.
 * @param {string} message
 *   The translated fallback message.
 */
export function createChartFallback(element, message) {
  if (!element) {
    return;
  }

  element.innerHTML = "";

  const fallback = document.createElement("div");
  fallback.className = "no-chart-fallback";
  fallback.textContent = message || "";

  element.appendChild(fallback);
}

/**
 * Initializes an Apache ECharts chart and keeps it responsive.
 *
 * @param {HTMLElement} element
 *   The target chart element.
 * @param {Object} option
 *   The ECharts option object.
 * @param {string} missingLibraryMessage
 *   The translated fallback message shown when ECharts is unavailable.
 */
export function initResponsiveEchart(
  element,
  option,
  missingLibraryMessage = "",
) {
  if (!element) {
    return;
  }

  if (typeof window.echarts === "undefined") {
    createChartFallback(element.parentNode || element, missingLibraryMessage);
    return;
  }

  let chart = null;
  let resizeObserver = null;

  /**
   * Boots the chart only when the container has measurable dimensions.
   */
  const bootChart = () => {
    const width = element.clientWidth;
    const height = element.clientHeight;

    if (!width || !height) {
      window.requestAnimationFrame(bootChart);
      return;
    }

    if (chart) {
      chart.dispose();
    }

    chart = window.echarts.init(element);
    chart.setOption(option, true);
    chart.resize();
  };

  /**
   * Resizes the chart safely.
   */
  const resizeChart = () => {
    if (chart) {
      chart.resize();
    }
  };

  bootChart();

  window.addEventListener("resize", resizeChart);

  if (typeof ResizeObserver !== "undefined") {
    resizeObserver = new ResizeObserver(() => {
      resizeChart();
    });
    resizeObserver.observe(element);
    if (element.parentNode instanceof HTMLElement) {
      resizeObserver.observe(element.parentNode);
    }
  }
}
