const STORAGE_KEY = "picobot-theme";
const ACCENT_STORAGE_KEY = "picobot-accent";

export const ACCENT_THEMES = Object.freeze([
  { id: "blue", label: "海蓝", swatch: "#0f6cbd", description: "Fluent 默认蓝" },
  { id: "purple", label: "紫罗兰", swatch: "#5c2e91", description: "沉静而专注" },
  { id: "teal", label: "青绿", swatch: "#006c4c", description: "清晰且克制" },
  { id: "green", label: "森林", swatch: "#107c10", description: "稳定与活力" },
  { id: "orange", label: "暖橙", swatch: "#ca5010", description: "醒目而友好" },
  { id: "magenta", label: "莓红", swatch: "#9b0062", description: "鲜明有个性" }
]);

const ACCENT_IDS = new Set(ACCENT_THEMES.map((theme) => theme.id));

export function preferredTheme() {
  const saved = localStorage.getItem(STORAGE_KEY);
  if (saved === "light" || saved === "dark") return saved;
  return matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}

export function preferredAccent() {
  const saved = localStorage.getItem(ACCENT_STORAGE_KEY);
  return ACCENT_IDS.has(saved) ? saved : "blue";
}

function notifyAppearance() {
  window.dispatchEvent(new CustomEvent("picobot-appearance-change", {
    detail: {
      theme: document.documentElement.dataset.theme,
      accent: document.documentElement.dataset.accent
    }
  }));
}

export function applyTheme(theme) {
  const next = theme === "dark" ? "dark" : "light";
  document.documentElement.dataset.theme = next;
  document.documentElement.style.colorScheme = next;
  document
    .querySelector('meta[name="theme-color"]')
    ?.setAttribute("content", next === "dark" ? "#1f1f1f" : "#fafafa");
  localStorage.setItem(STORAGE_KEY, next);
  notifyAppearance();
}

export function applyAccent(accent) {
  const next = ACCENT_IDS.has(accent) ? accent : "blue";
  document.documentElement.dataset.accent = next;
  localStorage.setItem(ACCENT_STORAGE_KEY, next);
  notifyAppearance();
}
