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

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  private renderer: Renderer2;
  private currentThemeSub = new BehaviorSubject<string>('dark');
  currentTheme$ = this.currentThemeSub.asObservable();

  constructor(rendererFactory: RendererFactory2) {
    this.renderer = rendererFactory.createRenderer(null, null);
    const savedTheme = localStorage.getItem('palm-ai-theme') || 'dark';
    this.setTheme(savedTheme);
  }

  toggleTheme(): void {
    const nextTheme = this.currentThemeSub.value === 'dark' ? 'light' : 'dark';
    this.setTheme(nextTheme);
  }

  setTheme(theme: string): void {
    const oldTheme = theme === 'dark' ? 'light' : 'dark';
    this.renderer.removeClass(document.body, `theme-${oldTheme}`);
    this.renderer.addClass(document.body, `theme-${theme}`);
    localStorage.setItem('palm-ai-theme', theme);
    this.currentThemeSub.next(theme);
  }

  isDark(): boolean {
    return this.currentThemeSub.value === 'dark';
  }
}
