// Appearance preferences (theme / locale / date format / currency / font size), applied
// to the document so every view — not just the Settings page — reflects them.
import { reactive } from "vue";

export const prefs = reactive({
  theme: "system", // light | dark | system
  locale: "en-US",
  dateFormat: "YMD", // YMD | DMY | MDY
  timeFormat: "auto", // auto (the region's own convention) | 24 | 12
  currency: "USD", // ISO 4217 code
  fontSize: "medium", // small | medium | large
  // Holds every arrangement still: the garage, a car's tabs, its Information
  // rows, the provider's readings. Nothing to apply to the document — the views
  // read it to decide whether their elements are draggable at all.
  dragLocked: false,
  // The charging page's tab arrangement. Kept here rather than fetched by the
  // view because it arrives with the profile anyway, and the bar has to render
  // in the right order on the first paint.
  chargerTabOrder: [],
  chargerCardOrder: [],
  // Which tab each tabbed page opens on, keyed by page:
  // { charging: "home", car: "info", settings: "personal" }. A page missing here
  // opens on whichever tab leads its bar — see lib/tabs.js, which owns the rule
  // and the key lists.
  defaultTabs: {},
});

const FONT_SCALE = { small: "93.75%", medium: "100%", large: "112.5%" };

let media = null;

function applyTheme() {
  const dark = prefs.theme === "dark" || (prefs.theme === "system" && media?.matches);
  document.documentElement.classList.toggle("dark", !!dark);
}

function applyFontSize() {
  document.documentElement.style.fontSize = FONT_SCALE[prefs.fontSize] || FONT_SCALE.medium;
}

// Called once at startup so the login screen (pre-auth) already respects the
// system color scheme, before any profile has been loaded.
export function initPrefs() {
  if (!media) {
    media = window.matchMedia("(prefers-color-scheme: dark)");
    media.addEventListener("change", () => {
      if (prefs.theme === "system") applyTheme();
    });
  }
  applyTheme();
  applyFontSize();
}

// Called after fetching /api/me (login, app boot, and Settings saves) to sync
// the document to the signed-in user's saved preferences.
export function applyProfilePrefs(profile) {
  prefs.theme = profile.theme || "system";
  prefs.locale = profile.locale || "en-US";
  prefs.dateFormat = profile.dateFormat || "YMD";
  prefs.timeFormat = profile.timeFormat || "auto";
  prefs.currency = profile.currency || "USD";
  prefs.fontSize = profile.fontSize || "medium";
  prefs.dragLocked = !!profile.dragLocked;
  prefs.chargerTabOrder = Array.isArray(profile.chargerTabOrder) ? profile.chargerTabOrder : [];
  prefs.chargerCardOrder = Array.isArray(profile.chargerCardOrder) ? profile.chargerCardOrder : [];
  prefs.defaultTabs = profile.defaultTabs && typeof profile.defaultTabs === "object"
    ? { ...profile.defaultTabs }
    : {};
  applyTheme();
  applyFontSize();
}
