/**
 * 主题管理工具
 * - 主色调切换（预设色板）
 * - 暗色/浅色模式（手动切换 + 跟随系统）
 */

// 预设主色调
export const themeColors = [
  { name: '靛蓝', value: '#6366f1' },
  { name: '天蓝', value: '#3b82f6' },
  { name: '青色', value: '#06b6d4' },
  { name: '翠绿', value: '#10b981' },
  { name: '琥珀', value: '#f59e0b' },
  { name: '玫红', value: '#ec4899' },
  { name: '紫色', value: '#8b5cf6' },
  { name: '红色', value: '#ef4444' },
];

// 根据主色生成衍生色
function generatePalette(hex) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return {
    '--color-primary': hex,
    '--color-primary-light': lighten(r, g, b, 0.25),
    '--color-primary-dark': darken(r, g, b, 0.15),
    '--color-primary-bg': lighten(r, g, b, 0.9),
    '--sidebar-bg': darken(r, g, b, 0.35),
  };
}

function lighten(r, g, b, amount) {
  return rgbToHex(
    Math.round(r + (255 - r) * amount),
    Math.round(g + (255 - g) * amount),
    Math.round(b + (255 - b) * amount)
  );
}

function darken(r, g, b, amount) {
  return rgbToHex(
    Math.round(r * (1 - amount)),
    Math.round(g * (1 - amount)),
    Math.round(b * (1 - amount))
  );
}

function rgbToHex(r, g, b) {
  return '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
}

// 应用主色调
export function applyThemeColor(hex) {
  const palette = generatePalette(hex);
  const root = document.documentElement;
  Object.entries(palette).forEach(([key, val]) => {
    root.style.setProperty(key, val);
  });
  // 同步 Element Plus 主色
  root.style.setProperty('--el-color-primary', hex);
  localStorage.setItem('theme-color', hex);
}

// 暗色模式: 'light' | 'dark' | 'system'
export function applyDarkMode(mode) {
  const root = document.documentElement;
  localStorage.setItem('theme-mode', mode);

  if (mode === 'system') {
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    root.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
  } else {
    root.setAttribute('data-theme', mode);
  }
}

// 监听系统主题变化
export function watchSystemTheme() {
  const mql = window.matchMedia('(prefers-color-scheme: dark)');
  mql.addEventListener('change', (e) => {
    const mode = localStorage.getItem('theme-mode') || 'light';
    if (mode === 'system') {
      document.documentElement.setAttribute('data-theme', e.matches ? 'dark' : 'light');
    }
  });
}

// 布局模式: 'sidebar' | 'topnav'
export function applyLayout(layout) {
  localStorage.setItem('theme-layout', layout);
  document.documentElement.setAttribute('data-layout', layout);
  const root = document.documentElement;
  if (layout === 'topnav') {
    // header(50px) + spacing(4px) + 标题栏(40px)
    root.style.setProperty('--page-top-offset', 'calc(var(--header-height) + 44px)');
  } else {
    root.style.setProperty('--page-top-offset', 'var(--content-padding-top)');
  }
}

export function getLayout() {
  return localStorage.getItem('theme-layout') || 'sidebar';
}

// 初始化主题（页面加载时调用）
export function initTheme() {
  const savedColor = localStorage.getItem('theme-color');
  if (savedColor) {
    applyThemeColor(savedColor);
  }

  const savedMode = localStorage.getItem('theme-mode') || 'light';
  applyDarkMode(savedMode);
  watchSystemTheme();

  const savedLayout = getLayout();
  applyLayout(savedLayout);
}
