<template>
  <div class="envelope-layout">
    <!-- 信封头部 -->
    <div class="envelope-header" :class="{ expanded: showHeaderDetail }">
      <!-- 紧凑发件人行（默认显示） -->
      <div class="envelope-compact-row">
        <div class="compact-left">
          <div class="sender-avatar">
            <span class="avatar-text">{{ avatarLetter }}</span>
          </div>
          <div class="compact-sender">
            <span class="sender-name">{{ senderFullName || senderEmail }}</span>
            <span v-if="recipientList.length > 0" class="compact-arrow" @click="showHeaderDetail = !showHeaderDetail">
              <Icon icon="tabler:arrow-right" :size="14" />
            </span>
            <span v-if="recipientList.length > 0" class="compact-to" @click="showHeaderDetail = !showHeaderDetail">
              {{ compactRecipientText }}
            </span>
            <span
              class="direction-tag"
              :class="isIncoming ? 'direction-in' : 'direction-out'"
              @click="showHeaderDetail = !showHeaderDetail"
            >
              <Icon :icon="isIncoming ? 'tabler:arrow-down-left' : 'tabler:arrow-up-right'" :size="12" />
            </span>
          </div>
        </div>
        <div class="compact-right">
          <span v-if="deliveryBadge" class="delivery-badge" :class="deliveryBadge.class">{{ deliveryBadge.label }}</span>
          <span class="compact-date">{{ formatDateTime(record.communication_date) }}</span>
          <button class="detail-toggle-btn" @click="showHeaderDetail = !showHeaderDetail">
            <Icon :icon="showHeaderDetail ? 'tabler:chevron-up' : 'tabler:chevron-down'" :size="16" />
          </button>
        </div>
      </div>

      <!-- 展开详情（点击显示） -->
      <transition name="header-expand">
        <div v-if="showHeaderDetail" class="envelope-detail">
          <div class="detail-row">
            <span class="detail-label">{{ t('To') }}</span>
            <span class="detail-value">
              {{ recipientList.join(', ') || '—' }}
            </span>
          </div>
          <div class="detail-row" v-if="ccList.length > 0">
            <span class="detail-label">{{ t('Cc') }}</span>
            <span class="detail-value">{{ ccList.join(', ') }}</span>
          </div>
          <div class="detail-row" v-if="bccList.length > 0">
            <span class="detail-label">{{ t('Bcc') }}</span>
            <span class="detail-value">{{ bccList.join(', ') }}</span>
          </div>
          <div class="detail-row" v-if="senderEmail && senderFullName">
            <span class="detail-label">{{ t('From') }}</span>
            <span class="detail-value">{{ senderEmail }}</span>
          </div>
        </div>
      </transition>

      <!-- 参考链接 & 附件条 -->
      <div class="envelope-extras" v-if="hasExtras">
        <div class="reference-link" v-if="record.reference_pagetype && record.reference_name" @click="emit('goToReference')">
          <Icon icon="tabler:link" :size="14" />
          <span class="ref-label">{{ t(record.reference_pagetype) }}:</span>
          <span class="ref-name">{{ record.reference_name }}</span>
          <Icon icon="tabler:external-link" :size="12" class="ref-arrow" />
        </div>
        <div class="attachments-bar" v-if="attachments.length > 0">
          <Icon icon="tabler:paperclip" :size="14" />
          <span class="attach-count">{{ attachments.length }} {{ t('attachments') }}</span>
          <div class="attach-chips">
            <a
              v-for="(att, idx) in displayAttachments"
              :key="idx"
              :href="att.file_url"
              target="_blank"
              class="attach-chip"
              :title="att.file_name || att.name"
            >
              <Icon :icon="fileIcon(att)" :size="12" />
              <span class="attach-name">{{ att.file_name || att.name }}</span>
              <span v-if="att.file_size" class="attach-size">{{ formatFileSize(att.file_size) }}</span>
            </a>
            <button v-if="attachments.length > 3" class="toggle-detail-btn" @click="showFullAttachments = !showFullAttachments">
              {{ showFullAttachments ? t('less') : `+${attachments.length - 3}` }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 正文区域 -->
    <div class="envelope-body">
      <div class="body-content-wrapper">
        <!-- HTML 邮件内容 -->
        <div v-if="record.content" class="email-html-body" v-html="sanitizedContent"></div>
        <!-- 纯文本回退 -->
        <div v-else-if="record.text_content" class="email-text-body">
          <pre>{{ record.text_content }}</pre>
        </div>
        <!-- 空内容 -->
        <div v-else class="email-empty-body">
          <Icon icon="tabler:mail-off" :size="32" />
          <span>{{ t('No content') }}</span>
        </div>
      </div>
    </div>

    <!-- 快捷回复栏 -->
    <div class="quick-reply-bar" v-if="canReply">
      <div class="quick-reply-actions">
        <n-button size="medium" @click="emit('reply')" class="quick-action-btn">
          <template #icon><n-icon><Icon icon="tabler:arrow-back-up" /></n-icon></template>
          {{ t('Reply') }}
        </n-button>
        <n-button size="medium" @click="emit('replyAll')" class="quick-action-btn">
          <template #icon><n-icon><Icon icon="tabler:arrow-back-up-double" /></n-icon></template>
          {{ t('Reply All') }}
        </n-button>
        <n-button size="medium" @click="emit('forward')" class="quick-action-btn">
          <template #icon><n-icon><Icon icon="tabler:arrow-forward-up" /></n-icon></template>
          {{ t('Forward') }}
        </n-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton, NIcon } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { formatDateTimeInTimezone } from '@/shared/utils/timezone'

