<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { invoke } from '@tauri-apps/api/tauri'
import { WebviewWindow } from '@tauri-apps/api/window'
import type { DeviceInfo, CurrentUser, Device, HistoryItem, ConnectRequest, ConnectionState, ClientConfig } from './types'

// 状态
const deviceInfo = ref<DeviceInfo | null>(null)
const currentUser = ref<CurrentUser | null>(null)
const devices = ref<Device[]>([])
const history = ref<HistoryItem[]>([])
const connectionState = ref<ConnectionState>({ type: 'Disconnected' })
const loading = ref(false)
const error = ref('')
const successMsg = ref('')
const autostart = ref(false)

// 配置
const config = ref<ClientConfig>({
  server_url: 'ws://localhost:9099',
  device_name: '',
  quality: {
    frame_rate: 30,
    resolution_scale: 1.0,
    image_quality: 80,
    hardware_acceleration: true
  },
  auto_start: false,
  launch_on_boot: false
})
const configEditing = ref(false)
const configForm = ref({
  server_url: ''
})

// 测试结果
const testResult = ref('')

// 标签页
const activeTab = ref<'local' | 'remote' | 'devices' | 'history' | 'settings'>('local')

// 登录表单
const showLogin = ref(false)
const loginForm = ref({
  username: '',
  password: '',
  isRegister: false
})

// 连接表单
const connectForm = ref({
  device_id: '',
  verification_code: ''
})

// 流媒体设置
const streamSettings = ref({
  resolution: '0.5',
  fps: '15',
  quality: '70'
})

// 计算属性
const isLoggedIn = computed(() => currentUser.value !== null)
const formattedDeviceId = computed(() => deviceInfo.value?.device_id_formatted || '')
const onlineDevices = computed(() => devices.value.filter(d => d.is_online && d.device_id !== deviceInfo.value?.device_id))

// 初始化
onMounted(async () => {
  try {
    await loadConfig()
    await loadAutostart()
    await invoke('initialize')
    deviceInfo.value = await invoke('get_device_info')
    currentUser.value = await invoke('get_current_user')
    
    if (currentUser.value) {
      await loadDevices()
      await loadHistory()
    }
  } catch (e) {
    console.error('初始化失败:', e)
  }
})

// 加载开机启动状态
async function loadAutostart() {
  try {
    autostart.value = await invoke('get_autostart')
  } catch (e) {
    console.error('加载开机启动状态失败:', e)
  }
}

// 切换开机启动
async function toggleAutostart() {
  try {
    const newValue = !autostart.value
    await invoke('set_autostart', { enable: newValue })
    autostart.value = newValue
    showSuccess(newValue ? '已设置开机自动启动' : '已取消开机自动启动')
  } catch (e: any) {
    showError('设置开机启动失败: ' + e)
  }
}

// 测试本地输入控制
async function testLocalInput() {
  try {
    testResult.value = '正在测试...'
    const result = await invoke('test_local_input')
    testResult.value = result as string
    showSuccess('测试完成，请查看结果')
  } catch (e: any) {
    testResult.value = '测试失败: ' + e
    showError('测试失败: ' + e)
  }
}

async function loadConfig() {
  try {
    config.value = await invoke('get_config')
    configForm.value.server_url = config.value.server_url
  } catch (e) {
    console.error('加载配置失败:', e)
  }
}

async function loadDeviceInfo() {
  try {
    deviceInfo.value = await invoke('get_device_info')
  } catch (e) {
    console.error('加载设备信息失败:', e)
  }
}

async function saveConfig() {
  loading.value = true
  try {
    const oldServerUrl = config.value.server_url
    const newConfig: ClientConfig = {
      ...config.value,
      server_url: configForm.value.server_url
    }
    await invoke('save_config', { config: newConfig })
    config.value = newConfig
    configEditing.value = false
    
    // 如果服务器地址改变了，自动重新连接
    if (oldServerUrl !== newConfig.server_url) {
      showSuccess('配置已保存，正在重新连接服务器...')
      try {
        await invoke('reconnect_server')
        showSuccess('已连接到新服务器')
        // 刷新设备状态
        await loadDeviceInfo()
      } catch (reconnectErr: any) {
        error.value = '连接新服务器失败: ' + reconnectErr.toString()
      }
    } else {
      showSuccess('配置已保存')
    }
  } catch (e: any) {
    error.value = e.toString()
  } finally {
    loading.value = false
  }
}

