<template>
  <figure class="image-node">
    <img class="image-node__img" :src="resolvedSrc" :alt="altText" loading="lazy" @error="onError" />
    <figcaption v-if="captionText" class="image-node__caption">{{ captionText }}</figcaption>
  </figure>
</template>

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

const props = defineProps({
  node: {
    type: Object,
    default: () => ({})
  },
  placeholderSrc: {
    type: String,
    default: ''
  }
})

const hasError = ref(false)

const rawSrc = computed(() => {
  const payload = props.node?.content_payload || {}
  return String(payload.img_path || payload.preview_img_path || '').trim()
})
const altText = computed(() => String(props.node?.content_payload?.alt_text || '图片'))
const captionText = computed(() => String(props.node?.content_payload?.caption || '').trim())

const resolvedSrc = computed(() => {
  if (hasError.value) return props.placeholderSrc
  if (!rawSrc.value) return props.placeholderSrc
  if (/^(https?:)?\/\//i.test(rawSrc.value) || /^(data|blob):/i.test(rawSrc.value)) return rawSrc.value
  const normalizedPath = rawSrc.value.replaceAll('\\', '/')
  const baseUrl = String(import.meta.env.VITE_INTELLIGENT_TRANSLATION_ASSET_BASE_URL || import.meta.env.VITE_BASE_FILE_URL || '').trim()
  if (!baseUrl) return normalizedPath.startsWith('/') ? normalizedPath : `/${normalizedPath}`
  return `${baseUrl.replace(/\/+$/, '')}/${normalizedPath.replace(/^\/+/, '')}`
})

function onError() {
  hasError.value = true
}
</script>

<style scoped lang="scss">
.image-node {
  margin: 0;
}

.image-node__img {
  width: 100%;
  min-height: 120px;
  object-fit: contain;
  border-radius: 6px;
  border: 1px solid #e4e7ec;
  background: #f8fafc;
}

.image-node__caption {
  margin-top: 8px;
  font-size: 12px;
  color: #667085;
}
</style>
