/**
 * 主题配置模块
 * 
 * 支持：
 * - 预设主题（绿色森林、蓝色海洋、暖色调等）
 * - 自定义主题（手动设置各层级颜色）
 * - 配色理论自动生成（基于基础颜色）
 */

/** 单个层级颜色配置 */
export interface LevelColorConfig {
  /** 节点填充色 */
  fill: string
  /** 节点边框色 */
  stroke: string
  /** 文字颜色 */
  color: string
}

/** 主题配置 */
export interface ThemeConfig {
  /** 主题ID */
  id: string
  /** 主题名称 */
  name: string
  /** 是否为预设主题 */
  preset?: boolean
  /** 是否为深色主题 */
  isDark?: boolean
  /** 是否为收藏主题 */
  favorite?: boolean
  /** 基础颜色（仅自定义主题） */
  baseColor?: string
  /** 配色方案（仅自定义主题） */
  schemeType?: ColorSchemeType
  /** 各层级颜色配置（最多7层） */
  levels: LevelColorConfig[]
  /** 连线颜色 */
  edgeColor: string
  /** 连线宽度 */
  edgeWidth: number
  /** 画布背景色 */
  backgroundColor: string
  /** 选中节点边框色 */
  selectedStroke: string
  /** 添加按钮颜色 */
  addButtonColor: string
}

/** 配色理论类型 */
export type ColorSchemeType = 
  | 'monochromatic'    // 单色系（同色相不同明度）
  | 'analogous'        // 类似色（相邻色相）
  | 'complementary'    // 互补色（对比色）
  | 'triadic'          // 三等色（三色均衡）
  | 'split-complementary' // 分裂互补色
  | 'tetradic'         // 四角配色

// ===== 工具函数 =====

/**
 * HSL 转 RGB
 */
function hslToRgb(h: number, s: number, l: number): [number, number, number] {
  h /= 360
  s /= 100
  l /= 100
  
  let r: number, g: number, b: number
  
  if (s === 0) {
    r = g = b = l
  } else {
    const hue2rgb = (p: number, q: number, t: number) => {
      if (t < 0) t += 1
      if (t > 1) t -= 1
      if (t < 1/6) return p + (q - p) * 6 * t
      if (t < 1/2) return q
      if (t < 2/3) return p + (q - p) * (2/3 - t) * 6
      return p
    }
    
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s
    const p = 2 * l - q
    r = hue2rgb(p, q, h + 1/3)
    g = hue2rgb(p, q, h)
    b = hue2rgb(p, q, h - 1/3)
  }
  
  return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
}

/**
 * RGB 转 HSL
 */
function rgbToHsl(r: number, g: number, b: number): [number, number, number] {
  r /= 255
  g /= 255
  b /= 255
  
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  let h: number = 0
  let s: number = 0
  const l: number = (max + min) / 2
  
  if (max !== min) {
    const d = max - min
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
    
    switch (max) {
      case r:
        h = ((g - b) / d + (g < b ? 6 : 0)) / 6
        break
      case g:
        h = ((b - r) / d + 2) / 6
        break
      case b:
        h = ((r - g) / d + 4) / 6
        break
    }
  }
  
  return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)]
}

/**
 * HEX 转 RGB
 */
export function hexToRgb(hex: string): [number, number, number] {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  if (!result) return [0, 0, 0]
  return [
    parseInt(result[1], 16),
    parseInt(result[2], 16),
    parseInt(result[3], 16)
  ]
}

/**
 * RGB 转 HEX
 */
export function rgbToHex(r: number, g: number, b: number): string {
  return '#' + [r, g, b].map(x => {
    const hex = x.toString(16)
    return hex.length === 1 ? '0' + hex : hex
  }).join('')
}

/**
 * 调整颜色明度
 */
function adjustLightness(hex: string, amount: number): string {
  const [r, g, b] = hexToRgb(hex)
  const [h, s, l] = rgbToHsl(r, g, b)
  const newL = Math.max(0, Math.min(100, l + amount))
  const [nr, ng, nb] = hslToRgb(h, s, newL)
  return rgbToHex(nr, ng, nb)
}

/**
 * 调整颜色饱和度
 */
function adjustSaturation(hex: string, amount: number): string {
  const [r, g, b] = hexToRgb(hex)
  const [h, s, l] = rgbToHsl(r, g, b)
  const newS = Math.max(0, Math.min(100, s + amount))
  const [nr, ng, nb] = hslToRgb(h, newS, l)
  return rgbToHex(nr, ng, nb)
}

/**
 * 根据配色理论生成颜色序列
 */