function startEditConfig() {
  configForm.value.server_url = config.value.server_url
  configEditing.value = true
}

function cancelEditConfig() {
  configForm.value.server_url = config.value.server_url
  configEditing.value = false
}

function showSuccess(msg: string) {
  successMsg.value = msg
  setTimeout(() => { successMsg.value = '' }, 3000)
}

function showError(msg: string) {
  error.value = msg
  setTimeout(() => { error.value = '' }, 3000)
}

async function refreshCode() {
  try {
    const newCode = await invoke<string>('refresh_verification_code')
    if (deviceInfo.value) {
      deviceInfo.value.verification_code = newCode
    }
    showSuccess('验证码已刷新')
  } catch (e) {
    console.error('刷新验证码失败:', e)
  }
}

async function handleAuth() {
  loading.value = true
  error.value = ''
  try {
    if (loginForm.value.isRegister) {
      currentUser.value = await invoke('register', {
        username: loginForm.value.username,
        password: loginForm.value.password
      })
    } else {
      currentUser.value = await invoke('login', {
        username: loginForm.value.username,
        password: loginForm.value.password
      })
    }
    showLogin.value = false
    loginForm.value = { username: '', password: '', isRegister: false }
    await loadDevices()
    await loadHistory()
    showSuccess('登录成功')
  } catch (e: any) {
    error.value = e.toString()
  } finally {
    loading.value = false
  }
}

async function handleLogout() {
  try {
    await invoke('logout')
    currentUser.value = null
    devices.value = []
    history.value = []
    activeTab.value = 'local'
  } catch (e) {
    console.error('退出失败:', e)
  }
}

async function loadDevices() {
  try {
    devices.value = await invoke('get_devices')
  } catch (e) {
    console.error('加载设备失败:', e)
  }
}

async function loadHistory() {
  try {
    history.value = await invoke('get_history', { page: 1, limit: 20 })
  } catch (e) {
    console.error('加载历史失败:', e)
  }
}

async function connectToDevice(targetDeviceId?: string, targetCode?: string) {
  const deviceId = targetDeviceId || connectForm.value.device_id
  const code = targetCode || connectForm.value.verification_code
  
  if (!deviceId) {
    error.value = '请输入设备ID'
    return
  }
  
  // 创建一个临时设备对象
  const tempDevice: Device = {
    id: '',
    device_id: deviceId.replace(/\s/g, ''),
    name: `设备 ${deviceId}`,
    os_type: 'Unknown',
    os_version: '',
    is_online: true,
    last_seen: ''
  }
  
  // 打开远程控制窗口
  openRemoteWindow(tempDevice)
}

async function quickConnect(device: Device) {
  // 打开新窗口进行远程控制
  openRemoteWindow(device)
}

// 打开远程控制窗口
async function openRemoteWindow(device: Device) {
  const serverUrl = config.value.server_url
  
  console.log('打开远程控制窗口:', {
    deviceId: device.device_id,
    deviceName: device.name,
    serverUrl: serverUrl
  })
  
  // 调用后端命令打开远程控制窗口
  try {
    loading.value = true
    await invoke('open_remote_window', {
      deviceId: device.device_id,
      deviceName: device.name,
      serverUrl: serverUrl
    })
    console.log('远程控制窗口命令已发送')
    showSuccess('正在打开远程控制窗口...')
  } catch (e: any) {
    console.error('打开远程控制窗口失败:', e)
    showError('打开远程控制窗口失败: ' + e.toString())
  } finally {
    loading.value = false
  }
}

async function disconnect() {
  try {
    await invoke('disconnect')
    connectionState.value = { type: 'Disconnected' }
  } catch (e) {
    console.error('断开失败:', e)
  }
}