// ===== Props =====
const props = defineProps<{
  record: Record<string, any>
  attachments?: any[]
  statusBadge?: { label: string; class: string } | null
  deliveryBadge?: { label: string; class: string } | null
}>()

// ===== Emits =====
const emit = defineEmits<{
  reply: []
  replyAll: []
  forward: []
  goToReference: []
}>()

// ===== Internal state =====
const showHeaderDetail = ref(false)
const showFullAttachments = ref(false)

// ===== Computed =====
const senderEmail = computed(() => {
  const raw = props.record.sender || ''
  const match = raw.match(/<(.+?)>/)
  return match ? match[1] : raw
})

const senderFullName = computed(() => {
  const raw = props.record.sender || ''
  const match = raw.match(/^(.+?)\s*<.*>$/)
  return match ? match[1].trim().replace(/^"|"$/g, '') : ''
})

const avatarLetter = computed(() => {
  const name = senderFullName.value || senderEmail.value
  return name.charAt(0).toUpperCase()
})

const isIncoming = computed(() => props.record.sent_or_received === 'Received')
const canReply = computed(() => isIncoming.value)

const recipientList = computed(() => splitEmailList(props.record.recipients || ''))
const ccList = computed(() => splitEmailList(props.record.cc || ''))
const bccList = computed(() => splitEmailList(props.record.bcc || ''))

const compactRecipientText = computed(() => {
  const list = recipientList.value
  if (list.length === 0) return ''
  if (list.length === 1) return list[0]
  return `${list[0]} ...`
})

const attachmentList = computed(() => props.attachments || [])
const displayAttachments = computed(() => {
  if (showFullAttachments.value || attachmentList.value.length <= 3) return attachmentList.value
  return attachmentList.value.slice(0, 3)
})
const hasExtras = computed(() =>
  (props.record.reference_pagetype && props.record.reference_name) || attachmentList.value.length > 0
)

const sanitizedContent = computed(() => sanitizeHtml(props.record.content || ''))

// ===== HTML Sanitization =====
function sanitizeHtml(html: string): string {
  if (!html) return ''
  const textarea = document.createElement('textarea')
  textarea.innerHTML = html
  const decoded = textarea.value
  const parser = new DOMParser()
  const pg = parser.parseFromString(decoded, 'text/html')
  const dangerousSelectors = ['script', 'style', 'iframe', 'object', 'embed', 'applet', 'link[rel="stylesheet"]', 'meta', 'base']
  dangerousSelectors.forEach(sel => {
    pg.querySelectorAll(sel).forEach(el => el.remove())
  })
  pg.querySelectorAll('*').forEach(el => {
    const attrs = Array.from(el.attributes)
    attrs.forEach(attr => {
      if (/^on/i.test(attr.name)) el.removeAttribute(attr.name)
      if (/^\s*(javascript|vbscript|data\s*:\s*text\/html)/i.test(attr.value)) el.removeAttribute(attr.name)
    })
  })
  return pg.body.innerHTML
}

