import { defineStore } from 'pinia'

import {
  DEFAULT_THEME_ID,
  LEGACY_THEMES,
  PRIMARY_THEMES,
  applyThemeVars,
  findTheme,
  resolveThemeId,
  THEMES,
  type ThemePreset
} from '@/styles/themes'
import {
  mergeThemePreset,
  type ThemeColorKey,
  type ThemeColorOverrides,
  type ThemeOverridesMap
} from '@/styles/themeCustomize'

interface UiState {
  sidebarCollapsed: boolean
  /**
   * @deprecated 仅保留兼容字段；实际外观由 themeId 决定，可于下一个迁移窗口删除。
   * 旧 localStorage 里可能仍残留 'light' / 'dark'，反序列化时容错读取。
   */
  theme: 'light' | 'dark'
  /** 主题色板 ID（对应 themes.ts 的 ThemePreset.id） */
  themeId: string
  /** 各主题取色盘自定义（仅存三项品牌色，其余由 derive 推导） */
  themeOverrides: ThemeOverridesMap
}

const STORAGE_KEY = 'simple.ui.state'
/** Outpost 壳层上线：旧本地主题只换了 id、观感几乎不变 → 升 schema 强制一次默认浅色 */
const THEME_SCHEMA_KEY = 'simple.ui.themeSchema'
const THEME_SCHEMA_VERSION = 2

const DEFAULT_STATE: UiState = {
  sidebarCollapsed: false,
  theme: 'light',
  themeId: DEFAULT_THEME_ID,
  themeOverrides: {}
}

function loadInitial(): UiState {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) {
      localStorage.setItem(THEME_SCHEMA_KEY, String(THEME_SCHEMA_VERSION))
      return { ...DEFAULT_STATE }
    }
    const parsed = JSON.parse(raw) as Partial<UiState>
    let themeId = resolveThemeId(parsed.themeId ?? DEFAULT_STATE.themeId)
    const schema = Number(localStorage.getItem(THEME_SCHEMA_KEY) || '0')
    const migrated = schema < THEME_SCHEMA_VERSION
    if (migrated) {
      // ponytail: 一次强制 outpost-light，兼容主题仍可从高级菜单切回
      themeId = DEFAULT_THEME_ID
      localStorage.setItem(THEME_SCHEMA_KEY, String(THEME_SCHEMA_VERSION))
    }
    const state: UiState = {
      sidebarCollapsed: parsed.sidebarCollapsed ?? DEFAULT_STATE.sidebarCollapsed,
      theme: parsed.theme === 'dark' ? 'dark' : 'light',
      themeId,
      themeOverrides: parsed.themeOverrides ?? {}
    }
    if (migrated) {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(state))
      } catch {
        /* ignore */
      }
    }
    return state
  } catch (err) {
    console.warn('[ui.store] localStorage 中的 UI 状态解析失败，已回退默认：', err)
    return { ...DEFAULT_STATE }
  }
}

export const useUiStore = defineStore('ui', {
  state: (): UiState => loadInitial(),
  getters: {
    /** 当前生效的主题预设（含自定义配色） */
    activeTheme(state): ThemePreset {
      return mergeThemePreset(findTheme(state.themeId), state.themeOverrides[state.themeId])
    },
    /** 顶栏精选主题（浅色 / 紫色 / 蓝色） */
    availableThemes(): ThemePreset[] {
      return PRIMARY_THEMES
    },
    /** 高级 → 兼容主题（旧深色霓虹） */
    legacyThemes(): ThemePreset[] {
      return LEGACY_THEMES
    },
    /** 全量（自定义配色等内部用） */
    allThemes(): ThemePreset[] {
      return THEMES
    }
  },
  actions: {
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
      this.persist()
    },

    setTheme(t: 'light' | 'dark') {
      this.theme = t
      document.documentElement.classList.toggle('dark', t === 'dark')
      this.persist()
    },

    getMergedTheme(preset: ThemePreset): ThemePreset {
      return mergeThemePreset(preset, this.themeOverrides[preset.id])
    },

    getThemeColor(themeId: string, key: ThemeColorKey): string {
      const preset = findTheme(themeId)
      return this.themeOverrides[themeId]?.[key] ?? preset.vars[key]
    },

    setThemeColor(themeId: string, key: ThemeColorKey, hex: string) {
      if (!this.themeOverrides[themeId]) this.themeOverrides[themeId] = {}
      this.themeOverrides[themeId][key] = hex
      if (this.themeId === themeId) {
        applyThemeVars(this.getMergedTheme(findTheme(themeId)))
      }
      this.persist()
    },

    clearThemeOverrides(themeId: string) {
      delete this.themeOverrides[themeId]
      if (this.themeId === themeId) applyThemeVars(findTheme(themeId))
      this.persist()
    },

    clearAllThemeOverrides() {
      this.themeOverrides = {}
      applyThemeVars(this.activeTheme)
      this.persist()
    },

    /** 切换品牌主题色板（精选或兼容均可） */
    setThemeId(id: string) {
      const preset = findTheme(id)
      this.themeId = preset.id
      applyThemeVars(this.getMergedTheme(preset))
      this.persist()
    },

    /** 应用当前已保存的主题（启动时调用） */
    applyCurrentTheme() {
      applyThemeVars(this.activeTheme)
    },

    /** 仅持久化稳定字段，避免把瞬态/敏感字段误写入 localStorage。 */
    persist() {
      const snapshot: UiState = {
        sidebarCollapsed: this.sidebarCollapsed,
        theme: this.theme,
        themeId: this.themeId,
        themeOverrides: this.themeOverrides
      }
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot))
      } catch (err) {
        console.warn('[ui.store] 持久化 UI 状态失败：', err)
      }
    }
  }
})
