import { createSignal, createEffect, createRoot, onCleanup } from "solid-js";

type Theme = "light" | "dark" | "system";
type ResolvedTheme = "light" | "dark";

const STORAGE_KEY = "shieldai-theme";

export function getSystemTheme(): ResolvedTheme {
  if (typeof window === "undefined") return "light";
  return window.matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
}

export function getStoredTheme(): Theme {
  try {
    const stored = globalThis.localStorage?.getItem(STORAGE_KEY);
    if (stored === "light" || stored === "dark") return stored;
  } catch {
    // storage unavailable
  }
  return "system";
}

export function getResolvedTheme(theme: Theme): ResolvedTheme {
  return theme === "system" ? getSystemTheme() : theme;
}

export function applyThemeClass(resolved: ResolvedTheme) {
  if (typeof document === "undefined") return;
  const root = document.documentElement;
  root.classList.remove("light", "dark");
  root.classList.add(resolved);
}

export function updateMetaThemeColor(resolved: ResolvedTheme) {
  if (typeof document === "undefined") return;
  const color = resolved === "dark" ? "#111827" : "#fafbfc";
  let meta = document.querySelector<HTMLMetaElement>(
    'meta[name="theme-color"]',
  );
  if (!meta) {
    meta = document.createElement("meta");
    meta.name = "theme-color";
    document.head.appendChild(meta);
  }
  meta.content = color;
}

export function persistTheme(theme: Theme) {
  try {
    globalThis.localStorage?.setItem(STORAGE_KEY, theme);
  } catch {
    // storage unavailable
  }
}

export function useTheme() {
  const initial = getStoredTheme();
  const [theme, setTheme] = createSignal<Theme>(initial);

  const resolved = () => getResolvedTheme(theme());

  createEffect(() => {
    const current = resolved();
    applyThemeClass(current);
    updateMetaThemeColor(current);
  });

  if (typeof window !== "undefined") {
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    const listener = () => {
      if (theme() === "system") {
        const systemResolved = getSystemTheme();
        applyThemeClass(systemResolved);
        updateMetaThemeColor(systemResolved);
      }
    };
    mediaQuery.addEventListener("change", listener);
    onCleanup(() => mediaQuery.removeEventListener("change", listener));
  }

  const setAndPersist = (newTheme: Theme) => {
    setTheme(newTheme);
    persistTheme(newTheme);
  };

  const toggle = () => {
    const next = resolved() === "dark" ? "light" : "dark";
    setAndPersist(next);
  };

  return { theme, resolved, setTheme: setAndPersist, toggle };
}
