/**
 * Theme Manager - Handles light/dark theme with cookie persistence
 */

class ThemeManager {
  constructor() {
    this.cookieName = 'dss-theme';
    this.cookieExpireDays = 365;
    this.init();
  }

  init() {
    // Load theme from cookie or default to dark
    const savedTheme = this.getCookie(this.cookieName) || 'dark';
    this.setTheme(savedTheme, false); // Don't save on init
  }

  /**
   * Get cookie value
   */
  getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
      return parts.pop().split(';').shift();
    }
    return null;
  }

  /**
   * Set cookie value
   */
  setCookie(name, value, days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = `expires=${date.toUTCString()}`;
    document.cookie = `${name}=${value};${expires};path=/;SameSite=Lax`;
  }

  /**
   * Set theme (light or dark)
   */
  setTheme(theme, save = true) {
    const html = document.documentElement;

    if (theme === 'dark') {
      html.classList.add('dark');
      html.classList.remove('light');
    } else {
      html.classList.add('light');
      html.classList.remove('dark');
    }

    // Save to cookie
    if (save) {
      this.setCookie(this.cookieName, theme, this.cookieExpireDays);
    }

    // Dispatch event for other components
    window.dispatchEvent(new CustomEvent('theme-changed', {
      detail: { theme }
    }));

    return theme;
  }

  /**
   * Toggle between light and dark
   */
  toggle() {
    const currentTheme = this.getCurrentTheme();
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    return this.setTheme(newTheme);
  }

  /**
   * Get current theme
   */
  getCurrentTheme() {
    return document.documentElement.classList.contains('dark') ? 'dark' : 'light';
  }

  /**
   * Check if dark mode is active
   */
  isDark() {
    return this.getCurrentTheme() === 'dark';
  }
}

// Create singleton instance
const themeManager = new ThemeManager();

export default themeManager;
