import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import { AgChartOptions } from "ag-charts-enterprise";
import "ag-charts-enterprise";

const ChartExample = () => {
  const [options, setOptions] = useState<AgChartOptions>({
    dataSource: {
      getData: () =>
        new Promise(() => {
          // Never resolve so the loading spinner remains
        }),
    },
    overlays: {
      loading: {
        renderer: () => {
          const container = document.createElement("div");
          container.style.display = "flex";
          container.style.alignItems = "flex-end";
          container.style.justifyContent = "flex-start";
          container.style.flexDirection = "column";
          container.style.height = "100%";
          container.style.boxSizing = "border-box";
          container.style.userSelect = "none";
          container.style.animation = "loading 250ms linear 50ms both";
          const spinner = document.createElement("div");
          spinner.style.width = "20px";
          spinner.style.height = "20px";
          spinner.style.backgroundImage = [
            "linear-gradient(#333, #333)",
            "linear-gradient(#999, #999)",
            "linear-gradient(#ccc, #ccc)",
          ].join(", ");
          spinner.style.backgroundPosition = "0% 0%, 0% 100%, 100% 100%";
          spinner.style.backgroundSize = "50% 50%";
          spinner.style.backgroundRepeat = "no-repeat";
          spinner.style.animation = "loading-spinner 1s infinite";
          const animation = document.createElement("style");
          animation.innerText = [
            "@keyframes loading { from { opacity: 0 } to { opacity: 1 } }",
            "@keyframes loading-spinner {",
            "  0% { background-position: 0% 0%, 0% 100%, 100% 100%; }",
            "  25% { background-position: 100% 0%, 0% 0%, 0% 100%; }",
            "  50% { background-position: 100% 100%, 100% 0%, 0% 0%; }",
            "  75% { background-position: 0% 100%, 100% 100%, 100% 0%; }",
            "  100% { background-position: 0% 0%, 0% 100%, 100% 100%; }",
            "}",
          ].join(" ");
          container.replaceChildren(spinner, animation);
          return container;
        },
      },
    },
    series: [
      {
        xKey: "year",
        yKey: "spending",
      },
    ],
    axes: [
      { type: "number", position: "left", title: { text: "Year" } },
      { type: "number", position: "bottom", title: { text: "Spending" } },
    ],
  });

  return <AgCharts options={options as any} />;
};

const root = createRoot(document.getElementById("root")!);
root.render(<ChartExample />);

/** DARK MODE START **/
import { AgCharts as __chartAPI } from "ag-charts-community";

let darkmode =
  (localStorage["documentation:darkmode"] ||
    String(matchMedia("(prefers-color-scheme: dark)").matches)) === "true";

const isAgThemeOrUndefined = (theme) => {
  return (
    theme == null || (typeof theme === "string" && theme.startsWith("ag-"))
  );
};

const getDarkmodeTheme = (theme = "ag-default", preset) => {
  const baseTheme =
    preset === "price-volume" ? "ag-financial" : theme.replace(/-dark$/, "");
  return darkmode ? baseTheme + "-dark" : baseTheme;
};

__chartAPI.optionsMutationFn = function update(options, preset) {
  const nextOptions = { ...options };
  const theme = options.theme;
  if (isAgThemeOrUndefined(theme)) {
    nextOptions.theme = getDarkmodeTheme(theme, preset);
  } else if (
    typeof theme === "object" &&
    isAgThemeOrUndefined(theme.baseTheme)
  ) {
    nextOptions.theme = {
      ...options.theme,
      baseTheme: getDarkmodeTheme(theme.baseTheme, preset),
    };
  }
  return nextOptions;
};

const applyDarkmode = () => {
  document.documentElement.setAttribute("data-dark-mode", darkmode);
  const charts = document.querySelectorAll("[data-ag-charts]");
  charts.forEach((element) => {
    const chart = __chartAPI.getInstance(element.parentElement);
    if (chart == null) return;
    // This is just needed to trigger the theme update
    chart.update(chart.getOptions());
  });
  return charts.length !== 0;
};

if (!applyDarkmode()) {
  /* React defers updates. Rather than try and hook into the API, just wait until the darkmode is applied. */
  const observer = new MutationObserver(() => {
    if (applyDarkmode()) {
      observer.disconnect();
    }
  });
  observer.observe(document.body, {
    attributes: true,
    childList: true,
    subtree: true,
  });
}
window.addEventListener("message", (event) => {
  if (event.data && event.data.type === "color-scheme-change") {
    darkmode = event.data.darkmode;
    applyDarkmode();
  }
});
/** DARK MODE END **/