async function copyDeviceInfo() {
  if (!deviceInfo.value) return
  const text = `设备ID: ${deviceInfo.value.device_id_formatted}\n验证码: ${deviceInfo.value.verification_code}`
  await navigator.clipboard.writeText(text)
  showSuccess('已复制到剪贴板')
}

function formatTime(timeStr: string): string {
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

function getDeviceIcon(osType: string): string {
  const os = osType.toLowerCase()
  if (os.includes('windows')) return '💻'
  if (os.includes('mac')) return '🖥️'
  if (os.includes('linux')) return '🐧'
  if (os.includes('android')) return '📱'
  if (os.includes('ios')) return '📱'
  return '💻'
}
</script>

<template>
  <div class="app-container">
    <!-- 成功提示 -->
    <transition name="toast">
      <div v-if="successMsg" class="toast success">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
          <polyline points="22 4 12 14.01 9 11.01"/>
        </svg>
        {{ successMsg }}
      </div>
    </transition>

    <!-- 头部 -->
    <header class="app-header">
      <div class="app-title">
        <span class="logo-icon">🖥️</span>
        <span class="title-text">EasyRemote</span>
      </div>
      <div class="user-section">
        <template v-if="isLoggedIn">
          <div class="user-info">
            <div class="user-avatar">{{ currentUser?.username[0].toUpperCase() }}</div>
            <span class="user-name">{{ currentUser?.username }}</span>
          </div>
          <button class="btn btn-icon" @click="handleLogout" title="退出登录">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
              <polyline points="16 17 21 12 16 7"/>
              <line x1="21" y1="12" x2="9" y2="12"/>
            </svg>
          </button>
        </template>
        <button v-else class="btn btn-primary btn-login" @click="showLogin = true">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
            <polyline points="10 17 15 12 10 7"/>
            <line x1="15" y1="12" x2="3" y2="12"/>
          </svg>
          登录
        </button>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="main-content">
      <!-- Tab 导航 -->
      <nav class="tabs">
        <button class="tab" :class="{ active: activeTab === 'local' }" @click="activeTab = 'local'">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
            <line x1="8" y1="21" x2="16" y2="21"/>
            <line x1="12" y1="17" x2="12" y2="21"/>
          </svg>
          <span>本机</span>
        </button>
        <button class="tab" :class="{ active: activeTab === 'remote' }" @click="activeTab = 'remote'">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
            <polyline points="15 3 21 3 21 9"/>
            <line x1="10" y1="14" x2="21" y2="3"/>
          </svg>
          <span>远控</span>
        </button>
        <button class="tab" :class="{ active: activeTab === 'devices' }" @click="activeTab = 'devices'" v-if="isLoggedIn">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="4" y="4" width="16" height="16" rx="2" ry="2"/>
            <rect x="9" y="9" width="6" height="6"/>
            <line x1="9" y1="1" x2="9" y2="4"/>
            <line x1="15" y1="1" x2="15" y2="4"/>
            <line x1="9" y1="20" x2="9" y2="23"/>
            <line x1="15" y1="20" x2="15" y2="23"/>
          </svg>
          <span>设备</span>
          <span class="badge" v-if="onlineDevices.length > 0">{{ onlineDevices.length }}</span>
        </button>
        <button class="tab" :class="{ active: activeTab === 'history' }" @click="activeTab = 'history'">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <polyline points="12 6 12 12 16 14"/>
          </svg>
          <span>历史</span>
        </button>
        <button class="tab" :class="{ active: activeTab === 'settings' }" @click="activeTab = 'settings'">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
          </svg>
          <span>设置</span>
        </button>
      </nav>

      <!-- 本设备 -->
      <div v-if="activeTab === 'local'" class="tab-content">
        <div class="card hero-card">
          <div class="hero-header">
            <div class="hero-title">
              <h2>本机设备</h2>
              <p>他人可通过本机ID和验证码远程协助您</p>
            </div>
          </div>

          <div class="device-panel">
            <div class="device-id-card">
              <label class="field-label">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
                本机 ID
              </label>
              <div class="device-id-display">{{ formattedDeviceId }}</div>
            </div>

            <div class="verification-card">
              <label class="field-label">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                </svg>
                验证码
              </label>
              <div class="verification-code">
                <span class="code-text">{{ deviceInfo?.verification_code || '••••••••' }}</span>
                <button class="btn btn-icon btn-refresh" @click="refreshCode" title="刷新验证码">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="23 4 23 10 17 10"/>
                    <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <button class="btn btn-secondary btn-block btn-share" @click="copyDeviceInfo">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/>
              <polyline points="16 6 12 2 8 6"/>
              <line x1="12" y1="2" x2="12" y2="15"/>
            </svg>
            复制并分享给对方
          </button>
        </div>
      </div>

      <!-- 远控伙伴设备 -->
      <div v-if="activeTab === 'remote'" class="tab-content">
        <div class="card">
          <div class="card-header">
            <div>
              <h3 class="card-title">远程连接</h3>
              <p class="card-subtitle">输入对方的设备ID和验证码进行远程控制</p>
            </div>
          </div>

          <div class="input-group">
            <label class="input-label">设备 ID</label>
            <input 
              type="text" 
              class="input input-lg" 
              placeholder="输入9位设备ID"
              v-model="connectForm.device_id"
            />
          </div>

          <div class="input-group">
            <label class="input-label">验证码</label>
            <input 
              type="text" 
              class="input" 
              placeholder="输入验证码"
              v-model="connectForm.verification_code"
            />
          </div>

          <!-- 画质设置 -->
          <div class="stream-settings-panel">
            <div class="panel-title">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="3"/>
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
              </svg>
              画质设置
            </div>
            <div class="settings-row">
              <div class="setting-item">
                <label class="input-label">分辨率</label>
                <select class="select" v-model="streamSettings.resolution">
                  <option value="0.25">流畅 25%</option>
                  <option value="0.5">平衡 50%</option>
                  <option value="0.75">高清 75%</option>
                  <option value="1">原画 100%</option>
                </select>
              </div>
              <div class="setting-item">
                <label class="input-label">帧率</label>
                <select class="select" v-model="streamSettings.fps">
                  <option value="5">5 FPS</option>
                  <option value="10">10 FPS</option>
                  <option value="15">15 FPS</option>
                  <option value="24">24 FPS</option>
                  <option value="30">30 FPS</option>
                </select>
              </div>
              <div class="setting-item">
                <label class="input-label">画质</label>
                <select class="select" v-model="streamSettings.quality">
                  <option value="30">低</option>
                  <option value="50">中</option>
                  <option value="70">高</option>
                  <option value="85">极高</option>
                </select>
              </div>
            </div>
          </div>

          <p v-if="error" class="error-message">{{ error }}</p>

          <button 
            class="btn btn-primary btn-block btn-lg btn-connect" 
            @click="connectToDevice()"
            :disabled="loading"
          >
            <span v-if="loading" class="loading-spinner"></span>
            <template v-else>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
                <polyline points="15 3 21 3 21 9"/>
                <line x1="10" y1="14" x2="21" y2="3"/>
              </svg>
              发起远程连接
            </template>
          </button>
        </div>

        <!-- 快速连接提示 -->
        <div class="tip-card" v-if="!isLoggedIn">
          <div class="tip-icon">💡</div>
          <div class="tip-content">
            <p class="tip-title">快速连接</p>
            <p class="tip-text">登录账号后，可直接选择已绑定设备进行一键连接</p>
            <button class="btn btn-outline btn-sm" @click="showLogin = true">立即登录</button>
          </div>
        </div>
      </div>

      <!-- 我的设备列表 -->
      <div v-if="activeTab === 'devices' && isLoggedIn" class="tab-content">
        <div class="card">
          <div class="card-header">
            <div>
              <h3 class="card-title">我的设备</h3>
              <p class="card-subtitle">已绑定 {{ devices.length }} 台设备，在线 {{ onlineDevices.length }} 台</p>
            </div>
            <button class="btn btn-icon" @click="loadDevices" title="刷新">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="23 4 23 10 17 10"/>
                <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
              </svg>
            </button>
          </div>

          <div v-if="devices.length === 0" class="empty-state">
            <div class="empty-icon">📱</div>
            <p class="empty-text">暂无绑定设备</p>
            <p class="empty-hint">在其他设备上登录同一账号即可自动绑定</p>
          </div>

          <div v-else class="device-list">
            <div 
              class="device-item" 
              v-for="device in devices" 
              :key="device.id"
              :class="{ 'is-current': device.device_id === deviceInfo?.device_id }"
            >
              <div class="device-icon">
                <span>{{ getDeviceIcon(device.os_type) }}</span>
              </div>
              <div class="device-details">
                <div class="device-name">
                  <span class="status-indicator" :class="device.is_online ? 'online' : 'offline'"></span>
                  {{ device.name }}
                  <span class="current-tag" v-if="device.device_id === deviceInfo?.device_id">当前</span>
                </div>
                <div class="device-meta">
                  <span>{{ device.os_type }}</span>
                  <span class="dot">·</span>
                  <span class="device-id-text">{{ device.device_id }}</span>
                </div>
              </div>
              <div class="device-actions">
                <button 
                  class="btn btn-sm btn-primary" 
                  v-if="device.is_online && device.device_id !== deviceInfo?.device_id"
                  @click="quickConnect(device)"
                  :disabled="loading"
                >
                  连接
                </button>
                <span class="offline-text" v-else-if="!device.is_online">离线</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史记录 -->
      <div v-if="activeTab === 'history'" class="tab-content">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">控制历史</h3>
          </div>

          <div v-if="!isLoggedIn" class="empty-state">
            <div class="empty-icon">🔐</div>
            <p class="empty-text">登录后查看历史记录</p>
            <button class="btn btn-primary btn-sm" style="margin-top: 16px;" @click="showLogin = true">立即登录</button>
          </div>

          <div v-else-if="history.length === 0" class="empty-state">
            <div class="empty-icon">📋</div>
            <p class="empty-text">暂无控制历史</p>
          </div>

          <div v-else class="history-list">
            <div class="history-item" v-for="item in history" :key="item.id">
              <div class="history-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="12" cy="12" r="10"/>
                  <polyline points="12 6 12 12 16 14"/>
                </svg>
              </div>
              <div class="history-info">
                <div class="history-name">{{ item.device_name }}</div>
                <div class="history-meta">
                  {{ formatTime(item.started_at) }}
                  <span v-if="item.duration"> · {{ item.duration }}</span>
                </div>
              </div>
              <span class="history-type">{{ item.connection_type }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 设置 -->
      <div v-if="activeTab === 'settings'" class="tab-content">
        <!-- 启动设置 -->
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">启动设置</h3>
          </div>
          <div class="settings-list">
            <div class="settings-item clickable" @click="toggleAutostart">
              <div class="settings-left">
                <span class="settings-label">开机自动启动</span>
                <span class="settings-hint">开机后自动运行 EasyRemote</span>
              </div>
              <div class="switch" :class="{ active: autostart }"></div>
            </div>
            <div class="settings-item clickable">
              <div class="settings-left">
                <span class="settings-label">最小化到托盘</span>
                <span class="settings-hint">关闭窗口时最小化到系统托盘</span>
              </div>
              <div class="switch active"></div>
            </div>
          </div>
        </div>

        <!-- 服务器配置 -->
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">服务器设置</h3>
            <button 
              v-if="!configEditing" 
              class="btn btn-sm btn-secondary"
              @click="startEditConfig"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
              </svg>
              修改
            </button>
          </div>
          
          <div v-if="configEditing" class="config-form">
            <div class="input-group">
              <label class="input-label">服务器地址</label>
              <input 
                type="text" 
                class="input" 
                placeholder="ws://服务器IP:端口"
                v-model="configForm.server_url"
              />
              <p class="input-hint">示例: ws://192.168.1.100:9099 或 wss://example.com</p>
            </div>
            
            <div class="config-actions">
              <button class="btn btn-secondary" @click="cancelEditConfig">取消</button>
              <button 
                class="btn btn-primary" 
                @click="saveConfig"
                :disabled="loading"
              >
                <span v-if="loading" class="loading-spinner"></span>
                <span v-else>保存</span>
              </button>
            </div>
          </div>
          
          <div v-else class="settings-list">
            <div class="settings-item">
              <span class="settings-label">服务器地址</span>
              <span class="settings-value mono">{{ config.server_url }}</span>
            </div>
            <div class="settings-item">
              <span class="settings-label">连接状态</span>
              <span class="settings-value">
                <span class="status-badge connected">已配置</span>
              </span>
            </div>
          </div>
        </div>

        <!-- 设备信息 -->
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">设备信息</h3>
          </div>
          <div class="settings-list">
            <div class="settings-item">
              <span class="settings-label">设备名称</span>
              <span class="settings-value">{{ deviceInfo?.device_name }}</span>
            </div>
            <div class="settings-item">
              <span class="settings-label">操作系统</span>
              <span class="settings-value">{{ deviceInfo?.os_type }}</span>
            </div>
            <div class="settings-item">
              <span class="settings-label">设备ID</span>
              <span class="settings-value mono">{{ deviceInfo?.device_id }}</span>
            </div>
          </div>
        </div>

        <!-- 调试工具 -->
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">调试工具</h3>
          </div>
          <div class="settings-list">
            <div class="settings-item">
              <span class="settings-label">测试本地输入控制</span>
              <button class="btn btn-secondary btn-sm" @click="testLocalInput">
                测试鼠标移动和点击
              </button>
            </div>
            <div v-if="testResult" class="test-result">
              <pre>{{ testResult }}</pre>
            </div>
          </div>
        </div>

        <!-- 关于 -->
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">关于</h3>
          </div>
          <div class="settings-list">
            <div class="settings-item">
              <span class="settings-label">版本</span>
              <span class="settings-value">0.1.0</span>
            </div>
            <div class="settings-item">
              <span class="settings-label">开发团队</span>
              <span class="settings-value">EasyRemote Team</span>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 登录弹窗 -->
    <transition name="modal">
      <div v-if="showLogin" class="modal-overlay" @click.self="showLogin = false">
        <div class="modal-container">
          <button class="modal-close" @click="showLogin = false">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="18" y1="6" x2="6" y2="18"/>
              <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
          
          <div class="login-header">
            <div class="login-logo">🔐</div>
            <h2 class="login-title">{{ loginForm.isRegister ? '创建账号' : '欢迎回来' }}</h2>
            <p class="login-subtitle">{{ loginForm.isRegister ? '创建账号以同步您的设备' : '登录以管理您的设备' }}</p>
          </div>

          <div class="input-group">
            <label class="input-label">用户名</label>
            <input 
              type="text" 
              class="input" 
              placeholder="请输入用户名"
              v-model="loginForm.username"
              @keyup.enter="handleAuth"
            />
          </div>

          <div class="input-group">
            <label class="input-label">密码</label>
            <input 
              type="password" 
              class="input" 
              placeholder="请输入密码"
              v-model="loginForm.password"
              @keyup.enter="handleAuth"
            />
          </div>

          <p v-if="error" class="error-message">{{ error }}</p>

          <button 
            class="btn btn-primary btn-block btn-lg btn-auth" 
            @click="handleAuth"
            :disabled="loading"
          >
            <span v-if="loading" class="loading-spinner"></span>
            <span v-else>{{ loginForm.isRegister ? '注册' : '登录' }}</span>
          </button>

          <p class="login-switch">
            <span v-if="loginForm.isRegister">
              已有账号？
              <a href="#" @click.prevent="loginForm.isRegister = false">立即登录</a>
            </span>
            <span v-else>
              没有账号？
              <a href="#" @click.prevent="loginForm.isRegister = true">立即注册</a>
            </span>
          </p>
        </div>
      </div>
    </transition>

  </div>
</template>

<style scoped>
/* Toast 提示 */
.toast {
  position: fixed;
  top: 24px;
  left: 50%;
  transform: translateX(-50%);
  padding: 14px 28px;
  background: rgba(26, 29, 40, 0.95);
  backdrop-filter: blur(16px);
  border: 1px solid var(--border-light);
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  font-weight: 500;
  z-index: 2000;
  box-shadow: var(--shadow-lg);
}

.toast.success {
  border-color: var(--success);
  color: var(--success);
}

.toast-enter-active,
.toast-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.toast-enter-from,
.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-24px) scale(0.95);
}

