const themeKey = 'theme';
const html = document.documentElement;
const systemPrefDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

function applyTheme(theme) {
  html.setAttribute('data-theme', theme);
}

function getStoredTheme() {
  return localStorage.getItem(themeKey);
}

function initTheme(defaultTheme = systemPrefDark ? 'dark' : 'light') {
  const stored = getStoredTheme();
  applyTheme(stored || defaultTheme);
}

function toggleTheme() {
  const current = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
  applyTheme(current);
  localStorage.setItem(themeKey, current);
}

// initialize on load
initTheme();

// listen for toggle button
document.addEventListener('DOMContentLoaded', () => {
  const btn = document.querySelector('[data-theme-toggle]');
  if (btn) btn.addEventListener('click', toggleTheme);
});
