const THEME_KEY = 'theme-preference';

function getStoredUser() {
  try {
    const raw = localStorage.getItem('user');
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    return parsed && typeof parsed === 'object' ? parsed : null;
  } catch {
    return null;
  }
}

function getUserThemeKey() {
  const user = getStoredUser();
  if (!user) return null;

  const identity = user.id || user.userId || user.email || user.username || user.identifier;
  if (!identity) return null;

  return `${THEME_KEY}:user:${String(identity).toLowerCase()}`;
}

function setRootTheme(theme) {
  const root = document.documentElement;
  const finalTheme = theme === 'dark' ? 'dark' : 'light';
  root.setAttribute('data-theme', finalTheme);
  root.style.colorScheme = finalTheme;
}

function getSystemPrefersDark() {
  return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

export function getSavedTheme() {
  const userKey = getUserThemeKey();
  const saved = userKey ? localStorage.getItem(userKey) : localStorage.getItem(THEME_KEY);
  if (saved === 'dark' || saved === 'light') return saved;
  return 'light';
}

export function applyTheme(theme) {
  const finalTheme = theme === 'dark' ? 'dark' : 'light';
  setRootTheme(finalTheme);

  const userKey = getUserThemeKey();
  if (userKey) {
    localStorage.setItem(userKey, finalTheme);
    return;
  }

  localStorage.setItem(THEME_KEY, finalTheme);
}

export function initTheme() {
  applyTheme(getSavedTheme());
}

export function toggleTheme() {
  const current = document.documentElement.getAttribute('data-theme') || getSavedTheme();
  const next = current === 'dark' ? 'light' : 'dark';
  applyTheme(next);
  return next;
}

export function isDarkTheme() {
  const current = document.documentElement.getAttribute('data-theme') || getSavedTheme();
  return current === 'dark';
}

// Login should remain neutral and should not persist or inherit cross-user preferences.
export function applyLoginTheme() {
  setRootTheme('light');
}

export function applySavedTheme() {
  setRootTheme(getSavedTheme());
}
