<template>
  <v-dialog :model-value="modelValue" max-width="720" @update:model-value="$emit('update:modelValue', $event)">
    <v-card border>
      <v-card-title class="text-subtitle-1">
        {{ result?.name ?? '文件预览' }}
        <span v-if="result" class="text-caption text-medium-emphasis ml-2">
          ({{ formatSize(result.size) }})
        </span>
      </v-card-title>
      <v-card-text>
        <v-progress-linear v-if="loading" indeterminate class="mb-3" />
        <template v-else-if="result">
          <v-alert
            v-if="result.truncated"
            type="info"
            density="compact"
            variant="tonal"
            class="mb-2"
          >
            仅显示前 4KB 内容
          </v-alert>
          <v-alert
            v-if="result.encoding_hint !== 'text'"
            type="warning"
            density="compact"
            variant="tonal"
            class="mb-2"
          >
            二进制文件，以下为 Base64 片段
          </v-alert>
          <pre class="staging-preview-body">{{ previewText }}</pre>
        </template>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" @click="$emit('update:modelValue', false)">关闭</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { formatSize } from '@/composables/push/labels'
import type { StagingPreviewResult } from '@/composables/push/types'

const props = defineProps<{
  modelValue: boolean
  loading: boolean
  result: StagingPreviewResult | null
}>()

defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const previewText = computed(() => {
  const r = props.result
  if (!r?.content_base64) return ''
  try {
    const raw = atob(r.content_base64)
    if (r.encoding_hint === 'text') return raw
    return r.content_base64
  } catch {
    return r.content_base64
  }
})
</script>

<style scoped>
.staging-preview-body {
  max-height: 420px;
  overflow: auto;
  margin: 0;
  padding: 12px;
  border-radius: 8px;
  background: rgba(var(--v-theme-on-surface), 0.04);
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
