import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  connect() {
    this.initThemeToggle();
    console.log("Stimulus: chargement du contrôler du switch");
  }


  initThemeToggle() {
    const themeToggleBtn = document.getElementById('theme-toggle');
    if (!themeToggleBtn) return;

    let currentTheme = localStorage.getItem('theme') || 'auto';

    const applyTheme = (theme) => {
      if (theme === 'auto') {
        const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        theme = systemPrefersDark ? 'dark' : 'light';
      }
      document.documentElement.setAttribute('data-theme', theme);
    };

    const toggleTheme = () => {
      if (currentTheme === 'dark') {
        currentTheme = 'light';
        console.log('Thème clair activé');
      } else if (currentTheme === 'light') {
        currentTheme = 'dark';
        console.log('Thème sombre activé');
      } else {
        const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        currentTheme = systemPrefersDark ? 'light' : 'dark';
      }
      localStorage.setItem('theme', currentTheme);
      applyTheme(currentTheme);
    };

    applyTheme(currentTheme);

    themeToggleBtn.addEventListener('click', toggleTheme);

    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
      if (currentTheme === 'auto') {
        applyTheme(e.matches ? 'dark' : 'light');
      }
    });
  }
}