import { writable } from "svelte/store";

function createThemeToggler() {
  let defaultValue = false;
  let savedValue = localStorage.getItem("dark_theme");

  if (savedValue) {
    defaultValue = JSON.parse(savedValue);
  } else if (
    window.matchMedia &&
    window.matchMedia("(prefers-color-scheme: dark)").matches
  ) {
    defaultValue = true;
  }

  if (defaultValue) {
    document.body.dataset.theme = "dark";
  } else {
    document.body.dataset.theme = "light";
  }

  const { subscribe, update } = writable(defaultValue);

  return {
    subscribe,
    set: (value: boolean) => {
      update(() => value);
      if (value) {
        document.body.dataset.theme = "dark";
      } else {
        document.body.dataset.theme = "light";
      }

      localStorage.setItem("dark_theme", JSON.stringify(value));
    },
  };
}

export const darkTheme = createThemeToggler();