export function generateColorScheme(baseColor: string, schemeType: ColorSchemeType, levels: number = 7): string[] {
  const [r, g, b] = hexToRgb(baseColor)
  const [h, s, l] = rgbToHsl(r, g, b)
  const colors: string[] = []
  
  switch (schemeType) {
    case 'monochromatic': {
      // 单色系：同色相，不同明度
      // 从深到浅
      const lightStep = 50 / (levels - 1)
      for (let i = 0; i < levels; i++) {
        const lightness = Math.max(15, l + (i * lightStep) - 25)
        const [nr, ng, nb] = hslToRgb(h, s, lightness)
        colors.push(rgbToHex(nr, ng, nb))
      }
      break
    }
    
    case 'analogous': {
      // 类似色：相邻色相（30度范围内）
      const hueStep = 15 / (levels - 1)
      for (let i = 0; i < levels; i++) {
        const hue = (h - 15 + i * hueStep + 360) % 360
        const lightness = Math.max(20, l + i * 5 - 10)
        const [nr, ng, nb] = hslToRgb(hue, s, lightness)
        colors.push(rgbToHex(nr, ng, nb))
      }
      break
    }
    
    case 'complementary': {
      // 互补色：180度对比
      const complementH = (h + 180) % 360
      for (let i = 0; i < levels; i++) {
        const useComplement = i % 2 === 1
        const hue = useComplement ? complementH : h
        const lightness = Math.max(20, l + Math.floor(i / 2) * 8 - 10)
        const [nr, ng, nb] = hslToRgb(hue, s, lightness)
        colors.push(rgbToHex(nr, ng, nb))
      }
      break
    }
    
    case 'triadic': {
      // 三等色：120度间隔
      const h2 = (h + 120) % 360
      const h3 = (h + 240) % 360
      const hues = [h, h2, h3, h, h2, h3, h]
      for (let i = 0; i < levels; i++) {
        const lightness = Math.max(20, l + Math.floor(i / 3) * 10 - 5)
        const [nr, ng, nb] = hslToRgb(hues[i], s, lightness)
        colors.push(rgbToHex(nr, ng, nb))
      }
      break
    }
    
    case 'split-complementary': {
      // 分裂互补色：基础色 + 互补色两侧
      const h1 = (h + 150) % 360
      const h2 = (h + 210) % 360
      const hues = [h, h1, h2, h, h1, h2, h]
      for (let i = 0; i < levels; i++) {
        const lightness = Math.max(20, l + Math.floor(i / 3) * 10 - 5)
        const [nr, ng, nb] = hslToRgb(hues[i], s, lightness)
        colors.push(rgbToHex(nr, ng, nb))
      }
      break
    }
    
    case 'tetradic': {
      // 四角配色：90度间隔
      const h2 = (h + 90) % 360
      const h3 = (h + 180) % 360
      const h4 = (h + 270) % 360
      const hues = [h, h2, h3, h4, h, h2, h3]
      for (let i = 0; i < levels; i++) {
        const lightness = Math.max(20, l + Math.floor(i / 4) * 10 - 5)
        const [nr, ng, nb] = hslToRgb(hues[i], s, lightness)
        colors.push(rgbToHex(nr, ng, nb))
      }
      break
    }
    
    default:
      // 默认使用单色系
      return generateColorScheme(baseColor, 'monochromatic', levels)
  }
  
  return colors
}

/**
 * 根据基础颜色生成层级颜色配置
 */
export function generateLevelColors(baseColor: string, schemeType: ColorSchemeType): LevelColorConfig[] {
  const colors = generateColorScheme(baseColor, schemeType, 7)
  
  return colors.map(fill => {
    // 边框色稍亮
    const stroke = adjustLightness(fill, 15)
    // 判断填充色的明度，决定文字颜色
    const [r, g, b] = hexToRgb(fill)
    const [, , l] = rgbToHsl(r, g, b)
    const color = l < 55 ? '#ffffff' : '#1e293b'
    
    return { fill, stroke, color }
  })
}

// ===== 预设主题 =====

