import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  private isDarkModeSubject = new BehaviorSubject<boolean>(this.getInitialTheme());
  isDarkMode$ = this.isDarkModeSubject.asObservable();
  
  constructor() {  
    this.loadTheme();
    // Adicionar listener para mudanças de preferência do sistema
    window.matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', e => {
        this.isDarkModeSubject.next(e.matches);
        this.loadTheme();
      });
  }

  private getInitialTheme(): boolean {
    const savedTheme = localStorage.getItem('darkMode');
    if (savedTheme) {
      return JSON.parse(savedTheme);
    }

    // const currentHour = new Date().getHours();
    // currentHour >= 18  ? window.matchMedia('(prefers-color-scheme: dark)').matches : "";

    return window.matchMedia('(prefers-color-scheme: dark)').matches;

  }

  private loadTheme() {
    if (this.isDarkModeSubject.value) {
      document.documentElement.classList.add('dark-theme');
      document.documentElement.classList.remove('light-theme');
    } else {
      document.documentElement.classList.add('light-theme');
      document.documentElement.classList.remove('dark-theme');
    }
  }

  toggleTheme() {
    const isDark = !this.isDarkModeSubject.value;
    this.isDarkModeSubject.next(isDark);
    localStorage.setItem('darkMode', JSON.stringify(isDark));
    this.loadTheme();
  }
}  