import { ref } from "vue";

type Theme = "light" | "dark";

const theme = ref<Theme>(getInitialTheme());

function getInitialTheme(): Theme {
  const stored = localStorage.getItem("theme");
  if (stored === "light" || stored === "dark") return stored;
  if (window.matchMedia("(prefers-color-scheme: light)").matches) return "light";
  return "dark";
}

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

export function useTheme() {
  // Apply on first use
  applyTheme(theme.value);

  function toggleTheme() {
    theme.value = theme.value === "dark" ? "light" : "dark";
    applyTheme(theme.value);
  }

  return { theme, toggleTheme };
}
