// App-wide text size. Every font-size *and* every spacing value in globals.css
// is in rem and the root size is `calc(100% * var(--ui-scale))`, so writing one
// variable on <html> rescales the entire UI — no per-component work, and the
// browser's own base font size still applies underneath.
//
// The account is the source of truth (User.uiScale, served on /auth/me).
// localStorage holds a copy purely so the pre-hydration script in
// app/layout.tsx can paint at the right size before the session is known;
// AppShell reconciles the two once /auth/me answers. Keep UI_SCALE_KEY and the
// bounds in sync with that script and with the API's UpdatePreferencesDto.

export const UI_SCALE_KEY = "jc.ui-scale";
export const DEFAULT_UI_SCALE = 1;
export const MIN_UI_SCALE = 0.9;
export const MAX_UI_SCALE = 1.5;

export const UI_SCALES: { value: number; label: string; short: string }[] = [
  { value: 0.9, label: "Compacto", short: "A" },
  { value: 1, label: "Normal", short: "A" },
  { value: 1.15, label: "Grande", short: "A" },
  { value: 1.3, label: "Muy grande", short: "A" },
  { value: 1.5, label: "Máximo", short: "A" },
];

/** Clamp to the supported range; anything unparseable falls back to default. */
export function normalizeUiScale(value: unknown): number {
  const n = typeof value === "number" ? value : Number.parseFloat(String(value));
  if (!Number.isFinite(n)) return DEFAULT_UI_SCALE;
  return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, n));
}

export function readUiScale(): number {
  if (typeof window === "undefined") return DEFAULT_UI_SCALE;
  try {
    const raw = window.localStorage.getItem(UI_SCALE_KEY);
    return raw === null ? DEFAULT_UI_SCALE : normalizeUiScale(raw);
  } catch {
    // Private mode / storage disabled — the default is still usable.
    return DEFAULT_UI_SCALE;
  }
}

export function applyUiScale(scale: number): void {
  if (typeof document === "undefined") return;
  document.documentElement.style.setProperty("--ui-scale", String(scale));
}

export function saveUiScale(scale: number): void {
  try {
    window.localStorage.setItem(UI_SCALE_KEY, String(scale));
  } catch {
    /* ignore — the setting just won't survive a reload */
  }
}
