<template>
  <article class="poster-card" :class="{ 'is-readonly': readonly }" @click="handleClick">
    <div class="poster-thumb">
      <img :src="posterImageUrl" :alt="item.title" loading="lazy" />
      <span class="score-badge">{{ displayScore }}</span>
    </div>

    <div class="poster-body">
      <div class="poster-meta-row">
        <span class="poster-time">{{ displayFormattedDate }}</span>
      </div>
      <h3>{{ item.title }}</h3>
      <p v-if="item.originalName">{{ item.originalName }}</p>
      
      <!-- 导演和主演 -->
      <div v-if="item.directors" class="poster-director">
        <AppIcon name="movie" :size="14" /> {{ item.directors }}
      </div>
      <div v-if="item.casts" class="poster-casts">
        <AppIcon name="cast" :size="14" /> {{ item.casts }}
      </div>
      
      <!-- 简介按钮（点击打开弹窗） -->
      <div v-if="item.description" class="poster-description">
        <button 
          type="button" 
          class="description-toggle" 
          @click.stop="showDescriptionDialog = true"
        >
          <AppIcon name="detail" :size="14" /> 查看详情
        </button>
      </div>
      
      <div class="tag-list">
        <span v-for="tag in displayTags" :key="tag">{{ tag }}</span>
      </div>
    </div>

    <!-- 简介弹窗 -->
    <Teleport to="body">
      <Transition name="dialog-fade">
        <div v-if="showDescriptionDialog" class="description-overlay" @click.self="showDescriptionDialog = false">
          <div class="description-dialog">
            <div class="description-dialog__header">
              <h3>{{ item.title }} - 详情</h3>
              <button type="button" class="description-dialog__close" @click="showDescriptionDialog = false">✕</button>
            </div>
            <div class="description-dialog__body">
              <!-- 基本信息 -->
              <div v-if="item.description" class="detail-section">
                <h4><AppIcon name="description" :size="16" /> 简介</h4>
                <p class="detail-text">{{ item.description }}</p>
              </div>
              <div v-if="item.directors" class="detail-section">
                <h4><AppIcon name="movie" :size="16" /> 导演</h4>
                <p class="detail-text">{{ item.directors }}</p>
              </div>
              <div v-if="item.casts" class="detail-section">
                <h4><AppIcon name="cast" :size="16" /> 主演</h4>
                <p class="detail-text">{{ item.casts }}</p>
              </div>
              <div v-if="item.tags" class="detail-section">
                <h4><AppIcon name="tag" :size="16" /> 标签</h4>
                <div class="detail-tags">
                  <span v-for="tag in displayTags" :key="tag" class="detail-tag">{{ tag }}</span>
                </div>
              </div>
              <div v-if="item.score || item.rating" class="detail-section">
                <h4><AppIcon name="sparkle" :size="16" /> 评分</h4>
                <p class="detail-text">{{ displayScore }}</p>
              </div>
              <div v-if="item.category" class="detail-section">
                <h4><AppIcon name="folder-open" :size="16" /> 分类</h4>
                <p class="detail-text">{{ item.category }}</p>
              </div>
              <div v-if="item.status" class="detail-section">
                <h4><AppIcon name="info" :size="16" /> 状态</h4>
                <p class="detail-text">{{ displayStatus }}</p>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </article>
</template>

<script setup>
import { computed, ref } from 'vue'
import AppIcon from './AppIcon.vue'

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

const emit = defineEmits(['edit'])

// 简介弹窗显示状态
const showDescriptionDialog = ref(false)

// 显示海报图片 URL
const posterImageUrl = computed(() => {
  // 兼容多种字段名：poster, posterUrl, backdropUrl
  return props.item.poster || props.item.posterUrl || props.item.backdropUrl || ''
})

// 显示评分
const displayScore = computed(() => {
  const score = props.item.score ?? props.item.rating ?? 0
  return score ? `${score}` : '暂无评分'
})

// 格式化日期时间，将 ISO 8601 格式转换为友好格式
const displayFormattedDate = computed(() => {
  const raw = props.item.updatedAt || props.item.updateTime || props.item.createTime || ''
  if (!raw) return ''
  
  // 去掉 T 字符，将 2026-06-26T15:55:42 转换为 2026-06-26 15:55:42
  let formatted = raw.replace('T', ' ')
  
  // 如果有毫秒和时区信息（如 .000Z 或 +08:00），去掉
  formatted = formatted.replace(/\.\d+(Z|[+-]\d{2}:\d{2})?$/, '')
  
  return formatted
})

// 显示状态（用于弹窗）
const displayStatus = computed(() => {
  return props.item.status || '正常'
})

// 显示标签（兼容字符串和数组格式）
const displayTags = computed(() => {
  const tags = props.item.tags
  if (Array.isArray(tags)) return tags
  if (typeof tags === 'string' && tags.trim()) return tags.split(',').map(t => t.trim())
  return []
})

function handleClick() {
  if (!props.readonly) {
    emit('edit', props.item)
  }
}
</script>