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

@Injectable({ providedIn: 'root' })
export class ThemeService {
    private readonly darkModeSubject = new BehaviorSubject<boolean>(false);

    readonly darkMode$ = this.darkModeSubject.asObservable();

    initTheme(): void {
        const savedTheme = localStorage.getItem('theme');
        this.applyDarkMode(savedTheme === 'dark');
    }

    toggleTheme(): void {
        this.applyDarkMode(!this.darkModeSubject.value);
    }

    setDarkMode(isDarkMode: boolean): void {
        this.applyDarkMode(isDarkMode);
    }

    private applyDarkMode(isDarkMode: boolean): void {
        if (isDarkMode) {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
        } else {
            document.documentElement.removeAttribute('data-theme');
            localStorage.removeItem('theme');
        }

        this.darkModeSubject.next(isDarkMode);
    }
}