<template>
  <div class="car-management">
    <!-- 俱乐部赛车卡片 -->
    <div class="status-card car-management-card">
      <div class="card-header">
        <img
          src="/icons/car.jpg"
          alt="赛车图标"
          class="status-icon"
        >
        <div class="status-info">
          <h3>俱乐部赛车</h3>
          <p>车辆管理与操作</p>
        </div>
        <div class="header-stats">
          <div
            class="status-badge"
            :class="{ active: carData.length > 0 }"
          >
            <div class="status-dot" />
            <span>{{ carData.length }}辆车</span>
          </div>
          <div
            class="refresh-ticket-badge"
            title="刷新票数量"
          >
            <span class="ticket-icon">🎫</span>
            <span class="ticket-count">{{ refreshTicketCount }}</span>
          </div>
          <div
            class="send-count-badge"
            :class="{ 'limit-reached': dailySendCount >= 4 }"
            title="今日已发车次数 / 每日上限"
          >
            <span class="car-icon">🚗</span>
            <span class="send-count">{{ dailySendCount }}/4</span>
          </div>
        </div>
      </div>

      <div class="card-content">
        <!-- 查询按钮 -->
        <button 
          class="action-button query-btn"
          :disabled="isQuerying"
          @click="queryClubCars"
        >
          <span v-if="isQuerying" class="loading-text">
            <svg class="loading-icon" viewBox="0 0 24 24">
              <path
                fill="currentColor"
                d="M12 22c5.421 0 10-4.579 10-10h-2c0 4.337-3.663 8-8 8s-8-3.663-8-8c0-4.336 3.663-8 8-8V2C6.579 2 2 6.58 2 12c0 5.421 4.579 10 10 10z"
              />
            </svg>
            查询中...
          </span>
          <span v-else>🔍 查询俱乐部车辆</span>
        </button>

        <!-- 车辆列表 -->
        <div v-if="carData.length > 0" class="car-list">
          <div
            v-for="(car, index) in carData"
            :key="car.carId"
            class="car-item"
            :class="`quality-${car.quality}`"
          >
            <div class="car-info">
              <div class="car-index">#{{ index + 1 }}</div>
              <div class="car-details">
                <div class="car-header-row">
                  <div class="car-id">ID: {{ car.carId }}</div>
                  <div class="car-state-badge" :class="getStateClass(car.state)">
                    {{ getStateText(car.state) }}
                  </div>
                </div>
                
                <!-- 运输进度条（仅运输中显示） -->
                <div v-if="car.state === 1" class="transport-progress">
                  <div class="progress-info">
                    <span class="progress-text">运输进度: {{ car.transportProgress }}%</span>
                    <span class="remaining-time">剩余: {{ formatRemainingTime(car.remainingTime) }}</span>
                  </div>
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: car.transportProgress + '%' }"></div>
                  </div>
                </div>
                
                <div class="car-quality" :style="{ color: getQualityColor(car.quality) }">
                  {{ getQualityText(car.quality) }}
                </div>
                <div class="car-rewards-section">
                  <div v-if="car.rewards && car.rewards.length > 0" class="car-rewards">
                    <span class="rewards-label">🎁 奖励：</span>
                    <span class="rewards-content">{{ car.rewards.join('，') }}</span>
                  </div>
                  <div v-else class="car-rewards no-rewards">
                    <span class="rewards-label">🎁 奖励：</span>
                    <span class="rewards-content">无奖励</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="car-actions">
              <button
                class="mini-btn refresh-btn"
                :disabled="isOperating[car.carId]"
                @click="refreshCar(car.carId)"
                title="刷新车辆"
              >
                🔄
              </button>
              <button
                class="mini-btn claim-btn"
                :disabled="isOperating[car.carId]"
                @click="claimCar(car.carId)"
                title="收获车辆"
              >
                🎁
              </button>
              <button
                class="mini-btn send-btn"
                :disabled="isOperating[car.carId]"
                @click="sendCar(car.carId)"
                title="发送车辆"
              >
                🚀
              </button>
            </div>
          </div>
        </div>

        <!-- 刷新设置 -->
        <div v-if="carData.length > 0" class="refresh-settings">
          <div class="setting-item">
            <label class="setting-label">
              <input 
                v-model="skipCarsWithTickets" 
                type="checkbox" 
                class="setting-checkbox"
              >
              <span class="checkbox-text">跳过有刷新票的车辆</span>
            </label>
            <span class="setting-hint">（开启后，有刷新票奖励的车辆将不会被刷新）</span>
          </div>
        </div>

        <!-- 批量操作按钮 -->
        <div v-if="carData.length > 0" class="batch-actions">
          <button
            class="action-button secondary batch-btn"
            :disabled="isBatchOperating"
            @click="batchRefreshCars"
          >
            <span v-if="isBatchOperating" class="loading-text">
              <svg class="loading-icon" viewBox="0 0 24 24">
                <path
                  fill="currentColor"
                  d="M12 22c5.421 0 10-4.579 10-10h-2c0 4.337-3.663 8-8 8s-8-3.663-8-8c0-4.336 3.663-8 8-8V2C6.579 2 2 6.58 2 12c0 5.421 4.579 10 10 10z"
                />
              </svg>
              批量刷新中...
            </span>
            <span v-else>🔄 批量刷新</span>
          </button>
          <button
            class="action-button batch-btn"
            :disabled="isBatchOperating"
            @click="batchClaimAndSendCars"
          >
            <span v-if="isBatchOperating" class="loading-text">
              <svg class="loading-icon" viewBox="0 0 24 24">
                <path
                  fill="currentColor"
                  d="M12 22c5.421 0 10-4.579 10-10h-2c0 4.337-3.663 8-8 8s-8-3.663-8-8c0-4.336 3.663-8 8-8V2C6.579 2 2 6.58 2 12c0 5.421 4.579 10 10 10z"
                />
              </svg>
              一键发车中...
            </span>
            <span v-else>🚗 一键发车</span>
          </button>
        </div>

        <!-- 空状态提示 -->
        <div v-if="carData.length === 0 && !isQuerying" class="empty-state">
          <p>暂无车辆数据</p>
          <p class="hint">点击上方按钮查询俱乐部车辆</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch } from 'vue'
