/**
 * Unified theme management system
 * Works across all windows (setup-wizard, settings, actions)
 */

export type Theme = 'light' | 'dark' | 'system';

class ThemeManager {
  private theme: Theme = 'system';
  private listeners: Set<() => void> = new Set();
  private mediaQuery: MediaQueryList | null = null;

  constructor() {
    if (typeof window !== 'undefined') {
      this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      this.mediaQuery.addEventListener('change', this.handleSystemThemeChange);

      // Load saved theme preference from settings
      this.loadTheme();

      // Listen for theme changes from other windows
      this.listenForThemeChanges();
    }
  }

  private listenForThemeChanges = () => {
    // Listen for theme changes from other windows via IPC
    // Each window type (settings, setup-wizard, career-wizard, actions) has its own API
    if ((window as any).settingsAPI?.onThemeChange) {
      (window as any).settingsAPI.onThemeChange((newTheme: Theme) => {
        console.log('[ThemeManager] Received theme change:', newTheme);
        this.theme = newTheme;
        this.applyTheme();
        this.notifyListeners();
      });
    } else if ((window as any).setupWizardAPI?.onThemeChange) {
      (window as any).setupWizardAPI.onThemeChange((newTheme: Theme) => {
        console.log('[ThemeManager] Received theme change:', newTheme);
        this.theme = newTheme;
        this.applyTheme();
        this.notifyListeners();
      });
    } else if ((window as any).careerWizardAPI?.onThemeChange) {
      (window as any).careerWizardAPI.onThemeChange((newTheme: Theme) => {
        console.log('[ThemeManager] Received theme change:', newTheme);
        this.theme = newTheme;
        this.applyTheme();
        this.notifyListeners();
      });
    } else if ((window as any).actionsAPI?.onThemeChange) {
      (window as any).actionsAPI.onThemeChange((newTheme: Theme) => {
        console.log('[ThemeManager] Received theme change:', newTheme);
        this.theme = newTheme;
        this.applyTheme();
        this.notifyListeners();
      });
    } else if ((window as any).backupRestoreAPI?.onThemeChange) {
      (window as any).backupRestoreAPI.onThemeChange((newTheme: Theme) => {
        console.log('[ThemeManager] Received theme change:', newTheme);
        this.theme = newTheme;
        this.applyTheme();
        this.notifyListeners();
      });
    }
  };

  private loadTheme = async () => {
    try {
      let themeValue: string | undefined;

      // Try different window APIs to get the theme
      if (window.settingsAPI) {
        const settings = await window.settingsAPI.getSettings();
        themeValue = settings.theme;
      } else if ((window as any).setupWizardAPI?.getTheme) {
        themeValue = await (window as any).setupWizardAPI.getTheme();
      } else if ((window as any).careerWizardAPI?.getTheme) {
        themeValue = await (window as any).careerWizardAPI.getTheme();
      } else if ((window as any).actionsAPI?.getTheme) {
        themeValue = await (window as any).actionsAPI.getTheme();
      } else if ((window as any).backupRestoreAPI?.getTheme) {
        themeValue = await (window as any).backupRestoreAPI.getTheme();
      }

      if (themeValue) {
        this.theme = themeValue as Theme;
      }

      this.applyTheme();
      this.notifyListeners(); // Notify React components of the initial theme
    } catch (error) {
      console.error('Failed to load theme:', error);
      this.applyTheme();
    }
  };

  private handleSystemThemeChange = () => {
    if (this.theme === 'system') {
      this.applyTheme();
      this.notifyListeners();
    }
  };

  private applyTheme = () => {
    const root = document.documentElement;
    const isDark = this.getEffectiveTheme() === 'dark';

    if (isDark) {
      root.classList.add('dark');
    } else {
      root.classList.remove('dark');
    }
  };

  getTheme(): Theme {
    return this.theme;
  }

  getEffectiveTheme(): 'light' | 'dark' {
    if (this.theme === 'system') {
      return this.mediaQuery?.matches ? 'dark' : 'light';
    }
    return this.theme;
  }

  setTheme(theme: Theme) {
    this.theme = theme;
    this.applyTheme();
    this.notifyListeners();

    // Save to settings
    if (window.settingsAPI) {
      window.settingsAPI.setSetting('theme', theme).catch(console.error);
    }
  }

  subscribe(listener: () => void): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  private notifyListeners = () => {
    this.listeners.forEach(listener => listener());
  };

  cleanup() {
    if (this.mediaQuery) {
      this.mediaQuery.removeEventListener('change', this.handleSystemThemeChange);
    }
    this.listeners.clear();
  }
}

// Singleton instance
export const themeManager = new ThemeManager();
