<script setup lang="ts">
import type { BlockData } from '@vigilkids/section-core'
import type { Ref } from 'vue'

import { computed, inject, nextTick, onMounted, ref, watch } from 'vue'

import {
  applyArticleImageInlineStyle,
  normalizeArticleImageDimension,
} from '../../../utils/article-image'
import { resolveContentVariables } from '../../../utils/content-variables'
import { renderContent } from '../prosemirror'

const props = defineProps<{
  blockOrder: string[]
  blocks: Record<string, BlockData>
  editorMode?: boolean
  settings: Record<string, unknown>
}>()

// 从 createPreviewApp 注入当前产品标识，用于加载对应产品的 CSS
const currentProduct = inject<Ref<string>>('currentProduct')
const productClass = computed(() => {
  const code = currentProduct?.value || 'vigilkids'
  return `article-content--${code}`
})

/* 兼容 article-prose 的 settings.content 字段（可能是 ProseMirror JSON） */
const htmlContent = computed(() => {
  const raw = props.settings.html_content ?? props.settings.content ?? ''
  return resolveContentVariables(renderContent(raw))
})

const contentRef = ref<HTMLElement | null>(null)

function normalizeSizedImages() {
  const root = contentRef.value
  if (!root)
    return

  root
    .querySelectorAll<HTMLImageElement>('img[width], img[height]')
    .forEach((image) => {
      if (image.classList.contains('hot-icon') || image.classList.contains('icon'))
        return

      const width = normalizeArticleImageDimension(image.getAttribute('width'))
      const height = normalizeArticleImageDimension(image.getAttribute('height'))
      image.classList.add('article-custom-html__sized-image')
      applyArticleImageInlineStyle(image, width, height, { maxWidth: '500px' })
    })
}

async function syncSizedImages() {
  await nextTick()
  normalizeSizedImages()
}

onMounted(() => {
  void syncSizedImages()
})

watch(htmlContent, () => {
  void syncSizedImages()
}, { flush: 'post' })

// ── v-html 内容的交互处理 ──
// SectionWrapper 的 @click.stop 阻止事件冒泡到 document，
// document 级事件委托无法捕获 v-html 内的点击，
// 所以直接在组件根元素上用 @click 处理
function handleContentClick(e: MouseEvent) {
  // FAQ 手风琴
  const faqTitle = (e.target as HTMLElement).closest?.('.faq-item-title')
  if (faqTitle) {
    e.stopPropagation()
    handleFaqToggle(faqTitle)
    return
  }

  // 链接拦截：阻止非锚点链接在 iframe 内导航
  const anchor = (e.target as HTMLElement).closest?.('a')
  if (anchor) {
    const href = anchor.getAttribute('href')
    if (!href?.startsWith('#'))
      e.preventDefault()
  }
}

function handleFaqToggle(faqTitle: Element) {
  const faqItem = faqTitle.closest('.faq-item')
  if (!faqItem)
    return

  const faqList = faqItem.closest('.faq-list')
  const isActive = faqItem.classList.contains('active')

  // 手风琴互斥：收起同组其他项
  if (faqList) {
    faqList.querySelectorAll('.faq-item.active').forEach((item) => {
      if (item !== faqItem) {
        item.classList.remove('active')
        const body = item.querySelector('.faq-item-answer') as HTMLElement | null
        if (body)
          body.style.maxHeight = '0'
      }
    })
  }

  // 切换当前项
  faqItem.classList.toggle('active', !isActive)
  const body = faqItem.querySelector('.faq-item-answer') as HTMLElement | null
  if (body)
    body.style.maxHeight = isActive ? '0' : `${body.scrollHeight}px`
}
</script>

<template>
  <div
    ref="contentRef"
    class="article-custom-html article-content"
    :class="[productClass]"
    @click="handleContentClick"
    v-html="htmlContent"
  />
</template>
