function setTheme(dark) {
  const root = document.documentElement;
  const icon = document.getElementById('themeIcon');
  const text = document.getElementById('themeText');

  if (dark) {
    root.classList.add('dark');
    localStorage.theme = 'dark';
    if (icon) icon.textContent = '☀️';
    if (text) text.textContent = 'Claro';
  } else {
    root.classList.remove('dark');
    localStorage.theme = 'light';
    if (icon) icon.textContent = '🌙';
    if (text) text.textContent = 'Escuro';
  }
}

function toggleTheme() {
  setTheme(!document.documentElement.classList.contains('dark'));
}

// Inicializa
document.addEventListener('DOMContentLoaded', () => {
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  const stored = localStorage.theme;
  setTheme(stored ? stored === 'dark' : prefersDark);

  const btn = document.getElementById('toggleTheme');
  if (btn) btn.addEventListener('click', toggleTheme);
});
