<template>
  <!-- ═══ 外观设置(主题 / 语言 / AI 语言 / Token 用量)═══ -->
  <section class="panel">
    <div class="panel-header">
      <h2>{{ $t('settings.sectionAppearance') }}</h2>
    </div>
    <div class="general-settings">
      <SettingRow ref="rowTheme" :label="$t('settings.labelTheme')" :desc="$t('settings.descTheme')">
        <select v-model="settings.theme" class="setting-select" @change="markSaved('theme')">
          <option value="dark">{{ $t('settings.themeDark') }}</option>
          <option value="light">{{ $t('settings.themeLight') }}</option>
          <option value="system">{{ $t('settings.themeSystem') }}</option>
        </select>
      </SettingRow>
      <SettingRow ref="rowLanguage" :label="$t('settings.labelLanguage')" :desc="$t('settings.descLanguage')">
        <select v-model="settings.language" class="setting-select" @change="markSaved('language')">
          <option value="zh-CN">{{ $t('settings.aiLanguageZh') }}</option>
          <option value="en">{{ $t('settings.aiLanguageEn') }}</option>
        </select>
      </SettingRow>
      <SettingRow ref="rowAiLanguage" :label="$t('settings.labelAiLanguage')" :desc="$t('settings.descAiLanguage')">
        <select v-model="settings.aiLanguage" class="setting-select" @change="markSaved('aiLanguage')">
          <option value="auto">{{ $t('settings.aiLanguageAuto') }}</option>
          <option value="zh-CN">{{ $t('settings.aiLanguageZh') }}</option>
          <option value="en">{{ $t('settings.aiLanguageEn') }}</option>
        </select>
      </SettingRow>
      <SettingRow ref="rowToken" :label="$t('settings.labelShowTokenUsage')" :desc="$t('settings.descShowTokenUsage')">
        <label class="toggle">
          <input type="checkbox" v-model="settings.showTokenUsage" @change="markSaved('token')" />
          <span class="toggle-slider"></span>
        </label>
      </SettingRow>
      <SettingRow ref="rowStreamingMd" :label="$t('settings.labelStreamingMd')" :desc="$t('settings.descStreamingMd')">
        <label class="toggle">
          <input type="checkbox" v-model="settings.streamingMd" @change="markSaved('streamingMd')" />
          <span class="toggle-slider"></span>
        </label>
      </SettingRow>
    </div>
  </section>
</template>

<script setup lang="ts">
import { reactive, watch, onMounted, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppSettingsStore } from '@/stores/appSettings'
import SettingRow from './SettingRow.vue'

// ============================================================
// 外观域 — 本地设置(localStorage):主题 / 界面语言 / AI 语言 / Token 用量显隐
// 拆自 GeneralPanel,本 Section 仅持有外观相关 key
// 阶段5:SettingRow 封装行布局,控件变更后调 markSaved 显"已保存"
// ============================================================
const appSettings = useAppSettingsStore()
const { locale } = useI18n()

const settings = reactive({
  theme: appSettings.get<string>('df-theme', 'dark'),
  language: appSettings.get<string>('df-language', 'zh-CN'),
  aiLanguage: appSettings.get<string>('df-ai-language', 'auto'),
  showTokenUsage: appSettings.get<boolean>('df-show-token-usage', false),
  // AR-1 流式 Markdown 渲染开关:默认 true(流式过程渲染代码块/列表/标题格式);
  // 关 → 回退纯文本(防掉帧/性能敏感场景降级)
  streamingMd: appSettings.get<boolean>('df-ai-streaming-md', true),
})

function applyTheme(theme: string) {
  if (theme === 'system') {
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    document.documentElement.removeAttribute('data-theme')
    if (!prefersDark) document.documentElement.setAttribute('data-theme', 'light')
  } else if (theme === 'light') {
    document.documentElement.setAttribute('data-theme', 'light')
  } else {
    document.documentElement.removeAttribute('data-theme')
  }
}

// 即时生效反馈:SettingRow refs,key 映射对应 row
const rowTheme = useTemplateRef<InstanceType<typeof SettingRow>>('rowTheme')
const rowLanguage = useTemplateRef<InstanceType<typeof SettingRow>>('rowLanguage')
const rowAiLanguage = useTemplateRef<InstanceType<typeof SettingRow>>('rowAiLanguage')
const rowToken = useTemplateRef<InstanceType<typeof SettingRow>>('rowToken')
const rowStreamingMd = useTemplateRef<InstanceType<typeof SettingRow>>('rowStreamingMd')
function markSaved(key: 'theme' | 'language' | 'aiLanguage' | 'token' | 'streamingMd') {
  const map = { theme: rowTheme.value, language: rowLanguage.value, aiLanguage: rowAiLanguage.value, token: rowToken.value, streamingMd: rowStreamingMd.value }
  map[key]?.markSaved()
}

watch(() => settings.theme, (val) => {
  applyTheme(val)
  void appSettings.set('df-theme', val)
})

watch(() => settings.aiLanguage, (val) => {
  void appSettings.set('df-ai-language', val)
})

watch(() => settings.showTokenUsage, (val) => {
  void appSettings.set('df-show-token-usage', val)
})

watch(() => settings.streamingMd, (val) => {
  void appSettings.set('df-ai-streaming-md', val)
})

watch(() => settings.language, (val) => {
  void appSettings.set('df-language', val)
  // 同步 i18n 实例，让界面立即跟随语言切换
  locale.value = val as 'zh-CN' | 'en'
})

onMounted(() => {
  applyTheme(settings.theme)
})
</script>

<style scoped>
/* 阶段5 UX 重构:复用 settings.css 全局 .panel/.panel-header/.general-settings/
   .setting-select/.toggle/.toggle-slider + SettingRow(封装 .setting-row/.setting-info/
   .setting-label/.setting-desc/.setting-control)。本 Section 无特有 scoped 样式。 */
</style>
