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

    this.apply();
    if (this.cb) this.cb.addEventListener('change', () => this.toggle());
  }

  toggle() {
    const resolved = this.getResolved();
    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);
    if (this.cb) this.cb.checked = (theme === 'dark');

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

window.ThemeSwitcher = ThemeSwitcher;
