<script setup>
import { computed } from 'vue'
import { Check, CheckCheck, Clock, AlertCircle, FileText } from 'lucide-vue-next'

const props = defineProps({
  message: {
    type: Object,
    required: true
  },
  isSent: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['file-click'])

// 格式化时间
const formattedTime = computed(() => {
  const date = new Date(props.message.timestamp * 1000)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
})

// 状态图标
const statusIcon = computed(() => {
  switch (props.message.status) {
    case 'pending': return Clock
    case 'sent': return Check
    case 'delivered': return CheckCheck
    case 'read': return CheckCheck
    case 'failed': return AlertCircle
    default: return null
  }
})

const statusColor = computed(() => {
  switch (props.message.status) {
    case 'read': return 'text-primary-500'
    case 'failed': return 'text-red-500'
    default: return 'text-white/70'
  }
})

// 是否是图片消息
const isImage = computed(() => props.message.type === 'image')

// 是否是文件消息
const isFile = computed(() => props.message.type === 'file')

// 从文件消息中提取文件名（去掉 📎 前缀）
const fileName = computed(() => {
  if (isFile.value) {
    return props.message.content.replace(/^📎\s*/, '')
  }
  return ''
})

// 处理文件点击
function handleFileClick() {
  if (isFile.value && fileName.value) {
    emit('file-click', fileName.value)
  }
}
</script>

<template>
  <div 
    class="flex mb-3"
    :class="isSent ? 'justify-end' : 'justify-start'"
  >
    <div 
      class="message-bubble"
      :class="isSent ? 'sent' : 'received'"
    >
      <!-- 图片消息 -->
      <template v-if="isImage">
        <img 
          :src="message.content" 
          alt="图片"
          class="max-w-xs rounded-lg"
          loading="lazy"
        />
      </template>
      
      <!-- 文件消息 -->
      <template v-else-if="isFile">
        <div 
          class="flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity"
          @click="handleFileClick"
        >
          <FileText :size="20" />
          <span class="underline">{{ fileName }}</span>
        </div>
      </template>
      
      <!-- 文本消息 -->
      <template v-else>
        <p class="whitespace-pre-wrap">{{ message.content }}</p>
      </template>

      <!-- 时间和状态 -->
      <div 
        class="flex items-center gap-1 mt-1 text-xs"
        :class="isSent ? 'justify-end text-white/70' : 'text-gray-400'"
      >
        <span>{{ formattedTime }}</span>
        <component 
          v-if="isSent && statusIcon" 
          :is="statusIcon" 
          :size="12"
          :class="statusColor"
        />
      </div>
    </div>
  </div>
</template>