/** 所有系统预设主题 */
export const SYSTEM_THEMES: ThemeConfig[] = [
  {
    id: 'simple',
    name: 'Simple',
    preset: true,
    levels: [
      { fill: 'transparent', stroke: '#1e293b', color: '#0f172a' },  // 根节点：浓墨
      { fill: 'transparent', stroke: '#334155', color: '#1e293b' },  // 一级：重墨
      { fill: 'transparent', stroke: '#475569', color: '#1e293b' },  // 二级：中墨
      { fill: 'transparent', stroke: '#64748b', color: '#334155' },  // 三级：淡墨
      { fill: 'transparent', stroke: '#94a3b8', color: '#475569' },  // 四级：清墨
      { fill: 'transparent', stroke: '#94a3b8', color: '#475569' },  // 五级：清墨
      { fill: 'transparent', stroke: '#94a3b8', color: '#475569' }   // 六级+：清墨
    ],
    edgeColor: '#94a3b8',  // 淡灰蓝，契合水墨留白的退隐感
    edgeWidth: 2,
    backgroundColor: '#ffffff',
    selectedStroke: '#3b82f6',
    addButtonColor: '#3b82f6'
  },
  {
    id: 'forest-green',
    name: 'Forest Green',
    preset: true,
    levels: [
      { fill: '#1a4a3a', stroke: '#2a6a4a', color: '#ffffff' },
      { fill: '#2a6a4a', stroke: '#3a8a5a', color: '#ffffff' },
      { fill: '#3a8a5a', stroke: '#4aaa6a', color: '#ffffff' },
      { fill: '#4aaa6a', stroke: '#5aca7a', color: '#ffffff' },
      { fill: '#5aca7a', stroke: '#6aea8a', color: '#ffffff' },
      { fill: '#6aea8a', stroke: '#7afaaa', color: '#ffffff' },
      { fill: '#7afaaa', stroke: '#8affaa', color: '#1e293b' }
    ],
    edgeColor: '#5a8a7a',  // 低饱和绿，融入森林色系
    edgeWidth: 2,
    backgroundColor: '#f8fafc',
    selectedStroke: '#4a9cac',
    addButtonColor: '#4a9cac'
  },
  {
    id: 'ocean-blue',
    name: 'Ocean Blue',
    preset: true,
    levels: [
      { fill: '#1e3a5f', stroke: '#2a4a7f', color: '#ffffff' },
      { fill: '#1e40af', stroke: '#2563eb', color: '#ffffff' },
      { fill: '#2563eb', stroke: '#3b82f6', color: '#ffffff' },
      { fill: '#3b82f6', stroke: '#60a5fa', color: '#ffffff' },
      { fill: '#60a5fa', stroke: '#93c5fd', color: '#1e293b' },
      { fill: '#93c5fd', stroke: '#bfdbfe', color: '#1e293b' },
      { fill: '#bfdbfe', stroke: '#dbeafe', color: '#1e293b' }
    ],
    edgeColor: '#5a7a9a',  // 低饱和蓝，融入海洋色系
    edgeWidth: 2,
    backgroundColor: '#f8fafc',
    selectedStroke: '#0ea5e9',
    addButtonColor: '#0ea5e9'
  },
  {
    id: 'sunset-orange',
    name: 'Sunset Orange',
    preset: true,
    levels: [
      { fill: '#7c2d12', stroke: '#9a3412', color: '#ffffff' },
      { fill: '#c2410c', stroke: '#ea580c', color: '#ffffff' },
      { fill: '#ea580c', stroke: '#f97316', color: '#ffffff' },
      { fill: '#f97316', stroke: '#fb923c', color: '#ffffff' },
      { fill: '#fb923c', stroke: '#fdba74', color: '#1e293b' },
      { fill: '#fdba74', stroke: '#fed7aa', color: '#1e293b' },
      { fill: '#fed7aa', stroke: '#ffedd5', color: '#1e293b' }
    ],
    edgeColor: '#9a8a7a',  // 低饱和暖棕，融入落日色系
    edgeWidth: 2,
    backgroundColor: '#fefce8',
    selectedStroke: '#f97316',
    addButtonColor: '#ea580c'
  },
  {
    id: 'purple-violet',
    name: 'Purple Violet',
    preset: true,
    levels: [
      { fill: '#4c1d95', stroke: '#5b21b6', color: '#ffffff' },
      { fill: '#6d28d9', stroke: '#7c3aed', color: '#ffffff' },
      { fill: '#7c3aed', stroke: '#8b5cf6', color: '#ffffff' },
      { fill: '#8b5cf6', stroke: '#a78bfa', color: '#ffffff' },
      { fill: '#a78bfa', stroke: '#c4b5fd', color: '#1e293b' },
      { fill: '#c4b5fd', stroke: '#ddd6fe', color: '#1e293b' },
      { fill: '#ddd6fe', stroke: '#ede9fe', color: '#1e293b' }
    ],
    edgeColor: '#7a6a8a',  // 低饱和紫灰，融入紫色色系
    edgeWidth: 2,
    backgroundColor: '#faf5ff',
    selectedStroke: '#8b5cf6',
    addButtonColor: '#7c3aed'
  },
  {
 id: 'rose-pink',
    name: 'Rose Pink',
    preset: true,
    levels: [
      { fill: '#881337', stroke: '#9f1239', color: '#ffffff' },
      { fill: '#be123c', stroke: '#e11d48', color: '#ffffff' },
      { fill: '#e11d48', stroke: '#f43f5e', color: '#ffffff' },
      { fill: '#f43f5e', stroke: '#fb7185', color: '#ffffff' },
      { fill: '#fb7185', stroke: '#fda4af', color: '#1e293b' },
      { fill: '#fda4af', stroke: '#fecdd3', color: '#1e293b' },
      { fill: '#fecdd3', stroke: '#ffe4e6', color: '#1e293b' }
    ],
    edgeColor: '#9a7a8a',  // 低饱和玫灰，融入玫瑰色系
    edgeWidth: 2,
    backgroundColor: '#fff1f2',
    selectedStroke: '#f43f5e',
    addButtonColor: '#e11d48'
  },
  {
    id: 'teal-cyan',
    name: 'Teal Cyan',
    preset: true,
    levels: [
      { fill: '#134e4a', stroke: '#115e59', color: '#ffffff' },
      { fill: '#0f766e', stroke: '#0d9488', color: '#ffffff' },
      { fill: '#0d9488', stroke: '#14b8a6', color: '#ffffff' },
      { fill: '#14b8a6', stroke: '#2dd4bf', color: '#ffffff' },
      { fill: '#2dd4bf', stroke: '#5eead4', color: '#1e293b' },
      { fill: '#5eead4', stroke: '#99f6e4', color: '#1e293b' },
      { fill: '#99f6e4', stroke: '#ccfbf1', color: '#1e293b' }
    ],
    edgeColor: '#5a8a8a',  // 低饱和青灰，融入青色色系
    edgeWidth: 2,
    backgroundColor: '#f0fdfa',
    selectedStroke: '#14b8a6',
    addButtonColor: '#0d9488'
  },
  {
    id: 'dark-forest',
    name: 'Dark Forest',
    preset: true,
    isDark: true,
    levels: [
      { fill: '#0d2818', stroke: '#1a4a2e', color: '#ffffff' },
      { fill: '#134d2e', stroke: '#1a6839', color: '#ffffff' },
      { fill: '#1a6839', stroke: '#228b3b', color: '#ffffff' },
      { fill: '#228b3b', stroke: '#2fa449', color: '#ffffff' },
      { fill: '#2fa449', stroke: '#3dc95c', color: '#1e293b' },
      { fill: '#3dc95c', stroke: '#4ade80', color: '#1e293b' },
      { fill: '#4ade80', stroke: '#6ee7a0', color: '#1e293b' }
    ],
    edgeColor: '#2a4a3a',  // 深林绿，暗色背景下的森林色系
    edgeWidth: 2,
    backgroundColor: '#0f172a',
    selectedStroke: '#22d3ee',
    addButtonColor: '#10b981'
  },
  {
    id: 'dark-ocean',
    name: 'Dark Ocean',
    preset: true,
    isDark: true,
    levels: [
      { fill: '#0c1929', stroke: '#1e3a5f', color: '#ffffff' },
      { fill: '#1e3a5f', stroke: '#1e40af', color: '#ffffff' },
      { fill: '#1e40af', stroke: '#2563eb', color: '#ffffff' },
      { fill: '#2563eb', stroke: '#3b82f6', color: '#ffffff' },
      { fill: '#3b82f6', stroke: '#60a5fa', color: '#ffffff' },
      { fill: '#60a5fa', stroke: '#93c5fd', color: '#1e293b' },
      { fill: '#93c5fd', stroke: '#bfdbfe', color: '#1e293b' }
    ],
    edgeColor: '#1e3a5f',  // 深海蓝，暗色背景下的海洋色系
    edgeWidth: 2,
    backgroundColor: '#0f172a',
    selectedStroke: '#38bdf8',
    addButtonColor: '#3b82f6'
  }
]