// ===== Helpers =====
function splitEmailList(str: string): string[] {
  if (!str) return []
  return str.split(/[;,]/).map(s => s.trim()).filter(Boolean)
}

function formatDateTime(value: any): string {
  if (!value) return '—'
  try {
    return formatDateTimeInTimezone(value)
  } catch { return String(value) }
}

function formatFileSize(bytes: any): string {
  if (!bytes) return ''
  const n = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes
  if (isNaN(n)) return ''
  if (n < 1024) return n + ' B'
  if (n < 1048576) return (n / 1024).toFixed(1) + ' KB'
  return (n / 1048576).toFixed(1) + ' MB'
}

function fileIcon(att: any): string {
  const name = (att.file_name || att.name || '').toLowerCase()
  if (/\.(pdf)$/.test(name)) return 'tabler:file-type-pdf'
  if (/\.(doc|docx)$/.test(name)) return 'tabler:file-type-doc'
  if (/\.(xls|xlsx)$/.test(name)) return 'tabler:file-type-xls'
  if (/\.(png|jpg|jpeg|gif|webp|svg)$/.test(name)) return 'tabler:photo'
  if (/\.(zip|rar|7z|tar|gz)$/.test(name)) return 'tabler:file-zip'
  return 'tabler:file'
}
</script>

<style scoped>
/* ====== Envelope Layout ====== */
.envelope-layout {
  background: #ffffff;
  --envelope-px: 32px;
}

/* ====== Envelope Header ====== */
.envelope-header {
  padding: 28px var(--envelope-px) 20px;
  border-bottom: 1px solid #f0f0f0;
}

