import { onMounted } from 'vue';

type ThemeKey = 'classic' | 'light' | 'dark';

const THEME_STORAGE_KEY = 'agents_ui_theme';

const applyTheme = (theme: ThemeKey) => {
  const root = document.documentElement;
  root.setAttribute('data-theme', theme);
  document.body.setAttribute('data-theme', theme);

  // 调试信息
  console.log('=== Theme Applied ===');
  console.log('Theme:', theme);

  // 检查样式是否生效
  setTimeout(() => {
    console.log('=== Elements Check ===');

    // 输入栏底色
    const stadiumShell = document.querySelector('.stadium-shell');
    console.log('.stadium-shell exists:', !!stadiumShell);
    if (stadiumShell) {
      const styles = window.getComputedStyle(stadiumShell);
      console.log('.stadium-shell background-color:', styles.backgroundColor);
    }

    // 对话区域顶部的模型选择器
    const ribbonSelector = document.querySelector('.conversation-ribbon__selector');
    console.log('.conversation-ribbon__selector exists:', !!ribbonSelector);
    if (ribbonSelector) {
      const styles = window.getComputedStyle(ribbonSelector);
      console.log('.conversation-ribbon__selector color:', styles.color);
    }

    const selectorModel = document.querySelector('.selector-model');
    if (selectorModel) {
      const styles = window.getComputedStyle(selectorModel);
      console.log('.selector-model color:', styles.color);
    }

    const selectorMode = document.querySelector('.selector-mode');
    if (selectorMode) {
      const styles = window.getComputedStyle(selectorMode);
      console.log('.selector-mode color:', styles.color);
    }

    // 下拉菜单
    const dropdown = document.querySelector('.model-mode-dropdown');
    console.log('.model-mode-dropdown exists:', !!dropdown);
    if (dropdown) {
      const styles = window.getComputedStyle(dropdown);
      console.log('.model-mode-dropdown background-color:', styles.backgroundColor);
    }

    const dropdownItem = document.querySelector('.dropdown-item');
    if (dropdownItem) {
      const styles = window.getComputedStyle(dropdownItem);
      console.log('.dropdown-item color:', styles.color);
    }

    console.log('=== End Elements Check ===');
  }, 100);
};

const loadTheme = (): ThemeKey => {
  if (typeof window === 'undefined') return 'classic';
  const saved = window.localStorage.getItem(THEME_STORAGE_KEY) as ThemeKey | null;
  if (saved === 'light' || saved === 'dark' || saved === 'classic') return saved;
  return 'classic';
};

const persistTheme = (theme: ThemeKey) => {
  if (typeof window === 'undefined') return;
  window.localStorage.setItem(THEME_STORAGE_KEY, theme);
};

export const installTheme = () => {
  const theme = loadTheme();
  applyTheme(theme);
};

export const useTheme = () => {
  const setTheme = (theme: ThemeKey) => {
    applyTheme(theme);
    persistTheme(theme);
  };

  const restore = () => applyTheme(loadTheme());

  onMounted(() => {
    restore();
  });

  return { setTheme, restore, loadTheme };
};

export type { ThemeKey };