/** 兼容旧代码 */
export const PRESET_THEMES = SYSTEM_THEMES
export const DARK_THEMES = SYSTEM_THEMES.filter(t => t.isDark)
export const ALL_PRESET_THEMES = SYSTEM_THEMES

/**
 * 根据ID获取主题配置（从系统主题和收藏主题中查找）
 */
export function getThemeById(id: string): ThemeConfig | undefined {
  // 先从系统主题查找
  const systemTheme = SYSTEM_THEMES.find(t => t.id === id)
  if (systemTheme) return systemTheme
  
  // 再从收藏主题查找
  const favorites = loadFavoriteThemes()
  return favorites.find(t => t.id === id)
}

/**
 * 创建自定义主题
 */
export function createCustomTheme(
  baseColor: string,
  schemeType: ColorSchemeType,
  levelOverrides?: Record<number, LevelColorConfig>,
  options: Partial<ThemeConfig> = {}
): ThemeConfig {
  const generated = generateLevelColors(baseColor, schemeType)
  // 合并层级覆盖
  const levels = generated.map((c, i) => levelOverrides?.[i] || c)
  
  // 根据基础颜色判断明暗模式
  const [r, g, b] = hexToRgb(baseColor)
  const [, , l] = rgbToHsl(r, g, b)
  const isDark = l < 40
  
  return {
    id: `custom-${Date.now()}`,
    name: 'Custom',
    preset: false,
    isDark,
    baseColor,
    schemeType,
    levels,
    edgeColor: adjustSaturation(adjustLightness(baseColor, isDark ? -20 : -10), isDark ? -40 : -50),
    edgeWidth: 2,
    backgroundColor: isDark ? '#0f172a' : '#f8fafc',
    selectedStroke: adjustLightness(baseColor, 30),
    addButtonColor: baseColor,
    ...options
  }
}

