<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { 
  Settings, 
  Languages, 
  Send, 
  Copy, 
  Trash2, 
  ArrowRightLeft,
  Loader2,
  Check,
  FileText,
  ChevronDown,
  Sun,
  Moon,
  User,
  Type,
  Plus,
  Save,
  Play
} from 'lucide-vue-next';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { 
  useSettingsStore, 
  LANGUAGES, 
  DEFAULT_TEMPLATE,
  SPEAKER_IDENTITY_OPTIONS,
  TONE_REGISTER_OPTIONS,
  type ApiProfile
} from './stores/settings';
import pkg from '../package.json';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';

function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

const settings = useSettingsStore();

// Theme management
watch(() => settings.isDark, (val) => {
  if (val) {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
}, { immediate: true });

const toggleTheme = () => {
  settings.isDark = !settings.isDark;
};

const view = ref<'translate' | 'settings' | 'logs'>('translate');

// Profile Management
const newProfileName = ref('');
const isSavingProfile = ref(false);

const saveCurrentAsProfile = () => {
  if (!newProfileName.value.trim()) return;
  
  const newProfile: ApiProfile = {
    id: crypto.randomUUID(),
    name: newProfileName.value.trim(),
    apiBaseUrl: settings.apiBaseUrl,
    apiKey: settings.apiKey,
    modelName: settings.modelName
  };
  
  settings.profiles.push(newProfile);
  newProfileName.value = '';
  isSavingProfile.value = false;
};

const applyProfile = (p: ApiProfile) => {
  settings.apiBaseUrl = p.apiBaseUrl;
  settings.apiKey = p.apiKey;
  settings.modelName = p.modelName;
};

const deleteProfile = (id: string) => {
  settings.profiles = settings.profiles.filter(p => p.id !== id);
};

// Dropdown State
const sourceDropdownOpen = ref(false);
const targetDropdownOpen = ref(false);
const speakerDropdownOpen = ref(false);
const toneDropdownOpen = ref(false);

const closeAllDropdowns = () => {
  sourceDropdownOpen.value = false;
  targetDropdownOpen.value = false;
  speakerDropdownOpen.value = false;
  toneDropdownOpen.value = false;
};

const toggleDropdown = (type: 'source' | 'target' | 'speaker' | 'tone') => {
  const states = {
    source: sourceDropdownOpen,
    target: targetDropdownOpen,
    speaker: speakerDropdownOpen,
    tone: toneDropdownOpen
  };
  
  const targetState = states[type];
  const currentValue = targetState.value;
  
  closeAllDropdowns();
  targetState.value = !currentValue;
};

const handleGlobalClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  if (!target.closest('.lang-dropdown')) {
    closeAllDropdowns();
  }
};

onMounted(() => {
  window.addEventListener('click', handleGlobalClick);
});

onUnmounted(() => {
  window.removeEventListener('click', handleGlobalClick);
});

// Translation State
const sourceText = ref('');
const targetText = ref('');
const isTranslating = ref(false);
const showCopyFeedback = ref(false);

let unlisten: (() => void) | null = null;

onMounted(async () => {
  unlisten = await listen<string>('translation-chunk', (event) => {
    if (isTranslating.value) {
      targetText.value += event.payload;
    }
  });
});

onUnmounted(() => {
  if (unlisten) unlisten();
});

// Language Selection
const sourceLangCode = computed({
  get: () => settings.sourceLang.code,
  set: (code) => {
    const lang = LANGUAGES.find(l => l.code === code);
    if (lang) settings.sourceLang = lang;
  }
});

const targetLangCode = computed({
  get: () => settings.targetLang.code,
  set: (code) => {
    const lang = LANGUAGES.find(l => l.code === code);
    if (lang) settings.targetLang = lang;
  }
});

const sourceLang = computed(() => settings.sourceLang);
const targetLang = computed(() => settings.targetLang);

const currentSpeakerLabel = computed(() => {
  return SPEAKER_IDENTITY_OPTIONS.find(opt => opt.value === settings.speakerIdentity)?.label || '男性';
});

const currentToneLabel = computed(() => {
  return TONE_REGISTER_OPTIONS.find(opt => opt.value === settings.toneRegister)?.label || '正式专业';
});

const swapLanguages = () => {
  const temp = { ...settings.sourceLang };
  settings.sourceLang = { ...settings.targetLang };
  settings.targetLang = temp;
};

const clearSource = () => {
  sourceText.value = '';
  targetText.value = '';
};