/* 头部样式 */
.title-text {
  background: linear-gradient(135deg, var(--text-primary) 0%, var(--primary-light) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.btn-login {
  padding: 10px 20px;
  font-size: 13px;
}

/* Tab 导航 */
.tabs {
  display: flex;
  gap: 4px;
  background: rgba(26, 29, 40, 0.6);
  backdrop-filter: blur(8px);
  padding: 6px;
  border-radius: var(--radius-lg);
  margin-bottom: 24px;
  border: 1px solid var(--border-color);
}

.tab {
  flex: 1;
  min-width: 0;
  padding: 12px 16px;
  background: transparent;
  border: none;
  border-radius: var(--radius-md);
  color: var(--text-secondary);
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all var(--transition-normal);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  white-space: nowrap;
}

.tab svg {
  flex-shrink: 0;
  opacity: 0.7;
}

.tab span {
  display: inline-block;
}

.tab:hover {
  color: var(--text-primary);
  background: var(--bg-glass);
}

.tab.active {
  background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
  color: white;
  box-shadow: 0 4px 16px var(--primary-glow);
}

.tab.active svg {
  opacity: 1;
}

.tab .badge {
  margin-left: 2px;
  font-size: 10px;
}

/* Hero 卡片 */
.hero-card {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(139, 92, 246, 0.05) 100%);
  border-color: rgba(99, 102, 241, 0.2);
}

.hero-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 28px;
  gap: 16px;
}