/* Status & Delivery badges */
.status-badge, .delivery-badge {
  font-size: 11px;
  font-weight: 600;
  padding: 3px 10px;
  border-radius: 12px;
  white-space: nowrap;
  flex-shrink: 0;
}
.status-badge.status-open { background: #dbeafe; color: #1d4ed8; }
.status-badge.status-replied { background: #d1fae5; color: #065f46; }
.status-badge.status-closed { background: #f3f4f6; color: #6b7280; }
.status-badge.status-linked { background: #ede9fe; color: #5b21b6; }
.delivery-badge.delivery-opened { background: #d1fae5; color: #065f46; }
.delivery-badge.delivery-bounced { background: #fee2e2; color: #991b1b; }
.delivery-badge.delivery-error { background: #fee2e2; color: #991b1b; }
.delivery-badge.delivery-sending { background: #fef3c7; color: #92400e; }
.delivery-badge.delivery-scheduled { background: #e0e7ff; color: #3730a3; }

/* Compact sender row (Gmail-style) */
.envelope-compact-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  gap: 12px;
}

.compact-left {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  flex: 1;
}

.sender-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-text {
  color: #6b7280;
  font-size: 14px;
  font-weight: 600;
}

.compact-sender {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.sender-name {
  font-weight: 600;
  font-size: 14px;
  color: #111827;
  white-space: nowrap;
}

.compact-arrow {
  color: #9ca3af;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: color 0.15s;
}
.compact-arrow:hover { color: #3b82f6; }

.direction-tag {
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  cursor: pointer;
  transition: color 0.15s;
}
.direction-tag.direction-in {
  color: #1d4ed8;
}
.direction-tag.direction-in :deep(svg) {
  color: #1d4ed8;
}
.direction-tag.direction-out {
  color: #10b981;
}
.direction-tag.direction-out :deep(svg) {
  color: #10b981;
}

.compact-to {
  font-size: 13px;
  color: #6b7280;
  cursor: pointer;
  white-space: nowrap;
  transition: color 0.15s;
}
.compact-to:hover { color: #3b82f6; }

.compact-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.compact-date {
  font-size: 13px;
  color: #6b7280;
  white-space: nowrap;
}

.detail-toggle-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  border: none;
  background: transparent;
  color: #9ca3af;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s;
}

.detail-toggle-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

/* Expanded detail panel */
.envelope-detail {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.detail-row {
  display: flex;
  align-items: baseline;
  gap: 12px;
  font-size: 13px;
  line-height: 1.6;
}

.detail-label {
  color: #9ca3af;
  font-weight: 500;
  min-width: 56px;
  flex-shrink: 0;
  text-align: right;
}

.detail-value {
  color: #374151;
  word-break: break-all;
}

/* Transition */
.header-expand-enter-active,
.header-expand-leave-active {
  transition: all 0.2s ease;
  overflow: hidden;
}
.header-expand-enter-from,
.header-expand-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}
.header-expand-enter-to,
.header-expand-leave-from {
  opacity: 1;
  max-height: 200px;
}

.toggle-detail-btn {
  background: none;
  border: none;
  color: #3b82f6;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  padding: 0;
  white-space: nowrap;
}
.toggle-detail-btn:hover { text-decoration: underline; }

/* Extras row: reference link & attachments */
.envelope-extras {
  margin-top: 16px;
  padding-top: 14px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.reference-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #f0f7ff;
  border-radius: 8px;
  font-size: 13px;
  color: #1d4ed8;
  cursor: pointer;
  transition: background 0.15s;
  width: fit-content;
}
.reference-link:hover { background: #dbeafe; }

.ref-label { font-weight: 500; }
.ref-name { font-weight: 600; }
.ref-arrow { opacity: 0.5; }

.attachments-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  font-size: 13px;
  color: #6b7280;
}

.attach-count {
  font-weight: 500;
  color: #374151;
}

.attach-chips {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.attach-chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 12px;
  color: #374151;
  text-decoration: none;
  transition: all 0.15s;
  max-width: 220px;
}
.attach-chip:hover { background: #f0f0f0; border-color: #d1d5db; }

.attach-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 140px;
}

.attach-size {
  color: #9ca3af;
  font-size: 11px;
  flex-shrink: 0;
}

/* ====== Email Body ====== */
.envelope-body {
  padding: 0 var(--envelope-px);
  min-height: 200px;
}

.body-content-wrapper {
  padding: 24px 0;
}

.email-html-body {
  font-size: 15px;
  line-height: 1.7;
  color: #1f2937;
  word-break: break-word;
  overflow-wrap: break-word;
}

.email-html-body :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

.email-html-body :deep(table) {
  max-width: 100%;
  overflow-x: auto;
  display: block;
}

.email-html-body :deep(a) {
  color: #2563eb;
  text-decoration: underline;
}

.email-html-body :deep(blockquote) {
  border-left: 3px solid #d1d5db;
  padding-left: 12px;
  margin-left: 0;
  color: #6b7280;
}

.email-text-body {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
}

.email-text-body pre {
  white-space: pre-wrap;
  word-break: break-word;
  font-family: inherit;
  font-size: 15px;
  line-height: 1.7;
  color: #1f2937;
  margin: 0;
}

.email-empty-body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 60px 0;
  color: #9ca3af;
  font-size: 15px;
}

/* ====== Quick Reply Bar ====== */
.quick-reply-bar {
  padding: 16px var(--envelope-px);
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.quick-reply-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quick-action-btn {
  font-weight: 500;
}

/* ====== Responsive ====== */
@media (max-width: 768px) {
  .envelope-layout { --envelope-px: 16px; }
  .envelope-header { padding-top: 20px; padding-bottom: 16px; }
  .quick-reply-bar { padding-top: 12px; padding-bottom: 12px; }
  .envelope-compact-row { flex-wrap: wrap; }
  .compact-left { min-width: 0; }
  .compact-date { font-size: 12px; }
}

@media (min-width: 769px) and (max-width: 1024px) {
  .envelope-layout { --envelope-px: 24px; }
  .envelope-header { padding-top: 24px; padding-bottom: 18px; }
  .quick-reply-bar { padding-top: 14px; }
}
</style>