const copyTarget = async () => {
  try {
    await navigator.clipboard.writeText(targetText.value);
    showCopyFeedback.value = true;
    setTimeout(() => {
      showCopyFeedback.value = false;
    }, 2000);
  } catch (err) {
    console.error('Failed to copy text: ', err);
  }
};

const translate = async () => {
  if (!sourceText.value.trim() || isTranslating.value) return;

  isTranslating.value = true;
  targetText.value = '';

  const prompt = settings.systemPromptTemplate
    .replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
    .replace(/{SOURCE_CODE}/g, sourceLang.value.code)
    .replace(/{TARGET_LANG}/g, targetLang.value.englishName)
    .replace(/{TARGET_CODE}/g, targetLang.value.code)
    .replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
    .replace(/{TONE_REGISTER}/g, settings.toneRegister)
    .replace(/{TEXT}/g, sourceText.value);

  const requestBody = {
    model: settings.modelName,
    messages: [
      { role: "user", content: prompt }
    ],
    stream: settings.enableStreaming
  };

  settings.addLog('request', requestBody);

  try {
    const response = await invoke<string>('translate', {
      apiAddress: settings.apiBaseUrl,
      apiKey: settings.apiKey,
      payload: requestBody
    });
    
    // For non-streaming, response is returned as string
    if (!settings.enableStreaming) {
      targetText.value = response;
    }
    settings.addLog('response', 'Translation completed');
  } catch (err: any) {
    const errorMsg = String(err);
    settings.addLog('error', errorMsg);
    targetText.value = `Error: ${errorMsg}`;
  } finally {
    isTranslating.value = false;
  }
};
</script>

