import { FONT_SCALE_LS, FONT_SCALE_MAX, FONT_SCALE_MIN, FONT_SIZE_RANGE_MAX, FONT_SIZE_RANGE_MIN, FONT_SIZE_RANGE_STEP, THEME_LS } from '../config/constants.js';
import { $ } from '../core/dom.js';
import { readLs, writeLs } from '../core/storage.js';
import { scheduleUserPreferencesSave } from '../services/preferences.js';
import { state, userPrefsStore, runtime } from '../state/app-state.js';

export function getStoredTheme() {
  try {
    if (userPrefsStore.theme === "light" || userPrefsStore.theme === "dark" || userPrefsStore.theme === "system") {
      return userPrefsStore.theme;
    }
    const raw = readLs(THEME_LS);
    if (raw === "light" || raw === "dark" || raw === "system") return raw;
  } catch (_) {
    /* ignore */
  }
  return null;
}


export function resolveSystemTheme() {
  return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}


export function applyTheme(theme) {
  runtime.themeMode = theme === "system" ? "system" : theme === "dark" ? "dark" : "light";
  const t = runtime.themeMode === "system" ? resolveSystemTheme() : runtime.themeMode;
  document.documentElement.setAttribute("data-theme", t);
  writeLs(THEME_LS, runtime.themeMode);
  scheduleUserPreferencesSave({ theme: runtime.themeMode });
  const btn = $("btnThemeToggle");
  if (btn) {
    btn.setAttribute("aria-pressed", t === "dark" ? "true" : "false");
    btn.setAttribute("aria-label", t === "dark" ? "Activer le mode clair" : "Activer le mode sombre");
    btn.setAttribute("title", t === "dark" ? "Mode clair" : "Mode sombre");
    btn.textContent = t === "dark" ? "\u2600" : "\u263E";
  }
  const btnLight = $("btnThemeLight");
  const btnDark = $("btnThemeDark");
  const btnSystem = $("btnThemeSystem");
  if (btnLight) btnLight.classList.toggle("is-active", runtime.themeMode === "light");
  if (btnDark) btnDark.classList.toggle("is-active", runtime.themeMode === "dark");
  if (btnSystem) btnSystem.classList.toggle("is-active", runtime.themeMode === "system");
}


export function initTheme() {
  const stored = getStoredTheme();
  if (stored) {
    applyTheme(stored);
    return;
  }
  applyTheme("light");
}


export function getStoredFontScale() {
  try {
    if (userPrefsStore.font_scale != null) {
      const stored = Number(userPrefsStore.font_scale);
      if (isFinite(stored) && stored >= FONT_SCALE_MIN && stored <= FONT_SCALE_MAX) return stored;
    }
    const raw = readLs(FONT_SCALE_LS);
    if (raw == null) return 1;
    const n = parseFloat(raw);
    if (isFinite(n) && n >= FONT_SCALE_MIN && n <= FONT_SCALE_MAX) return n;
  } catch (_) {
    /* ignore */
  }
  return 1;
}


export function applyFontScale(scale) {
  let s = Number(scale);
  if (!isFinite(s)) s = 1;
  s = Math.min(FONT_SCALE_MAX, Math.max(FONT_SCALE_MIN, s));
  state.uiFontScale = s;
  document.documentElement.style.setProperty("--ui-font-scale", String(s));
  writeLs(FONT_SCALE_LS, String(s));
  scheduleUserPreferencesSave({ font_scale: s });
}


export function updateAppearanceFontPreviewHint() {
  const h = $("appearanceFontPreviewHint");
  const r = $("uiFontSizeRange");
  if (!h || !r) return;
  const raw = parseInt(r.value, 10);
  const slider = (isFinite(raw) ? raw : 100) / 100;
  const cl = Math.min(FONT_SCALE_MAX, Math.max(FONT_SCALE_MIN, slider));
  const diff = Math.abs(cl - state.uiFontScale) > 0.0005;
  h.hidden = !diff;
}


export function syncFontSizeSettingsUi() {
  const r = $("uiFontSizeRange");
  if (!r) return;
  const pct = Math.min(FONT_SIZE_RANGE_MAX, Math.max(FONT_SIZE_RANGE_MIN, Math.round(state.uiFontScale * 100)));
  const stepped = Math.round(pct / FONT_SIZE_RANGE_STEP) * FONT_SIZE_RANGE_STEP;
  const finalPct = Math.min(FONT_SIZE_RANGE_MAX, Math.max(FONT_SIZE_RANGE_MIN, stepped));
  r.value = String(finalPct);
  document.querySelectorAll(".appearance-font-presets__btn").forEach((btn) => {
    const p = parseInt(btn.dataset.fontPreset || "", 10);
    btn.classList.toggle("is-active", Number.isFinite(p) && p === finalPct);
  });
  updateAppearanceFontPreviewHint();
}


export function initFontScale() {
  applyFontScale(getStoredFontScale());
}