import { useTokenStore } from '@/stores/tokenStore'
import { useMessage } from 'naive-ui'

const tokenStore = useTokenStore()
const message = useMessage()

// 响应式数据
const carData = ref([])
const isQuerying = ref(false)
const isBatchOperating = ref(false)
const isOperating = reactive({})
const skipCarsWithTickets = ref(true) // 跳过有刷新票的车辆（默认开启）
const refreshTicketCount = ref(0) // 刷新票数量

// 今日已发车次数（持久化到localStorage，按tokenId区分）
const STORAGE_KEY_PREFIX = 'car_daily_send_count_'
const getTodayKey = (tokenId) => {
  const today = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
  // 如果没有传入tokenId，使用当前选中的token
  const currentTokenId = tokenId || tokenStore.selectedToken?.id || 'default'
  return `${STORAGE_KEY_PREFIX}${today}_${currentTokenId}`
}

// 从localStorage恢复今日发车次数
const loadDailySendCount = () => {
  try {
    const savedCount = localStorage.getItem(getTodayKey())
    return savedCount ? parseInt(savedCount, 10) : 0
  } catch (error) {
    console.error('读取发车次数失败:', error)
    return 0
  }
}

// 保存今日发车次数到localStorage
const saveDailySendCount = (count) => {
  try {
    localStorage.setItem(getTodayKey(), count.toString())
    console.log(`💾 已保存今日发车次数: ${count}`)
  } catch (error) {
    console.error('保存发车次数失败:', error)
  }
}

const dailySendCount = ref(loadDailySendCount()) // 今日已发车次数（初始从localStorage加载）

// 初始化日志
console.log(`🚗 初始化发车计数: ${dailySendCount.value}/4（今日: ${new Date().toLocaleDateString('zh-CN')}，Token: ${tokenStore.selectedToken?.id || 'default'}）`)

// 监听 token 切换，重新加载对应 token 的发车次数
watch(() => tokenStore.selectedToken?.id, (newTokenId, oldTokenId) => {
  if (newTokenId !== oldTokenId) {
    const newCount = loadDailySendCount()
    dailySendCount.value = newCount
    console.log(`🔄 Token切换: ${oldTokenId} → ${newTokenId}，发车计数: ${newCount}/4`)
  }
})

// 品质映射
const qualityMap = {
  1: '绿色(普通)',
  2: '蓝色(精致)',
  3: '紫色(卓越)',
  4: '橙色(传说)',
  5: '红色(神话)',
  6: '金色(传说)'
}

const qualityColorMap = {
  1: '#4ade80', // 绿色
  2: '#60a5fa', // 蓝色
  3: '#a78bfa', // 紫色
  4: '#fb923c', // 橙色
  5: '#f87171', // 红色
  6: '#fbbf24'  // 金色
}

// 获取品质文本
const getQualityText = (quality) => {
  return qualityMap[quality] || '未知品质'
}

// 获取品质颜色
const getQualityColor = (quality) => {
  return qualityColorMap[quality] || '#9ca3af'
}

// 获取车辆状态文本
const getStateText = (state) => {
  const stateMap = {
    0: '待发车',
    1: '运输中',
    2: '已到达'
  }
  return stateMap[state] || '待发车'
}

// 获取车辆状态样式类
const getStateClass = (state) => {
  const classMap = {
    0: 'state-waiting',     // 待发车
    1: 'state-shipping',    // 运输中
    2: 'state-arrived'      // 已到达
  }
  return classMap[state] || 'state-waiting'
}