<template>
  <div class="h-screen bg-slate-50 dark:bg-slate-950 text-slate-900 dark:text-slate-100 font-sans selection:bg-blue-100 dark:selection:bg-blue-900 flex flex-col overflow-hidden">
    <!-- Header -->
    <header class="h-14 border-b dark:border-slate-800 bg-white dark:bg-slate-900 flex items-center justify-between px-6 shrink-0 sticky top-0 z-10 shadow-sm">
      <div class="flex items-center gap-2 cursor-pointer group" @click="view = 'translate'">
        <Languages class="w-6 h-6 text-blue-600 group-hover:scale-110 transition-transform" />
        <h1 class="font-semibold text-lg tracking-tight">AI 翻译</h1>
      </div>
      <div class="flex items-center gap-2">
        <button 
          @click="toggleTheme"
          class="p-2 rounded-full transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300"
          :title="settings.isDark ? '切换亮色主题' : '切换暗色主题'"
        >
          <Sun v-if="settings.isDark" class="w-5 h-5" />
          <Moon v-else class="w-5 h-5" />
        </button>
        <button 
          @click="view = 'settings'"
          :class="cn('p-2 rounded-full transition-colors', view === 'settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300')"
          title="设置"
        >
          <Settings class="w-5 h-5" />
        </button>
        <button 
          @click="view = 'logs'"
          :class="cn('p-2 rounded-full transition-colors', view === 'logs' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300')"
          title="调试日志"
        >
          <FileText class="w-5 h-5" />
        </button>
      </div>
    </header>

    <main class="flex-1 flex overflow-hidden min-h-0 relative">
      <!-- Translation View -->
      <div v-if="view === 'translate'" class="flex-1 flex flex-col md:flex-row divide-y md:divide-y-0 md:divide-x dark:divide-slate-800 bg-white dark:bg-slate-900 overflow-hidden h-full">
        <!-- Source Pane -->
        <div class="flex-1 flex flex-col min-h-0 relative h-full">
          <div class="flex items-center gap-3 px-6 py-3 border-b dark:border-slate-800 bg-slate-50/50 dark:bg-slate-800/30 relative z-40 shrink-0">
            <!-- Custom Source Dropdown -->
            <div class="relative lang-dropdown min-w-30">
              <button 
                @click.stop="toggleDropdown('source')"
                class="flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-slate-200/60 dark:hover:bg-slate-700/60 transition-colors text-sm font-semibold text-slate-700 dark:text-slate-200 w-full justify-between group"
              >
                <span class="truncate">{{ sourceLang.displayName }}</span>
                <ChevronDown :class="cn('w-4 h-4 text-slate-400 transition-transform duration-200', sourceDropdownOpen && 'rotate-180')" />
              </button>
              
              <!-- Dropdown Menu -->
              <transition
                enter-active-class="transition duration-100 ease-out"
                enter-from-class="transform scale-95 opacity-0"
                enter-to-class="transform scale-100 opacity-100"
                leave-active-class="transition duration-75 ease-in"
                leave-from-class="transform scale-100 opacity-100"
                leave-to-class="transform scale-95 opacity-0"
              >
                <div 
                  v-if="sourceDropdownOpen"
                  class="absolute left-0 mt-2 w-56 max-h-80 overflow-y-auto bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 z-50 py-2 flex flex-col custom-scrollbar"
                >
                  <button
                    v-for="lang in LANGUAGES"
                    :key="lang.code"
                    @click="sourceLangCode = lang.code; sourceDropdownOpen = false"
                    :class="cn(
                      'px-4 py-2.5 text-sm text-left transition-colors flex items-center justify-between',
                      sourceLangCode === lang.code ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 font-bold' : 'text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700/50'
                    )"
                  >
                    {{ lang.displayName }}
                    <Check v-if="sourceLangCode === lang.code" class="w-3.5 h-3.5" />
                  </button>
                </div>
              </transition>
            </div>

            <button @click="swapLanguages" class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-md transition-colors" title="交换语言">
              <ArrowRightLeft class="w-4 h-4 text-slate-500 dark:text-slate-400" />
            </button>
            <div class="ml-auto flex items-center gap-2">
               <button @click="clearSource" class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-md transition-colors" title="清空内容">
                <Trash2 class="w-4 h-4 text-slate-500 dark:text-slate-400" />
              </button>
            </div>
          </div>
          <textarea
            v-model="sourceText"
            placeholder="请输入待翻译内容..."
            class="flex-1 p-6 resize-none outline-none text-lg leading-relaxed placeholder:text-slate-300 dark:placeholder:text-slate-600 bg-transparent min-h-0"
          ></textarea>
          <div class="p-4 border-t dark:border-slate-800 flex justify-end shrink-0">
            <button 
              @click="translate"
              :disabled="isTranslating || !sourceText.trim()"
              class="bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 dark:disabled:bg-blue-900/40 text-white px-6 py-2.5 rounded-lg font-medium transition-all flex items-center gap-2 shadow-sm"
            >
              <Loader2 v-if="isTranslating" class="w-4 h-4 animate-spin" />
              <Send v-else class="w-4 h-4" />
              {{ isTranslating ? '正在翻译...' : '翻译' }}
            </button>
          </div>
        </div>

        <!-- Target Pane -->
        <div class="flex-1 flex flex-col min-h-0 bg-slate-50/30 dark:bg-slate-900/50 relative h-full">
          <div class="flex items-center gap-3 px-6 py-3 border-b dark:border-slate-800 bg-slate-50/50 dark:bg-slate-800/30 relative z-40 shrink-0">
            <!-- Custom Target Dropdown -->
            <div class="relative lang-dropdown min-w-30">
              <button 
                @click.stop="toggleDropdown('target')"
                class="flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-slate-200/60 dark:hover:bg-slate-700/60 transition-colors text-sm font-semibold text-slate-700 dark:text-slate-200 w-full justify-between"
              >
                <span class="truncate">{{ targetLang.displayName }}</span>
                <ChevronDown :class="cn('w-4 h-4 text-slate-400 transition-transform duration-200', targetDropdownOpen && 'rotate-180')" />
              </button>
              
              <!-- Dropdown Menu -->
              <transition
                enter-active-class="transition duration-100 ease-out"
                enter-from-class="transform scale-95 opacity-0"
                enter-to-class="transform scale-100 opacity-100"
                leave-active-class="transition duration-75 ease-in"
                leave-from-class="transform scale-100 opacity-100"
                leave-to-class="transform scale-95 opacity-0"
              >
                <div 
                  v-if="targetDropdownOpen"
                  class="absolute left-0 mt-2 w-56 max-h-80 overflow-y-auto bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 z-50 py-2 flex flex-col custom-scrollbar"
                >
                  <button
                    v-for="lang in LANGUAGES"
                    :key="lang.code"
                    @click="targetLangCode = lang.code; targetDropdownOpen = false"
                    :class="cn(
                      'px-4 py-2.5 text-sm text-left transition-colors flex items-center justify-between',
                      targetLangCode === lang.code ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 font-bold' : 'text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700/50'
                    )"
                  >
                    {{ lang.displayName }}
                    <Check v-if="targetLangCode === lang.code" class="w-3.5 h-3.5" />
                  </button>
                </div>
              </transition>
            </div>

            <!-- Speaker Identity Dropdown -->
            <div class="relative lang-dropdown min-w-24">
              <button 
                @click.stop="toggleDropdown('speaker')"
                class="flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-slate-200/60 dark:hover:bg-slate-700/60 transition-colors text-sm font-medium text-slate-600 dark:text-slate-300 w-full justify-between group"
                title="说话人身份"
              >
                <div class="flex items-center gap-1.5 truncate">
                  <User class="w-3.5 h-3.5 text-slate-400" />
                  <span class="truncate">{{ currentSpeakerLabel }}</span>
                </div>
                <ChevronDown :class="cn('w-3.5 h-3.5 text-slate-400 transition-transform duration-200 shrink-0', speakerDropdownOpen && 'rotate-180')" />
              </button>
              
              <transition
                enter-active-class="transition duration-100 ease-out"
                enter-from-class="transform scale-95 opacity-0"
                enter-to-class="transform scale-100 opacity-100"
                leave-active-class="transition duration-75 ease-in"
                leave-from-class="transform scale-100 opacity-100"
                leave-to-class="transform scale-95 opacity-0"
              >
                <div 
                  v-if="speakerDropdownOpen"
                  class="absolute left-0 mt-2 w-40 max-h-80 overflow-y-auto bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 z-50 py-2 flex flex-col custom-scrollbar"
                >
                  <button
                    v-for="opt in SPEAKER_IDENTITY_OPTIONS"
                    :key="opt.value"
                    @click="settings.speakerIdentity = opt.value; speakerDropdownOpen = false"
                    :class="cn(
                      'px-4 py-2 text-sm text-left transition-colors flex items-center justify-between',
                      settings.speakerIdentity === opt.value ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 font-bold' : 'text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700/50'
                    )"
                  >
                    {{ opt.label }}
                    <Check v-if="settings.speakerIdentity === opt.value" class="w-3.5 h-3.5" />
                  </button>
                </div>
              </transition>
            </div>

            <!-- Tone & Register Dropdown -->
            <div class="relative lang-dropdown min-w-32">
              <button 
                @click.stop="toggleDropdown('tone')"
                class="flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-slate-200/60 dark:hover:bg-slate-700/60 transition-colors text-sm font-medium text-slate-600 dark:text-slate-300 w-full justify-between group"
                title="语气风格"
              >
                <div class="flex items-center gap-1.5 truncate">
                  <Type class="w-3.5 h-3.5 text-slate-400" />
                  <span class="truncate">{{ currentToneLabel }}</span>
                </div>
                <ChevronDown :class="cn('w-3.5 h-3.5 text-slate-400 transition-transform duration-200 shrink-0', toneDropdownOpen && 'rotate-180')" />
              </button>
              
              <transition
                enter-active-class="transition duration-100 ease-out"
                enter-from-class="transform scale-95 opacity-0"
                enter-to-class="transform scale-100 opacity-100"
                leave-active-class="transition duration-75 ease-in"
                leave-from-class="transform scale-100 opacity-100"
                leave-to-class="transform scale-95 opacity-0"
              >
                <div 
                  v-if="toneDropdownOpen"
                  class="absolute left-0 mt-2 w-56 max-h-80 overflow-y-auto bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 z-50 py-2 flex flex-col custom-scrollbar"
                >
                  <button
                    v-for="opt in TONE_REGISTER_OPTIONS"
                    :key="opt.value"
                    @click="settings.toneRegister = opt.value; toneDropdownOpen = false"
                    :class="cn(
                      'px-4 py-2.5 text-sm text-left transition-colors flex flex-col gap-0.5',
                      settings.toneRegister === opt.value ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 font-bold' : 'text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700/50'
                    )"
                  >
                    <div class="flex items-center justify-between w-full">
                      {{ opt.label }}
                      <Check v-if="settings.toneRegister === opt.value" class="w-3.5 h-3.5" />
                    </div>
                    <span class="text-[10px] opacity-60 font-normal truncate">{{ opt.description }}</span>
                  </button>
                </div>
              </transition>
            </div>

            <div class="ml-auto flex items-center gap-2">
              <button @click="copyTarget" class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-md transition-colors relative" title="复制结果">
                <Check v-if="showCopyFeedback" class="w-4 h-4 text-green-600" />
                <Copy v-else class="w-4 h-4 text-slate-500 dark:text-slate-400" />
              </button>
            </div>
          </div>
          <div class="flex-1 p-6 overflow-y-auto text-lg leading-relaxed whitespace-pre-wrap min-h-0">
            <template v-if="targetText">
              {{ targetText }}
            </template>
            <span v-else class="text-slate-300 dark:text-slate-600 italic">翻译结果将在此显示...</span>
          </div>
        </div>
      </div>

      <!-- Settings View -->
      <div v-else-if="view === 'settings'" class="flex-1 overflow-y-auto bg-slate-50 dark:bg-slate-950 p-6 md:p-10 min-h-0">
        <div class="max-w-2xl mx-auto space-y-8">
          <section>
            <h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-4">API 配置预设</h2>
            <div class="bg-white dark:bg-slate-900 rounded-xl shadow-sm border dark:border-slate-800 p-1.5 space-y-1">
              <div v-if="settings.profiles.length === 0" class="p-8 text-center text-sm text-slate-400 dark:text-slate-600 italic">
                暂无预设配置
              </div>
              <div 
                v-for="profile in settings.profiles" 
                :key="profile.id"
                class="p-3 flex items-center justify-between group hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors rounded-lg"
              >
                <div class="flex flex-col gap-0.5 min-w-0">
                  <span class="text-sm font-semibold text-slate-700 dark:text-slate-200 truncate">{{ profile.name }}</span>
                  <div class="flex items-center gap-2 text-[10px] text-slate-400 dark:text-slate-500 font-mono">
                    <span class="truncate max-w-30">{{ profile.modelName }}</span>
                    <span>•</span>
                    <span class="truncate">{{ profile.apiBaseUrl }}</span>
                  </div>
                </div>
                <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button 
                    @click="applyProfile(profile)"
                    class="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"
                    title="应用此配置"
                  >
                    <Play class="w-4 h-4 fill-current" />
                  </button>
                  <button 
                    @click="deleteProfile(profile.id)"
                    class="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
                    title="删除"
                  >
                    <Trash2 class="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          </section>

          <section>
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">模型接口配置</h2>
              <div v-if="!isSavingProfile" class="flex items-center gap-2">
                 <button 
                  @click="isSavingProfile = true"
                  class="text-xs flex items-center gap-1.5 text-blue-600 dark:text-blue-400 hover:underline px-2 py-1 rounded"
                >
                  <Save class="w-3.5 h-3.5" />
                  保存为预设
                </button>
              </div>
              <div v-else class="flex items-center gap-2 bg-white dark:bg-slate-800 p-1 rounded-lg border dark:border-slate-700 shadow-sm animate-in fade-in zoom-in duration-200">
                <input 
                  v-model="newProfileName"
                  type="text"
                  placeholder="输入预设名称..."
                  class="text-xs px-2 py-1 bg-transparent outline-none w-32 dark:text-slate-200"
                  @keyup.enter="saveCurrentAsProfile"
                />
                <button 
                  @click="saveCurrentAsProfile"
                  :disabled="!newProfileName.trim()"
                  class="p-1 text-green-600 hover:bg-green-50 dark:hover:bg-green-900/30 rounded disabled:opacity-50"
                >
                  <Check class="w-3.5 h-3.5" />
                </button>
                <button 
                  @click="isSavingProfile = false; newProfileName = ''"
                  class="p-1 text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded"
                >
                  <Plus class="w-3.5 h-3.5 rotate-45" />
                </button>
              </div>
            </div>
            <div class="bg-white dark:bg-slate-900 rounded-xl shadow-sm border dark:border-slate-800 p-6 space-y-4">
              <div class="space-y-2">
                <label class="text-sm font-medium text-slate-700 dark:text-slate-300">API Base URL</label>
                <input 
                  v-model="settings.apiBaseUrl"
                  type="text" 
                  class="w-full px-4 py-2 border dark:border-slate-700 rounded-lg bg-transparent focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-slate-900 dark:text-slate-100"
                  placeholder="https://api.openai.com/v1"
                />
              </div>
              <div class="space-y-2">
                <label class="text-sm font-medium text-slate-700 dark:text-slate-300">API Key</label>
                <input 
                  v-model="settings.apiKey"
                  type="password" 
                  class="w-full px-4 py-2 border dark:border-slate-700 rounded-lg bg-transparent focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100"
                  placeholder="sk-..."
                />
              </div>
              <div class="space-y-2">
                <label class="text-sm font-medium text-slate-700 dark:text-slate-300">Model</label>
                <input 
                  v-model="settings.modelName"
                  type="text" 
                  class="w-full px-4 py-2 border dark:border-slate-700 rounded-lg bg-transparent focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100"
                  placeholder="gpt-3.5-turbo"
                />
              </div>
              <div class="flex items-center justify-between">
                <div>
                  <label class="text-sm font-medium text-slate-700 dark:text-slate-300">流式输出</label>
                  <p class="text-xs text-slate-500 dark:text-slate-500">在生成时即时渲染文本</p>
                </div>
                <button 
                  @click="settings.enableStreaming = !settings.enableStreaming"
                  :class="cn(
                    'w-12 h-6 rounded-full transition-colors relative',
                    settings.enableStreaming ? 'bg-blue-600' : 'bg-slate-300 dark:bg-slate-700'
                  )"
                >
                  <div :class="cn(
                    'absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform',
                    settings.enableStreaming ? 'translate-x-6' : 'translate-x-0'
                  )"></div>
                </button>
              </div>
            </div>
          </section>

          <section>
            <h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-4">提示词工程</h2>
            <div class="bg-white dark:bg-slate-900 rounded-xl shadow-sm border dark:border-slate-800 p-6">
              <div class="space-y-2">
                <div class="flex items-center justify-between">
                  <label class="text-sm font-medium text-slate-700 dark:text-slate-300">系统提示词模板</label>
                  <button @click="settings.systemPromptTemplate = DEFAULT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline">恢复默认值</button>
                </div>
                <textarea 
                  v-model="settings.systemPromptTemplate"
                  rows="9"
                  class="w-full px-4 py-3 border dark:border-slate-700 rounded-lg bg-transparent focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-xs leading-relaxed text-slate-900 dark:text-slate-100"
                ></textarea>
                <div class="flex flex-wrap gap-2 mt-2">
                   <span v-for="tag in ['{SOURCE_LANG}', '{SOURCE_CODE}', '{TARGET_LANG}', '{TARGET_CODE}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{TEXT}']" :key="tag" class="px-2 py-1 bg-slate-100 dark:bg-slate-800 text-[10px] font-mono rounded border dark:border-slate-700 text-slate-600 dark:text-slate-400">{{ tag }}</span>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>

      <!-- Logs View -->
      <div v-else-if="view === 'logs'" class="flex-1 overflow-y-auto bg-slate-50 dark:bg-slate-950 p-6 md:p-10 min-h-0">
        <div class="max-w-3xl mx-auto space-y-6">
          <div class="flex items-center justify-between">
            <h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">调试日志</h2>
            <button 
              @click="settings.logs = []" 
              class="text-xs text-red-600 dark:text-red-400 hover:underline flex items-center gap-1"
            >
              <Trash2 class="w-3 h-3" />
              清空
            </button>
          </div>
          <div class="bg-white dark:bg-slate-900 rounded-xl shadow-sm border dark:border-slate-800 p-4 space-y-4">
            <div v-if="settings.logs.length === 0" class="text-sm text-slate-400 dark:text-slate-500 text-center py-10 italic">
              暂无日志记录。请尝试进行翻译。
            </div>
            <div 
              v-for="(log, idx) in settings.logs" 
              :key="idx" 
              class="text-[11px] font-mono border-b dark:border-slate-800 last:border-0 pb-4 flex flex-col gap-2"
            >
              <div class="flex items-center gap-2">
                <span class="text-slate-400 dark:text-slate-500">[{{ log.timestamp }}]</span>
                <span 
                  :class="cn(
                    'px-2 py-0.5 rounded uppercase font-bold text-[11px]',
                    log.type === 'request' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' :
                    log.type === 'response' ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300' :
                    'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
                  )"
                >{{ log.type === 'request' ? '请求' : log.type === 'response' ? '响应' : '错误' }}</span>
              </div>
              <pre class="bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg overflow-x-auto text-slate-600 dark:text-slate-300 max-h-56 leading-relaxed shadow-inner border border-slate-100 dark:border-slate-700">{{ typeof log.content === 'object' ? JSON.stringify(log.content, null, 2) : log.content }}</pre>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- Footer -->
    <footer class="h-8 bg-slate-100 dark:bg-slate-900 border-t dark:border-slate-800 flex items-center px-4 justify-between shrink-0">
      <div class="text-[10px] text-slate-400 dark:text-slate-500">
        {{ settings.apiBaseUrl }}
      </div>
      <div class="text-[10px] text-slate-400 dark:text-slate-500">
        Client v{{ pkg.version }}
      </div>
    </footer>
  </div>
</template>