.hero-title h2 {
  font-size: 20px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 8px;
  letter-spacing: -0.02em;
}

.hero-title p {
  font-size: 13px;
  color: var(--text-secondary);
  line-height: 1.6;
}

.toggle-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.toggle-label {
  font-size: 13px;
  color: var(--text-secondary);
  font-weight: 500;
  white-space: nowrap;
}

/* 设备面板 */
.device-panel {
  display: grid;
  gap: 20px;
  margin-bottom: 24px;
}

.device-id-card,
.verification-card {
  background: var(--bg-glass);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  padding: 20px;
}

.field-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 11px;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 12px;
}

.device-id-display {
  font-family: var(--font-mono);
  font-size: 32px;
  font-weight: 700;
  letter-spacing: 6px;
  background: linear-gradient(135deg, var(--primary-light) 0%, var(--accent-light) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 40px var(--primary-glow);
}

.verification-code {
  display: flex;
  align-items: center;
  gap: 16px;
}

.code-text {
  font-family: var(--font-mono);
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 3px;
  color: var(--text-primary);
}

.btn-refresh {
  width: 36px;
  height: 36px;
  padding: 0;
}

.btn-refresh:hover {
  background: var(--bg-tertiary);
  color: var(--primary-light);
}

.btn-share {
  padding: 14px 24px;
  font-size: 14px;
}

/* 连接按钮 */
.btn-connect {
  padding: 16px 32px;
  font-size: 15px;
  gap: 10px;
  margin-top: 8px;
}

/* 输入框大号 */
.input-lg {
  padding: 16px 18px;
  font-size: 16px;
  font-family: var(--font-mono);
  letter-spacing: 2px;
}

/* 提示卡片 */
.tip-card {
  background: linear-gradient(135deg, var(--primary-bg) 0%, rgba(139, 92, 246, 0.08) 100%);
  border: 1px solid rgba(99, 102, 241, 0.2);
  border-radius: var(--radius-lg);
  padding: 20px;
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.tip-icon {
  font-size: 28px;
  filter: drop-shadow(0 0 8px rgba(99, 102, 241, 0.5));
}

.tip-content {
  flex: 1;
}

.tip-title {
  font-weight: 600;
  font-size: 15px;
  color: var(--text-primary);
  margin-bottom: 6px;
}

.tip-text {
  font-size: 13px;
  color: var(--text-secondary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.btn-outline {
  background: transparent;
  border: 1px solid var(--primary);
  color: var(--primary-light);
}

.btn-outline:hover {
  background: var(--primary-bg);
}

/* 设备列表 */
.device-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.device-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: var(--bg-glass);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  gap: 16px;
  transition: all var(--transition-normal);
}

.device-item:hover {
  background: var(--bg-tertiary);
  border-color: var(--border-light);
  transform: translateX(4px);
}

.device-item.is-current {
  border-color: var(--primary);
  background: linear-gradient(135deg, var(--primary-bg) 0%, transparent 100%);
}

.device-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, var(--bg-tertiary) 0%, var(--bg-secondary) 100%);
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.device-details {
  flex: 1;
  min-width: 0;
}

.device-name {
  font-size: 15px;
  font-weight: 500;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-indicator.online {
  background: var(--success);
  box-shadow: 0 0 10px var(--success);
}

.status-indicator.offline {
  background: var(--text-dim);
}

.current-tag {
  font-size: 10px;
  padding: 3px 8px;
  background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
  color: white;
  border-radius: 6px;
  font-weight: 600;
}

.device-meta {
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 6px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.device-meta .dot {
  color: var(--text-dim);
}

.device-id-text {
  font-family: var(--font-mono);
  font-size: 11px;
}

.device-actions {
  flex-shrink: 0;
}

.offline-text {
  font-size: 12px;
  color: var(--text-dim);
  padding: 6px 12px;
  background: var(--bg-tertiary);
  border-radius: var(--radius-sm);
}

/* 历史列表 */
.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-type {
  font-size: 11px;
  color: var(--text-muted);
  padding: 5px 10px;
  background: var(--bg-tertiary);
  border-radius: var(--radius-sm);
  font-weight: 500;
}

/* 设置列表 */
.settings-list {
  display: flex;
  flex-direction: column;
}

/* 测试结果 */
.test-result {
  margin-top: 12px;
  padding: 12px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.test-result pre {
  margin: 0;
  color: var(--text-secondary);
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

/* 错误信息 */
.error-message {
  color: var(--error);
  font-size: 13px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: var(--error-bg);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: var(--radius-md);
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(8px);
  padding: 24px;
}

.modal-container {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-xl);
  padding: 36px;
  width: 100%;
  max-width: 400px;
  position: relative;
  box-shadow: var(--shadow-lg);
}

.modal-enter-active,
.modal-leave-active {
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-enter-from .modal-container,
.modal-leave-to .modal-container {
  transform: scale(0.95) translateY(16px);
}

.modal-close {
  position: absolute;
  top: 20px;
  right: 20px;
  background: var(--bg-glass);
  border: 1px solid var(--border-color);
  color: var(--text-muted);
  cursor: pointer;
  padding: 8px;
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.modal-close:hover {
  color: var(--text-primary);
  background: var(--bg-tertiary);
  border-color: var(--border-light);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-logo {
  font-size: 48px;
  margin-bottom: 16px;
  filter: drop-shadow(0 0 16px var(--primary-glow));
}

.login-title {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 8px;
  letter-spacing: -0.02em;
}

.login-subtitle {
  font-size: 14px;
  color: var(--text-secondary);
}

.btn-auth {
  margin-top: 8px;
}

.login-switch {
  text-align: center;
  margin-top: 24px;
  font-size: 14px;
  color: var(--text-secondary);
}

.login-switch a {
  color: var(--primary-light);
  text-decoration: none;
  font-weight: 600;
}

.login-switch a:hover {
  text-decoration: underline;
}

/* 配置表单 */
.config-form {
  padding-top: 8px;
}

.config-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.input-hint {
  font-size: 12px;
  color: var(--text-dim);
  margin-top: 8px;
}

/* 响应式 */
@media (max-width: 480px) {
  .tabs {
    gap: 2px;
    padding: 4px;
  }
  
  .tab {
    padding: 10px 8px;
    font-size: 12px;
  }
  
  .tab svg {
    width: 16px;
    height: 16px;
  }
  
  .tab span {
    display: none;
  }
  
  .device-id-display {
    font-size: 24px;
    letter-spacing: 3px;
  }
  
  .hero-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .toggle-section {
    width: 100%;
    justify-content: space-between;
  }
  
  .config-actions {
    flex-direction: column;
  }
  
  .config-actions .btn {
    width: 100%;
  }
}

</style>