/**
 * 主题配置存储键
 */
const THEME_STORAGE_KEY = 'mindmap-theme-config'

/**
 * 保存主题配置到本地存储
 */
export function saveThemeConfig(theme: ThemeConfig): void {
  try {
    localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(theme))
  } catch (e) {
    console.error('Failed to save theme config:', e)
  }
}

/**
 * 从本地存储加载主题配置
 */
export function loadThemeConfig(): ThemeConfig | null {
  try {
    const saved = localStorage.getItem(THEME_STORAGE_KEY)
    if (saved) {
      return JSON.parse(saved) as ThemeConfig
    }
  } catch (e) {
    console.error('Failed to load theme config:', e)
  }
  return null
}

/**
 * 收藏主题列表存储键
 */
const FAVORITES_STORAGE_KEY = 'mindmap-favorite-themes'

/**
 * 生成收藏主题ID（基于配置）
 */
function generateFavoriteThemeId(baseColor: string, schemeType: ColorSchemeType): string {
  return `favorite-${baseColor.slice(1)}-${schemeType}`
}

/**
 * 保存主题到收藏列表
 */
export function saveToFavoriteThemes(theme: ThemeConfig): void {
  try {
    const favorites = loadFavoriteThemes()
    // 使用固定ID（基于配置）
    const themeWithFixedId = {
      ...theme,
      id: generateFavoriteThemeId(theme.baseColor || '', theme.schemeType || 'monochromatic'),
      favorite: true
    }
    
    // 检查是否已存在
    const existingIndex = favorites.findIndex(t => t.id === themeWithFixedId.id)
    
    if (existingIndex >= 0) {
      // 已存在，更新
      favorites[existingIndex] = themeWithFixedId
    } else {
      // 不存在，添加
      favorites.push(themeWithFixedId)
    }
    
    localStorage.setItem(FAVORITES_STORAGE_KEY, JSON.stringify(favorites))
  } catch (e) {
    console.error('Failed to save favorite theme:', e)
  }
}

/**
 * 从收藏列表移除主题
 */
export function removeFromFavoriteThemes(themeId: string): void {
  try {
    const favorites = loadFavoriteThemes()
    const filtered = favorites.filter(t => t.id !== themeId)
    localStorage.setItem(FAVORITES_STORAGE_KEY, JSON.stringify(filtered))
  } catch (e) {
    console.error('Failed to remove favorite theme:', e)
  }
}

/**
 * 加载收藏主题列表
 */
export function loadFavoriteThemes(): ThemeConfig[] {
  try {
    const saved = localStorage.getItem(FAVORITES_STORAGE_KEY)
    if (saved) {
      return JSON.parse(saved) as ThemeConfig[]
    }
  } catch (e) {
    console.error('Failed to load favorite themes:', e)
  }
  return []
}

/**
 * 检查主题是否在收藏列表中
 */
export function isThemeInFavorites(theme: ThemeConfig): boolean {
  const favorites = loadFavoriteThemes()
  const themeId = generateFavoriteThemeId(theme.baseColor || '', theme.schemeType || 'monochromatic')
  return favorites.some(t => t.id === themeId)
}
