import { ref } from "vue";

// Persisted light/dark theme for the panel. Matches the DriverVault web app's
// class strategy (`.dark` on <html>), but under its own storage key so it
// doesn't collide with the main app's `theme` preference.
const KEY = "dh-panel-theme";

function initial() {
  try {
    const saved = localStorage.getItem(KEY);
    if (saved === "dark" || saved === "light") return saved;
  } catch {
    /* private mode */
  }
  // Fall back to the OS preference.
  return window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}

export const theme = ref(initial());

export function applyTheme(t) {
  theme.value = t;
  document.documentElement.classList.toggle("dark", t === "dark");
  try {
    localStorage.setItem(KEY, t);
  } catch {
    /* private mode — theme just won't persist */
  }
}

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

applyTheme(theme.value);
