import { Injectable, signal, effect } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  public highContrast = signal<boolean>(true);

  /** Whether the system prefers dark mode */
  private systemPrefersDark = signal<boolean>(false);

  constructor() {
    // Load from localStorage
    const saved = localStorage.getItem('high-contrast');
    if (saved !== null) {
      this.highContrast.set(saved === 'true');
    } else {
      this.highContrast.set(true);
    }

    // Detect system dark mode preference
    if (typeof window !== 'undefined') {
      const darkMq = window.matchMedia('(prefers-color-scheme: dark)');
      this.systemPrefersDark.set(darkMq.matches);
      darkMq.addEventListener('change', (e) => {
        this.systemPrefersDark.set(e.matches);
      });
    }

    // Effect to apply high-contrast class to body and html
    effect(() => {
      const isHigh = this.highContrast();
      if (typeof document !== 'undefined') {
        const root = document.documentElement;
        if (isHigh) {
          root.classList.add('high-contrast');
          if (document.body) document.body.classList.add('high-contrast');
        } else {
          root.classList.remove('high-contrast');
          if (document.body) document.body.classList.remove('high-contrast');
        }
      }
      localStorage.setItem('high-contrast', isHigh.toString());
    });

    // Effect to manage Ionic dark palette class
    // When high contrast is ON → NEVER apply dark palette (force light mode)
    // When high contrast is OFF and system prefers dark → apply dark palette
    effect(() => {
      const isHigh = this.highContrast();
      const systemDark = this.systemPrefersDark();

      if (typeof document !== 'undefined') {
        const root = document.documentElement;
        if (!isHigh && systemDark) {
          root.classList.add('ion-palette-dark');
          if (document.body) document.body.classList.add('ion-palette-dark');
        } else {
          root.classList.remove('ion-palette-dark');
          if (document.body) document.body.classList.remove('ion-palette-dark');
        }
      }
    });
  }

  toggleContrast() {
    this.highContrast.update(v => !v);
  }
}