// 格式化剩余时间
const formatRemainingTime = (seconds) => {
  if (seconds <= 0) return '即将到达'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}小时${minutes}分`
  } else if (minutes > 0) {
    return `${minutes}分${secs}秒`
  } else {
    return `${secs}秒`
  }
}

// 检查车辆是否包含刷新票
const carHasRefreshTicket = (carInfo) => {
  if (!carInfo?.rawInfo?.rewards || !Array.isArray(carInfo.rawInfo.rewards)) {
    return false
  }
  
  // 刷新票的itemId是35002
  return carInfo.rawInfo.rewards.some(reward => reward.itemId === 35002)
}

// 解析奖励信息
const parseRewards = (rewards) => {
  if (!rewards || !Array.isArray(rewards)) {
    return []
  }
  
  console.log('🎁 原始奖励数据:', rewards)
  
  const rewardMap = {
    gold: { name: '金币', count: 0 },          // type=1, itemId=0
    goldBrick: { name: '金砖', count: 0 },      // type=2, itemId=0
    recruitOrder: { name: '招募令', count: 0 },  // itemId=1001, type=3
    refreshTicket: { name: '刷新票', count: 0 }, // itemId=35002, type=3
    coloredJade: { name: '彩玉', count: 0 },    // itemId=1023, type=3
    whiteJade: { name: '白玉', count: 0 },      // itemId=1022, type=3
    item35009: { name: '赛车零件', count: 0 },   // itemId=35009, type=3
    item1003: { name: '进阶石', count: 0 },      // itemId=1003, type=3
    item1006: { name: '精铁', count: 0 },        // itemId=1006, type=3
    item3006: { name: '随机橙将碎片', count: 0 }, // itemId=3006, type=3
    item3005: { name: '随机紫将碎片', count: 0 }, // itemId=3005, type=3
    item1016: { name: '梦魇晶石', count: 0 },    // itemId=1016, type=3
    item3201: { name: '万能红将碎片', count: 0 } // itemId=3201, type=3
  }
  
  // 用于存储未识别的奖励
  const unknownRewards = []
  
  // 遍历奖励列表并统计
  rewards.forEach((reward, index) => {
    console.log(`🎁 解析奖励 [${index}]:`, reward)
    
    let recognized = false
    
    // 金币和金砖: itemId=0
    if (reward.itemId === 0) {
      if (reward.type === 1) {
        // 金币
        rewardMap.gold.count += reward.value || 0
        recognized = true
      } else if (reward.type === 2 || reward.type === 0) {
        // 金砖
        rewardMap.goldBrick.count += reward.value || 0
        recognized = true
      }
    }
    // type=3 的各种物品
    else if (reward.type === 3) {
      switch (reward.itemId) {
        case 1001: // 招募令
          rewardMap.recruitOrder.count += reward.value || 0
          recognized = true
          break
        case 35002: // 刷新票
          rewardMap.refreshTicket.count += reward.value || 0
          recognized = true
          break
        case 1023: // 彩玉
          rewardMap.coloredJade.count += reward.value || 0
          recognized = true
          break
        case 1022: // 白玉
          rewardMap.whiteJade.count += reward.value || 0
          recognized = true
          break
        case 35009: // 赛车零件
          rewardMap.item35009.count += reward.value || 0
          recognized = true
          break
        case 1003: // 进阶石
          rewardMap.item1003.count += reward.value || 0
          recognized = true
          break
        case 1006: // 精铁
          rewardMap.item1006.count += reward.value || 0
          recognized = true
          break
        case 3006: // 随机橙将碎片
          rewardMap.item3006.count += reward.value || 0
          recognized = true
          break
        case 3005: // 随机紫将碎片
          rewardMap.item3005.count += reward.value || 0
          recognized = true
          break
        case 1016: // 梦魇晶石
          rewardMap.item1016.count += reward.value || 0
          recognized = true
          break
        case 3201: // 万能红将碎片
          rewardMap.item3201.count += reward.value || 0
          recognized = true
          break
      }
    }
    
    // 如果奖励未被识别，添加到未知奖励列表
    if (!recognized) {
      console.warn(`⚠️ 未识别的奖励:`, reward)
      unknownRewards.push({
        itemId: reward.itemId,
        type: reward.type,
        value: reward.value || 0
      })
    }
  })
  
  // 构建结果列表，只包含有数量的奖励
  const result = []
  
  // 按照重要性排序输出
  if (rewardMap.gold.count > 0) {
    result.push(`金币:${rewardMap.gold.count}`)
  }
  if (rewardMap.goldBrick.count > 0) {
    result.push(`金砖:${rewardMap.goldBrick.count}`)
  }
  if (rewardMap.coloredJade.count > 0) {
    result.push(`彩玉:${rewardMap.coloredJade.count}`)
  }
  if (rewardMap.whiteJade.count > 0) {
    result.push(`白玉:${rewardMap.whiteJade.count}`)
  }
  if (rewardMap.recruitOrder.count > 0) {
    result.push(`招募令:${rewardMap.recruitOrder.count}`)
  }
  if (rewardMap.refreshTicket.count > 0) {
    result.push(`刷新票:${rewardMap.refreshTicket.count}`)
  }
  if (rewardMap.item35009.count > 0) {
    result.push(`赛车零件:${rewardMap.item35009.count}`)
  }
  if (rewardMap.item1006.count > 0) {
    result.push(`精铁:${rewardMap.item1006.count}`)
  }
  if (rewardMap.item1003.count > 0) {
    result.push(`进阶石:${rewardMap.item1003.count}`)
  }
  if (rewardMap.item1016.count > 0) {
    result.push(`梦魇晶石:${rewardMap.item1016.count}`)
  }
  if (rewardMap.item3201.count > 0) {
    result.push(`万能红将碎片:${rewardMap.item3201.count}`)
  }
  if (rewardMap.item3006.count > 0) {
    result.push(`随机橙将碎片:${rewardMap.item3006.count}`)
  }
  if (rewardMap.item3005.count > 0) {
    result.push(`随机紫将碎片:${rewardMap.item3005.count}`)
  }
  
  // 添加未识别的奖励
  unknownRewards.forEach(reward => {
    result.push(`物品[${reward.itemId}-${reward.type}]:${reward.value}`)
  })
  
  console.log('🎁 解析后的奖励:', result)
  
  return result
}

// 查询俱乐部车辆
const queryClubCars = async () => {
  if (!tokenStore.selectedToken) {
    message.warning('请先选择Token')
    return
  }
  
  try {
    isQuerying.value = true
    const tokenId = tokenStore.selectedToken.id
    
    console.log('🚗 开始查询俱乐部车辆...')
    message.info('正在查询俱乐部车辆...')
    
    // 发送查询命令（10秒超时）
    const response = await tokenStore.sendMessageAsync(tokenId, 'car_getrolecar', {}, 10000)
    
    console.log('🚗 车辆查询响应:', response)
    
    if (response) {
      carData.value = []
      let carDataMap = null
      
      // 多层级数据结构适配
      // 响应格式：{roleCar: {carDataMap: {...}}}
      if (response.roleCar?.carDataMap) {
        carDataMap = response.roleCar.carDataMap
      } else if (response._rawData?.roleCar?.carDataMap) {
        carDataMap = response._rawData.roleCar.carDataMap
      } else if (response.data?.body?.roleCar?.carDataMap) {
        carDataMap = response.data.body.roleCar.carDataMap
      }
      
      console.log('🚗 解析到的carDataMap:', carDataMap)
      
      // 获取刷新票数量和今日发车次数
      if (response.roleCar) {
        // 获取刷新票数量（itemId: 35002）
        const refreshTicketItem = response.roleCar.refreshTicket || 0
        refreshTicketCount.value = refreshTicketItem
        console.log('🎫 刷新票数量:', refreshTicketCount.value)
        
        // 获取今日发车次数（从服务器读取，如果不存在则保持当前值）
        // 注意：只有在初次查询或从localStorage恢复后才从服务器读取
        if (response.roleCar.sendCount !== undefined && response.roleCar.sendCount !== null) {
          // 如果服务器返回的值大于当前值，说明服务器数据更准确（可能是其他地方发送的）
          if (response.roleCar.sendCount > dailySendCount.value) {
            dailySendCount.value = response.roleCar.sendCount
            saveDailySendCount(dailySendCount.value) // 同步保存到localStorage
            console.log('🚗 从服务器更新今日发车次数:', dailySendCount.value)
          } else {
            console.log(`🚗 保持客户端发车次数: ${dailySendCount.value}（服务器值: ${response.roleCar.sendCount}）`)
          }
        } else {
          console.log('🚗 服务器未返回sendCount，保持客户端计数:', dailySendCount.value)
        }
      }
      
      if (carDataMap && Object.keys(carDataMap).length > 0) {
        // 按照车辆ID排序，保持固定顺序
        const sortedCarIds = Object.keys(carDataMap).sort()
        console.log('🔢 车辆ID排序:', sortedCarIds)
        
        // 提取车辆ID、品质、状态和奖励信息
        for (const carId of sortedCarIds) {
          const carInfo = carDataMap[carId]
          console.log(`🚗 处理车辆 ${carId}:`, carInfo)
          
          // 解析奖励信息
          const rewards = parseRewards(carInfo.rewards)
          console.log(`🎁 车辆 ${carId} 奖励:`, rewards)
          
          // 解析车辆状态
          // 根据 sendAt 和 claimAt 判断状态
          // sendAt: 发送时间, claimAt: 收获时间
          let state = 0 // 默认：待发车
          
          const now = Date.now()
          const sendAt = carInfo.sendAt || 0
          const claimAt = carInfo.claimAt || 0
          
          // 打印完整车辆信息用于调试
          console.log(`🔍 车辆 ${carId} 完整数据:`, {
            id: carInfo.id,
            sendAt: sendAt,
            claimAt: claimAt,
            legionId: carInfo.legionId,
            serverId: carInfo.serverId,
            helperServerId: carInfo.helperServerId,
            color: carInfo.color,
            raided: carInfo.raided,
            slot: carInfo.slot,
            now: now,
            timeSinceSend: sendAt > 0 ? Math.floor((now / 1000) - sendAt) : 0
          })
          
          // 判断状态
          if (claimAt > 0) {
            // 已经被收获过了（历史记录）
            state = 0 // 待发车（可以重新发送）
          } else if (sendAt > 0) {
            // 已经发送，根据品质计算运输时间判断是否到达
            const color = carInfo.color || 1
            let transportDuration = 9000 // 默认150分钟（普通、稀有）
            
            if (color === 3) {
              // 史诗：180分钟
              transportDuration = 10800
            } else if (color === 4 || color === 5) {
              // 神话、传奇：240分钟
              transportDuration = 14400
            }
            
            const timeSinceSend = Math.floor((now / 1000) - sendAt)
            
            if (timeSinceSend >= transportDuration) {
              state = 2 // 已到达（可以收获）
            } else {
              state = 1 // 运输中（还在路上）
            }
          } else {
            // 还没发送
            state = 0 // 待发车
          }
          
          const timeSinceSend = sendAt > 0 ? Math.floor((now / 1000) - sendAt) : 0
          const color = carInfo.color || 1
          let transportDuration = 9000
          if (color === 3) transportDuration = 10800
          else if (color === 4 || color === 5) transportDuration = 14400
          
          console.log(`🚦 车辆 ${carId} 状态: ${state} (${getStateText(state)}) - color:${color}, 已发送:${timeSinceSend}秒, 需要:${transportDuration}秒, 进度:${Math.floor(timeSinceSend/transportDuration*100)}%`)
          
          // 计算运输进度信息
          let transportProgress = 0
          let remainingTime = 0
          if (state === 1 && sendAt > 0) {
            const color = carInfo.color || 1
            let transportDuration = 9000
            if (color === 3) transportDuration = 10800
            else if (color === 4 || color === 5) transportDuration = 14400
            
            transportProgress = Math.floor((timeSinceSend / transportDuration) * 100)
            remainingTime = Math.max(0, transportDuration - timeSinceSend)
          }
          
          carData.value.push({
            carId: carInfo.id || carId,  // 优先使用carInfo.id
            quality: carInfo.color || 1,
            state: state,  // 车辆状态
            rewards: rewards,
            rawInfo: carInfo,
            transportProgress: transportProgress,  // 运输进度百分比
            remainingTime: remainingTime  // 剩余时间（秒）
          })
        }
        
        console.log(`🚗 查询到 ${carData.value.length} 辆俱乐部车辆`, carData.value)
        
        // 统计各状态的车辆数量
        const carsInTransit = carData.value.filter(car => car.state === 1)  // 运输中
        const carsArrived = carData.value.filter(car => car.state === 2)    // 已到达
        const carsReady = carData.value.filter(car => car.state === 0)      // 待发车
        
        console.log(`📊 车辆状态统计: 运输中${carsInTransit.length}辆, 已到达${carsArrived.length}辆, 待发车${carsReady.length}辆`)
        
        // 如果有车正在运输中，将其算作今日已发车
        if (carsInTransit.length > 0) {
          // 计算实际应该记录的发车数（考虑运输中的车辆）
          const expectedSendCount = carsInTransit.length
          
          // 如果客户端记录的发车数小于运输中的车辆数，更新为运输中的车辆数
          if (dailySendCount.value < expectedSendCount) {
            console.log(`🚗 检测到 ${carsInTransit.length} 辆车正在运输中，更新今日发车次数: ${dailySendCount.value} → ${expectedSendCount}`)
            dailySendCount.value = expectedSendCount
            saveDailySendCount(dailySendCount.value)
          }
        }
        
        message.success(`成功查询到 ${carData.value.length} 辆车辆（今日已发车: ${dailySendCount.value}/4）`)
      } else {
        console.log('🚗 未查询到俱乐部车辆数据')
        message.warning('未查询到车辆数据')
        carData.value = []
      }
    } else {
      console.error('🚗 查询失败：响应为空')
      message.error('车辆查询失败')
    }
  } catch (error) {
    console.error('🚗 查询出错:', error)
    message.error('查询过程出错: ' + error.message)
  } finally {
    isQuerying.value = false
  }
}

// 刷新车辆
const refreshCar = async (carId) => {
  if (!tokenStore.selectedToken) {
    message.warning('请先选择Token')
    return
  }
  
  // 检查是否启用跳过有刷新票的车辆
  if (skipCarsWithTickets.value) {
    const car = carData.value.find(c => c.carId === carId)
    if (car && carHasRefreshTicket(car)) {
      console.log(`⏭️ 跳过有刷新票的车辆: ${carId}`)
      message.info(`已跳过车辆 ${carId}（含刷新票）`)
      return
    }
  }
  
  try {
    isOperating[carId] = true
    const tokenId = tokenStore.selectedToken.id
    
    console.log(`🔄 开始刷新车辆，ID: ${carId}`)
    message.info(`正在刷新车辆: ${carId}`)
    
    const response = await tokenStore.sendMessageAsync(tokenId, 'car_refresh', {
      carId: carId
    }, 5000)
    
    console.log(`🔄 车辆刷新完整响应:`, response)
    
    if (response) {
      // 检查响应中是否有 car 对象
      if (response.car) {
        console.log(`🔄 车辆刷新成功，新品质: ${response.car.color}, 刷新次数: ${response.car.refreshCount}`)
        console.log(`🔄 新奖励:`, response.car.rewards)
        message.success(`车辆 ${carId} 刷新成功！品质: ${getQualityText(response.car.color)}`)
      } else {
        console.log(`🔄 车辆刷新成功，ID: ${carId}`, response)
        message.success(`车辆 ${carId} 刷新成功`)
      }
      
      // 刷新后重新查询车辆列表
      await queryClubCars()
    } else {
      console.error(`🔄 车辆刷新失败，ID: ${carId}`)
      message.error(`车辆 ${carId} 刷新失败`)
    }
  } catch (error) {
    console.error('🔄 刷新车辆出错:', error)
    
    // 解析错误信息
    const errorMsg = error.message || String(error)
    if (errorMsg.includes('200020')) {
      message.warning(`车辆 ${carId} 刷新失败：可能刷新次数已用完或处于冷却中`)
    } else if (errorMsg.includes('超时')) {
      message.error(`刷新车辆 ${carId} 超时`)
    } else {
      message.error(`刷新车辆 ${carId} 失败: ${errorMsg}`)
    }
  } finally {
    delete isOperating[carId]
  }
}

// 收获车辆
const claimCar = async (carId) => {
  if (!tokenStore.selectedToken) {
    message.warning('请先选择Token')
    return
  }
  
  try {
    isOperating[carId] = true
    const tokenId = tokenStore.selectedToken.id
    
    console.log(`🎁 开始收获车辆，ID: ${carId}`)
    message.info(`正在收获车辆: ${carId}`)
    
    const response = await tokenStore.sendMessageAsync(tokenId, 'car_claim', {
      carId: carId
    }, 5000)
    
    if (response) {
      console.log(`🎁 车辆收获成功，ID: ${carId}`, response)
      message.success(`车辆 ${carId} 收获成功`)
      
      // 收获后重新查询车辆列表
      await queryClubCars()
    } else {
      console.error(`🎁 车辆收获失败，ID: ${carId}`)
      message.error(`车辆 ${carId} 收获失败`)
    }
  } catch (error) {
    console.error('🎁 收获车辆出错:', error)
    message.error(`收获车辆 ${carId} 过程出错`)
  } finally {
    delete isOperating[carId]
  }
}

// 发送车辆
const sendCar = async (carId) => {
  if (!tokenStore.selectedToken) {
    message.warning('请先选择Token')
    return
  }
  
  // 检查每日发车次数限制
  if (dailySendCount.value >= 4) {
    console.warn(`⚠️ 今日发车次数已达上限: ${dailySendCount.value}/4`)
    message.warning('今日发车次数已达上限（4/4），明天再来吧！')
    return
  }
  
  try {
    isOperating[carId] = true
    const tokenId = tokenStore.selectedToken.id
    
    console.log(`🚀 开始发送车辆，ID: ${carId}（今日已发${dailySendCount.value}/4）`)
    message.info(`正在发送车辆: ${carId}`)
    
    const response = await tokenStore.sendMessageAsync(tokenId, 'car_send', {
      carId: carId,
      helperId: 0,
      text: ""
    }, 5000)
    
    if (response) {
      console.log(`🚀 车辆发送成功，ID: ${carId}`, response)
      // 发送成功后，增加今日发车次数
      dailySendCount.value++
      saveDailySendCount(dailySendCount.value) // 持久化到localStorage
      console.log(`✅ 今日发车次数更新: ${dailySendCount.value}/4`)
      message.success(`车辆 ${carId} 发送成功（今日已发${dailySendCount.value}/4）`)
      
      // 重新查询车辆列表
      await queryClubCars()
    } else {
      console.error(`🚀 车辆发送失败，ID: ${carId}`)
      message.error(`车辆 ${carId} 发送失败`)
    }
  } catch (error) {
    console.error('🚀 发送车辆出错:', error)
    message.error(`发送车辆 ${carId} 过程出错`)
  } finally {
    delete isOperating[carId]
  }
}

// 批量刷新车辆
const batchRefreshCars = async () => {
  if (!tokenStore.selectedToken || carData.value.length === 0) {
    message.warning('没有可刷新的车辆')
    return
  }
  
  try {
    isBatchOperating.value = true
    
    // 统计跳过的车辆
    let skippedCount = 0
    if (skipCarsWithTickets.value) {
      skippedCount = carData.value.filter(car => carHasRefreshTicket(car)).length
      if (skippedCount > 0) {
        console.log(`⏭️ 将跳过 ${skippedCount} 辆有刷新票的车辆`)
      }
    }
    
    const totalCars = carData.value.length
    const carsToRefresh = totalCars - skippedCount
    
    if (carsToRefresh === 0) {
      message.warning('所有车辆都有刷新票，已全部跳过')
      isBatchOperating.value = false
      return
    }
    
    message.info(`开始批量刷新 ${carsToRefresh}/${totalCars} 辆车${skippedCount > 0 ? `（跳过${skippedCount}辆）` : ''}...`)
    
    let successCount = 0
    let cdCount = 0 // 冷却中的车辆
    let failCount = 0
    
    for (let i = 0; i < carData.value.length; i++) {
      const car = carData.value[i]
      
      // 检查是否跳过有刷新票的车辆
      if (skipCarsWithTickets.value && carHasRefreshTicket(car)) {
        console.log(`⏭️ 跳过有刷新票的车辆: ${car.carId}`)
        continue
      }
      
      console.log(`🔄 批量刷新进度: ${successCount + cdCount + failCount + 1}/${carsToRefresh}`)
      
      try {
        await refreshCar(car.carId)
        successCount++
      } catch (error) {
        const errorMsg = error.message || String(error)
        if (errorMsg.includes('200020')) {
          cdCount++
        } else {
          failCount++
        }
      }
      
      // 添加间隔，避免请求过快
      if (i < carData.value.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 300))
      }
    }
    
    let resultMsg = `批量刷新完成！成功: ${successCount}`
    if (cdCount > 0) {
      resultMsg += `, 冷却中: ${cdCount}`
    }
    if (failCount > 0) {
      resultMsg += `, 失败: ${failCount}`
    }
    if (skippedCount > 0) {
      resultMsg += `, 跳过: ${skippedCount}`
    }
    
    if (cdCount > 0 || failCount > 0) {
      message.warning(resultMsg)
    } else {
      message.success(resultMsg)
    }
    
    // 重新查询车辆列表
    await queryClubCars()
  } catch (error) {
    console.error('批量刷新出错:', error)
    message.error('批量刷新过程出错')
  } finally {
    isBatchOperating.value = false
  }
}

// 一键发车（收获 + 发送）
const batchClaimAndSendCars = async () => {
  if (!tokenStore.selectedToken || carData.value.length === 0) {
    message.warning('没有可操作的车辆')
    return
  }
  
  try {
    isBatchOperating.value = true
    message.info(`开始一键发车，共 ${carData.value.length} 辆车...`)
    
    let claimSuccessCount = 0
    let claimFailCount = 0
    let sendSuccessCount = 0
    let sendFailCount = 0
    
    // 第一步：批量收获
    console.log('🎁 第1步：批量收获车辆')
    
    // 筛选已到达的车辆（state: 2）
    const arrivedCars = carData.value.filter(car => car.state === 2)
    const waitingCars = carData.value.filter(car => car.state !== 2)
    
    if (arrivedCars.length === 0) {
      message.warning('没有已到达的车辆可以收获')
      console.log('⚠️ 所有车辆都未到达终点')
    } else {
      console.log(`🎁 找到 ${arrivedCars.length} 辆已到达的车辆`)
    }
    
    for (let i = 0; i < arrivedCars.length; i++) {
      const car = arrivedCars[i]
      console.log(`🎁 收获进度: ${i + 1}/${arrivedCars.length}`)
      
      try {
        await claimCar(car.carId)
        claimSuccessCount++
      } catch (error) {
        console.error(`收获车辆 ${car.carId} 失败:`, error)
        claimFailCount++
      }
      
      // 添加间隔，避免请求过快
      if (i < arrivedCars.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 300))
      }
    }
    
    // 统计运输中的车辆（state: 1）
    const shippingCars = carData.value.filter(car => car.state === 1)
    if (shippingCars.length > 0) {
      console.log(`⚠️ 跳过 ${shippingCars.length} 辆运输中的车辆:`, shippingCars.map(c => c.carId))
    }
    
    console.log(`🎁 收获完成：成功 ${claimSuccessCount}, 失败 ${arrivedCars.length - claimSuccessCount}`)
    
    if (claimSuccessCount === 0 && arrivedCars.length > 0) {
      // 有已到达的车辆但全部收获失败
      message.error(`收获失败！${arrivedCars.length}辆已到达的车辆全部收获失败`)
      await queryClubCars()
      isBatchOperating.value = false
      return
    }
    
    if (claimSuccessCount > 0) {
      message.info(`收获完成！成功: ${claimSuccessCount}, 失败: ${arrivedCars.length - claimSuccessCount}。开始发送...`)
      // 等待1秒，重新查询车辆列表获取待发车的车辆
      await new Promise(resolve => setTimeout(resolve, 1000))
      // 重新查询车辆列表
      await queryClubCars()
    } else {
      console.log('💡 没有需要收获的车辆，直接进入发送步骤')
    }
    
    // 第二步：批量发送待发车的车辆（state: 0）
    console.log('🚀 第2步：批量发送车辆')
    
    // 检查每日发车次数限制
    if (dailySendCount.value >= 4) {
      console.warn(`⚠️ 今日发车次数已达上限: ${dailySendCount.value}/4，跳过发送步骤`)
      message.warning(`今日发车次数已达上限（${dailySendCount.value}/4），明天再来吧！`)
      await queryClubCars()
      isBatchOperating.value = false
      return
    }
    
    // 筛选待发车的车辆（state: 0）
    const readyToSendCars = carData.value.filter(car => car.state === 0)
    const currentShippingCars = carData.value.filter(car => car.state === 1)
    
    // 计算剩余可发车次数
    const remainingSendCount = 4 - dailySendCount.value
    console.log(`📊 今日已发${dailySendCount.value}辆，剩余可发${remainingSendCount}辆`)
    
    if (readyToSendCars.length === 0) {
      if (claimSuccessCount === 0 && currentShippingCars.length > 0) {
        // 全部都在运输中
        message.info(`所有车辆都在运输中，无需操作`)
        console.log('⚠️ 所有车辆都在运输中')
        await queryClubCars()
        isBatchOperating.value = false
        return
      } else if (claimSuccessCount === 0) {
        // 没有任何车辆
        message.warning('没有可操作的车辆')
        console.log('⚠️ 没有可操作的车辆')
        await queryClubCars()
        isBatchOperating.value = false
        return
      }
      console.log('⚠️ 没有待发车的车辆')
    } else {
      console.log(`🚀 找到 ${readyToSendCars.length} 辆待发车的车辆`)
      
      // 如果待发车数量大于剩余可发数量，显示提示
      if (readyToSendCars.length > remainingSendCount) {
        console.log(`⚠️ 待发车${readyToSendCars.length}辆，但今日仅剩${remainingSendCount}个发车名额`)
        message.info(`今日剩余${remainingSendCount}个发车名额，将优先发送前${remainingSendCount}辆车`)
      }
    }
    
    // 限制发送数量不超过剩余可发次数
    const carsToSend = readyToSendCars.slice(0, remainingSendCount)
    
    for (let i = 0; i < carsToSend.length; i++) {
      const car = carsToSend[i]
      console.log(`🚀 发送进度: ${i + 1}/${carsToSend.length}（今日已发${dailySendCount.value}/4）`)
      
      try {
        await sendCar(car.carId)
        sendSuccessCount++
        
        // 发送成功后检查是否达到上限（sendCar内部会增加计数）
        if (dailySendCount.value >= 4) {
          console.log(`✅ 今日发车次数已达上限，停止继续发送`)
          break
        }
      } catch (error) {
        const errorMsg = error.message || String(error)
        console.error(`发送车辆 ${car.carId} 失败:`, error)
        // 错误码 200020 可能是冷却期
        if (errorMsg.includes('200020')) {
          console.log(`⚠️ 车辆 ${car.carId} 处于发送冷却期`)
        }
        sendFailCount++
      }
      
      // 添加间隔，避免请求过快
      if (i < carsToSend.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 300))
      }
    }
    
    // 统计运输中的车辆（无法发送）
    if (currentShippingCars.length > 0) {
      console.log(`⚠️ 跳过 ${currentShippingCars.length} 辆运输中的车辆:`, currentShippingCars.map(c => c.carId))
    }
    
    console.log(`🚀 发送完成：成功 ${sendSuccessCount}, 失败 ${sendFailCount}`)
    
    // 生成统计消息
    let summaryMsg = '一键发车完成！'
    if (claimSuccessCount > 0) {
      summaryMsg += ` 收获: ${claimSuccessCount}辆,`
    }
    if (sendSuccessCount > 0) {
      summaryMsg += ` 发送: ${sendSuccessCount}辆`
    }
    if (currentShippingCars.length > 0) {
      summaryMsg += ` (${currentShippingCars.length}辆运输中)`
    }
    
    message.success(summaryMsg)
    
    // 重新查询车辆列表
    await queryClubCars()
  } catch (error) {
    console.error('一键发车出错:', error)
    message.error('一键发车过程出错')
  } finally {
    isBatchOperating.value = false
  }
}
</script>

<style scoped lang="scss">
.car-management {
  .car-management-card {
    background: var(--bg-primary);
    border-radius: var(--border-radius-xl);
    padding: var(--spacing-lg);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), 0 1px 3px rgba(0, 0, 0, 0.02);
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4px;
      background: linear-gradient(90deg, #667eea, #764ba2);
      opacity: 0.8;
      transition: opacity 0.3s ease;
    }
    
    &:hover {
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.04);
      transform: translateY(-4px);
      
      &::before {
        opacity: 1;
      }
    }
  }

  .card-header {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-md);
    margin-bottom: var(--spacing-lg);

    .status-icon {
      width: 32px;
      height: 32px;
      object-fit: contain;
      flex-shrink: 0;
    }

    .status-info {
      flex: 1;

      h3 {
        font-size: var(--font-size-md);
        font-weight: var(--font-weight-semibold);
        color: var(--text-primary);
        margin: 0 0 var(--spacing-xs) 0;
      }

      p {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        margin: 0;
      }
    }

    .header-stats {
      display: flex;
      gap: var(--spacing-sm);
      align-items: center;
    }

    .refresh-ticket-badge {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 12px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: var(--border-radius-md);
      box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
      transition: all var(--transition-normal);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }

      .ticket-icon {
        font-size: 16px;
      }

      .ticket-count {
        font-size: var(--font-size-sm);
        font-weight: var(--font-weight-semibold);
        color: white;
      }
    }

    .send-count-badge {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 12px;
      background: linear-gradient(135deg, #34d399 0%, #10b981 100%);
      border-radius: var(--border-radius-md);
      box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
      transition: all var(--transition-normal);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
      }

      &.limit-reached {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
        animation: pulse 2s ease-in-out infinite;

        &:hover {
          box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
        }
      }

      .car-icon {
        font-size: 16px;
      }

      .send-count {
        font-size: var(--font-size-sm);
        font-weight: var(--font-weight-semibold);
        color: white;
      }
    }

    @keyframes pulse {
      0%, 100% {
        opacity: 1;
      }
      50% {
        opacity: 0.8;
      }
    }

    .status-badge {
      display: flex;
      align-items: center;
      gap: var(--spacing-xs);
      padding: var(--spacing-xs) var(--spacing-sm);
      border-radius: var(--border-radius-full);
      font-size: var(--font-size-sm);
      font-weight: var(--font-weight-medium);
      background: rgba(156, 163, 175, 0.1);
      color: var(--text-secondary);

      &.active {
        background: rgba(34, 197, 94, 0.1);
        color: var(--success-color);
      }

      .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: currentColor;
      }
    }
  }

  .card-content {
    .query-btn {
      margin-bottom: var(--spacing-md);
    }

    .car-list {
      max-height: 700px;
      overflow-y: auto;
      margin-bottom: var(--spacing-md);
      
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: var(--bg-tertiary);
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: var(--border-light);
        border-radius: 3px;
        
        &:hover {
          background: var(--text-tertiary);
        }
      }
    }

    .car-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: var(--spacing-sm);
      margin-bottom: var(--spacing-xs);
      border-radius: var(--border-radius-medium);
      background: var(--bg-secondary);
      border-left: 3px solid var(--border-light);
      transition: all var(--transition-fast);

      &:hover {
        background: var(--bg-tertiary);
        transform: translateX(2px);
      }

      &.quality-1 { border-left-color: #4ade80; }
      &.quality-2 { border-left-color: #60a5fa; }
      &.quality-3 { border-left-color: #a78bfa; }
      &.quality-4 { border-left-color: #fb923c; }
      &.quality-5 { border-left-color: #f87171; }
      &.quality-6 { border-left-color: #fbbf24; }

      .car-info {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        flex: 1;

        .car-index {
          font-weight: var(--font-weight-bold);
          color: var(--text-tertiary);
          font-size: var(--font-size-sm);
          min-width: 24px;
        }

        .car-details {
          flex: 1;

          .car-header-row {
            display: flex;
            align-items: center;
            gap: 8px;
            justify-content: space-between;
            margin-bottom: 4px;
          }

          .car-id {
            font-size: var(--font-size-sm);
            color: var(--text-primary);
            font-weight: var(--font-weight-medium);
            flex: 1;
          }

          .car-state-badge {
            font-size: 11px;
            font-weight: var(--font-weight-semibold);
            padding: 2px 8px;
            border-radius: 12px;
            white-space: nowrap;
            flex-shrink: 0;
            
            &.state-waiting {
              background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
              color: white;
              box-shadow: 0 1px 4px rgba(251, 191, 36, 0.3);
            }
            
            &.state-shipping {
              background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
              color: white;
              box-shadow: 0 1px 4px rgba(59, 130, 246, 0.3);
              animation: pulse 2s ease-in-out infinite;
            }
            
            &.state-arrived {
              background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
              color: white;
              box-shadow: 0 1px 4px rgba(34, 197, 94, 0.3);
            }
          }

          .transport-progress {
            margin-top: 6px;
            margin-bottom: 4px;
            
            .progress-info {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 4px;
              font-size: 11px;
              color: var(--text-secondary);
              
              .progress-text {
                font-weight: var(--font-weight-medium);
              }
              
              .remaining-time {
                color: var(--text-tertiary);
                font-weight: var(--font-weight-normal);
              }
            }
            
            .progress-bar {
              height: 4px;
              background: var(--bg-tertiary);
              border-radius: 2px;
              overflow: hidden;
              
              .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, 
                  #3b82f6 0%, 
                  #60a5fa 25%, 
                  #93c5fd 50%, 
                  #60a5fa 75%, 
                  #3b82f6 100%
                );
                background-size: 200% 100%;
                border-radius: 2px;
                transition: width 0.3s ease;
                animation: shimmer 2s ease-in-out infinite;
              }
            }
          }

          .car-quality {
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-medium);
            margin-top: 2px;
          }

          .car-rewards-section {
            margin-top: 4px;
            
            .car-rewards {
              font-size: var(--font-size-xs);
              display: flex;
              align-items: flex-start;
              gap: 4px;
              
              .rewards-label {
                color: var(--text-tertiary);
                font-weight: var(--font-weight-medium);
                flex-shrink: 0;
              }
              
              .rewards-content {
                color: var(--text-primary);
                font-weight: var(--font-weight-medium);
                background: rgba(34, 197, 94, 0.1);
                padding: 2px 6px;
                border-radius: 4px;
                line-height: 1.4;
              }
              
              &.no-rewards .rewards-content {
                color: var(--text-tertiary);
                background: rgba(156, 163, 175, 0.1);
              }
            }
          }
        }
      }

      .car-actions {
        display: flex;
        gap: var(--spacing-xs);

        .mini-btn {
          width: 32px;
          height: 32px;
          border: none;
          border-radius: var(--border-radius-small);
          cursor: pointer;
          font-size: 14px;
          transition: all var(--transition-fast);
          display: flex;
          align-items: center;
          justify-content: center;

          &:hover:not(:disabled) {
            transform: scale(1.1);
          }

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }

          &.refresh-btn {
            background: rgba(59, 130, 246, 0.1);
            &:hover:not(:disabled) {
              background: rgba(59, 130, 246, 0.2);
            }
          }

          &.claim-btn {
            background: rgba(34, 197, 94, 0.1);
            &:hover:not(:disabled) {
              background: rgba(34, 197, 94, 0.2);
            }
          }

          &.send-btn {
            background: rgba(245, 158, 11, 0.1);
            &:hover:not(:disabled) {
              background: rgba(245, 158, 11, 0.2);
            }
          }
        }
      }
    }

    .refresh-settings {
      padding: var(--spacing-md);
      background: rgba(var(--primary-color-rgb), 0.05);
      border-radius: var(--border-radius-md);
      border: 1px solid rgba(var(--primary-color-rgb), 0.1);
      margin-bottom: var(--spacing-md);
      
      .setting-item {
        display: flex;
        flex-direction: column;
        gap: var(--spacing-xs);
      }
      
      .setting-label {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        cursor: pointer;
        user-select: none;
        
        &:hover .checkbox-text {
          color: var(--primary-color);
        }
      }
      
      .setting-checkbox {
        width: 18px;
        height: 18px;
        cursor: pointer;
        accent-color: var(--primary-color);
      }
      
      .checkbox-text {
        font-size: var(--font-size-sm);
        font-weight: var(--font-weight-medium);
        color: var(--text-primary);
        transition: color var(--transition-fast);
      }
      
      .setting-hint {
        font-size: var(--font-size-xs);
        color: var(--text-secondary);
        padding-left: 26px;
      }
    }

    .batch-actions {
      display: flex;
      gap: var(--spacing-sm);

      .batch-btn {
        flex: 1;
      }
    }

    .empty-state {
      text-align: center;
      padding: var(--spacing-xl) var(--spacing-md);
      color: var(--text-secondary);

      p {
        margin: 0 0 var(--spacing-xs) 0;
        font-size: var(--font-size-sm);
      }

      .hint {
        font-size: var(--font-size-xs);
        color: var(--text-tertiary);
      }
    }
  }

  .action-button {
    width: 100%;
    padding: var(--spacing-sm) var(--spacing-md);
    border: none;
    border-radius: var(--border-radius-medium);
    font-size: var(--font-size-sm);
    font-weight: var(--font-weight-medium);
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
      transition: left 0.5s;
    }

    &:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
      
      &::before {
        left: 100%;
      }
    }
    
    &:active {
      transform: translateY(0);
      box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    }

    &:disabled {
      background: var(--bg-tertiary);
      color: var(--text-tertiary);
      cursor: not-allowed;
      transform: none;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      &::before {
        display: none;
      }
    }

    &.secondary {
      background: linear-gradient(135deg, #6b7280, #9ca3af);
      box-shadow: 0 4px 12px rgba(107, 114, 128, 0.3);
      
      &:hover:not(:disabled) {
        box-shadow: 0 6px 16px rgba(107, 114, 128, 0.4);
      }
      
      &:active {
        box-shadow: 0 2px 8px rgba(107, 114, 128, 0.3);
      }
    }
  }

  .loading-text {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: var(--spacing-xs);
  }

  .loading-icon {
    width: 16px;
    height: 16px;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }

  @keyframes pulse {
    0%, 100% {
      box-shadow: 0 1px 4px rgba(59, 130, 246, 0.3);
      transform: scale(1);
    }
    50% {
      box-shadow: 0 2px 8px rgba(59, 130, 246, 0.6);
      transform: scale(1.05);
    }
  }

  @keyframes shimmer {
    0% {
      background-position: -100% 0;
    }
    100% {
      background-position: 200% 0;
    }
  }
}
</style>



