import { lightTheme } from './light'
import { darkTheme } from './dark'

export type ThemeMode = 'light' | 'dark'

export type ThemeColors = Record<string, string>

export { lightTheme, darkTheme }

const THEME_MODE_KEY = 'app-theme-mode'

function setCssVars(colors: ThemeColors) {
	const root = document.documentElement
	Object.entries(colors).forEach(([key, value]) => {
		// 设置 Element Plus 颜色变量
		root.style.setProperty(`--el-color-${key}`, value)
		// 同时设置通用变量（去掉 el-color- 前缀）
		root.style.setProperty(`--${key}`, value)
	})
}

export function applyTheme(mode: ThemeMode, colors?: ThemeColors) {
	const colorMap = !colors ? (mode === 'dark' ? darkTheme : lightTheme) : colors
	setCssVars(colorMap)

	const html = document.documentElement
	html.classList.toggle('dark', mode === 'dark')

	localStorage.setItem(THEME_MODE_KEY, mode)
}

export function initTheme(customLight?: ThemeColors, customDark?: ThemeColors) {
	const mode = (localStorage.getItem(THEME_MODE_KEY) as ThemeMode) || 'light'
	const lightColors = customLight || lightTheme
	const darkColors = customDark || darkTheme

	applyTheme(mode, mode === 'dark' ? darkColors : lightColors)

	return mode
}
