<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useDeviceStore } from '@/stores/deviceStore'
import { useChatStore } from '@/stores/chatStore'
import { Monitor, Smartphone, Laptop, MessageSquare, Send } from 'lucide-vue-next'

const props = defineProps({
  device: {
    type: Object,
    required: true
  }
})

const router = useRouter()
const deviceStore = useDeviceStore()
const chatStore = useChatStore()

const isConnected = computed(() => deviceStore.isConnected(props.device.deviceId))
const unreadCount = computed(() => chatStore.getUnreadCount(props.device.deviceId))

// 根据设备名推断图标
const deviceIcon = computed(() => {
  const name = props.device.deviceName.toLowerCase()
  if (name.includes('phone') || name.includes('mobile') || name.includes('android') || name.includes('iphone')) {
    return Smartphone
  }
  if (name.includes('laptop') || name.includes('macbook') || name.includes('notebook')) {
    return Laptop
  }
  return Monitor
})

// 连接并进入聊天
async function openChat() {
  // 如果设备在线但未连接，先尝试连接
  if (props.device.online && !isConnected.value) {
    try {
      await deviceStore.connectToDevice(props.device.deviceId)
    } catch (error) {
      console.error('Connection failed:', error)
      // 连接失败也允许进入查看历史记录
    }
  }
  // 无论在线离线都允许进入聊天页面（离线时只能查看历史记录）
  router.push(`/chat/${props.device.deviceId}`)
}

// 选择文件发送（仅在线设备可用）
async function sendFile() {
  if (!props.device.online) return
  
  const file = await chatStore.selectFile()
  if (file) {
    router.push(`/chat/${props.device.deviceId}`)
  }
}
</script>

<template>
  <div 
    class="device-card group relative bg-white dark:bg-surface-800 rounded-2xl p-5 border border-surface-100 dark:border-surface-700/50 cursor-pointer hover:shadow-hard hover:border-primary-200/50 dark:hover:border-primary-700/30 transition-all duration-300"
    @click="openChat"
  >
    <!-- 悬停时出现的背景光晕 -->
    <div class="absolute inset-0 bg-gradient-to-br from-primary-50/50 to-transparent dark:from-primary-900/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-2xl pointer-events-none"></div>

    <div class="relative flex items-start gap-4">
      <!-- 设备图标 -->
      <div 
        class="w-14 h-14 rounded-2xl flex items-center justify-center shadow-sm transition-transform duration-300 group-hover:scale-105 group-hover:rotate-[-2deg]"
        :class="device.online ? 'bg-gradient-to-br from-primary-100 to-primary-50 dark:from-primary-900/40 dark:to-primary-800/20 text-primary-600 dark:text-primary-300' : 'bg-surface-100 dark:bg-surface-700 text-surface-400'"
      >
        <component :is="deviceIcon" :size="26" stroke-width="1.5" />
        
        <!-- 在线状态点 (集成在图标右下角) -->
        <div class="absolute -bottom-1 -right-1 p-0.5 bg-white dark:bg-surface-800 rounded-full">
            <span 
                class="block w-3 h-3 rounded-full border-2 border-white dark:border-surface-800 transition-colors duration-300"
                :class="isConnected ? 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.4)]' : (device.online ? 'bg-amber-400' : 'bg-surface-300 dark:bg-surface-600')"
            />
        </div>
      </div>

      <!-- 设备信息 -->
      <div class="flex-1 min-w-0 pt-0.5">
        <div class="flex items-center justify-between mb-1">
          <h3 class="font-semibold text-base text-surface-900 dark:text-surface-50 truncate pr-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
            {{ device.deviceName }}
          </h3>
        </div>
        
        <p class="text-xs font-medium text-surface-400 dark:text-surface-500 font-mono tracking-wide mb-3">
          {{ device.ip }}
        </p>

        <!-- 能力标签 -->
        <div class="flex flex-wrap gap-1.5">
          <span 
            v-for="cap in device.capabilities" 
            :key="cap"
            class="px-2 py-0.5 bg-surface-50 dark:bg-surface-700/50 border border-surface-100 dark:border-surface-700 text-surface-500 dark:text-surface-400 text-[10px] uppercase font-bold tracking-wider rounded-md"
          >
            {{ cap }}
          </span>
        </div>
      </div>

      <!-- 操作按钮 (悬停时更明显) -->
      <div class="flex flex-col gap-2 opacity-80 group-hover:opacity-100 transition-opacity">
        <button
          @click.stop="openChat"
          class="relative w-9 h-9 rounded-xl flex items-center justify-center bg-surface-50 dark:bg-surface-700/50 hover:bg-primary-500 hover:text-white dark:hover:bg-primary-500 text-surface-500 dark:text-surface-400 transition-all duration-200 hover:shadow-lg hover:shadow-primary-500/30 active:scale-95"
          :title="device.online ? '发送消息' : '查看聊天记录'"
        >
          <MessageSquare :size="18" stroke-width="2" />
          <span 
            v-if="unreadCount > 0"
            class="absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center border-2 border-white dark:border-surface-800 animate-bounce shadow-sm"
          >
            {{ unreadCount > 9 ? '9+' : unreadCount }}
          </span>
        </button>
        
        <button
          v-if="device.online"
          @click.stop="sendFile"
          class="w-9 h-9 rounded-xl flex items-center justify-center bg-surface-50 dark:bg-surface-700/50 hover:bg-green-500 hover:text-white dark:hover:bg-green-500 text-surface-500 dark:text-surface-400 transition-all duration-200 hover:shadow-lg hover:shadow-green-500/30 active:scale-95"
          title="发送文件"
        >
          <Send :size="18" stroke-width="2" />
        </button>
      </div>
    </div>
  </div>
</template>
