class ThemeSwitcher {
  constructor() {
    this.btn = document.getElementById('theme-toggle');
    this.current = localStorage.getItem('cmux-remote-theme') || 'auto';

    this.apply();
    this.btn.addEventListener('click', () => this.toggle());
  }

  toggle() {
    const resolved = this.getResolved();
    // Toggle to opposite of current effective theme
    this.current = resolved === 'dark' ? 'light' : 'dark';
    localStorage.setItem('cmux-remote-theme', this.current);
    this.apply();
  }

  getResolved() {
    if (this.current === 'auto') {
      return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
    }
    return this.current;
  }

  apply() {
    const theme = this.getResolved();
    document.documentElement.setAttribute('data-theme', theme);
    this.btn.textContent = theme === 'dark' ? '\u{2600}' : '\u{1F319}';

    // Update theme-color meta
    const meta = document.querySelector('meta[name="theme-color"]');
    if (meta) {
      meta.content = theme === 'dark' ? '#0c0c14' : '#f8f9fc';
    }
  }
}

window.ThemeSwitcher = ThemeSwitcher;
