<template>
  <div class="dynamic-page">
    <p v-if="loading" class="state">加载中…</p>
    <p v-else-if="error" class="state error">{{ error }}</p>
    <template v-else>
      <h1 v-if="pageTitle" class="page-title">{{ pageTitle }}</h1>
      <BlockRenderer v-if="mode === 'builder' && builderBlocks.length" :blocks="builderBlocks" />
      <div v-else class="html-content" v-html="htmlContent"></div>
    </template>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import BlockRenderer from '../components/blocks/BlockRenderer.vue'
import { fetchWebPageByPath } from '../api/webPages'

const route = useRoute()
const loading = ref(true)
const error = ref('')
const pageTitle = ref('')
const mode = ref('html')
const htmlContent = ref('')
const builderBlocks = ref([])

function parsePath() {
  const p = route.path || '/'
  return p === '' ? '/' : p
}

async function load() {
  loading.value = true
  error.value = ''
  try {
    const path = parsePath()
    const data = await fetchWebPageByPath(path)
    pageTitle.value = data.title || ''
    document.title = data.title ? `${data.title} - 官网` : '官网'
    const cm = (data.content_mode || 'html').toLowerCase()
    mode.value = cm === 'builder' ? 'builder' : 'html'
    if (mode.value === 'builder' && data.content) {
      try {
        const json = JSON.parse(data.content)
        builderBlocks.value = Array.isArray(json.blocks) ? json.blocks : []
        if (!builderBlocks.value.length) {
          mode.value = 'html'
          htmlContent.value = data.content
        }
      } catch {
        mode.value = 'html'
        htmlContent.value = data.content || ''
      }
    } else {
      htmlContent.value = data.content || ''
      builderBlocks.value = []
    }
  } catch (e) {
    error.value = e.message || '页面加载失败'
    pageTitle.value = ''
    builderBlocks.value = []
    htmlContent.value = ''
  } finally {
    loading.value = false
  }
}

watch(() => route.path, load, { immediate: true })
</script>

<style scoped>
.state {
  text-align: center;
  padding: 48px 16px;
  color: #606266;
}
.state.error {
  color: #f56c6c;
}
.page-title {
  margin: 0 0 24px;
  font-size: 1.75rem;
  font-weight: 700;
}
</style>
