import { watch } from "vue";
import { addClass, removeClass } from "@grozav/utils";
export const onChangeColorMode = (colorMode) => {
  let color;
  if (colorMode === "system") {
    color = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
  } else {
    color = colorMode;
  }
  removeClass(document.documentElement, "light-theme dark-theme");
  addClass(document.documentElement, `${color}-theme`);
};
export const colorModeLocalStorageKey = "inkline-color-mode";
export const ColorModePlugin = {
  install: (app, { inkline, renderMode }) => {
    if (typeof window !== "undefined") {
      const onDarkModeMediaQueryChange = () => {
        if (inkline.options.colorMode === "system") {
          onChangeColorMode(inkline.options.colorMode);
        }
      };
      const darkModeMediaQuery = matchMedia("(prefers-color-scheme: dark)");
      if (darkModeMediaQuery.addEventListener) {
        darkModeMediaQuery.addEventListener("change", onDarkModeMediaQueryChange);
      } else {
        darkModeMediaQuery.addListener(onDarkModeMediaQueryChange);
      }
      watch(
        () => inkline.options.colorMode,
        (colorMode) => {
          onChangeColorMode(colorMode);
          if (inkline.options.colorModeStrategy === "localStorage") {
            localStorage.setItem(colorModeLocalStorageKey, colorMode);
          }
        }
      );
      if (inkline.options.colorModeStrategy === "localStorage" && renderMode === "client") {
        const storedColorMode = localStorage.getItem(colorModeLocalStorageKey);
        if (storedColorMode) {
          inkline.options.colorMode = storedColorMode;
        }
      } else {
        onChangeColorMode(inkline.options.colorMode);
      }
    }
  }
};
