import { writable } from "svelte/store";
import { browser } from "$app/environment";

type Theme = "light" | "dark";

function createThemeStore() {
  const initial: Theme = browser
    ? ((localStorage.getItem("theme") as Theme) ?? "dark")
    : "dark";

  const { subscribe, set, update } = writable<Theme>(initial);

  function applyTheme(theme: Theme) {
    if (browser) {
      document.documentElement.setAttribute("data-theme", theme);
      localStorage.setItem("theme", theme);
    }
  }

  // Apply on init
  if (browser) applyTheme(initial);

  return {
    subscribe,
    toggle() {
      update((current) => {
        const next = current === "dark" ? "light" : "dark";
        applyTheme(next);
        return next;
      });
    },
    set(theme: Theme) {
      applyTheme(theme);
      set(theme);
    },
  };
}

export const theme = createThemeStore();
