<template>
  <div class="space-y-8">
    <!-- Hero -->
    <section class="space-y-4">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">Hero 文案</h3>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <label class="space-y-1 md:col-span-2">
          <span class="text-xs text-art-muted">副标题 / Eyebrow</span>
          <input v-model="model.hero.eyebrow" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">标题行 1</span>
          <input v-model="model.hero.titleLines[0]" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">标题行 2</span>
          <input v-model="model.hero.titleLines[1]" class="admin-input w-full" />
        </label>
        <label class="space-y-1 md:col-span-2">
          <span class="text-xs text-art-muted">标题行 3</span>
          <input v-model="model.hero.titleLines[2]" class="admin-input w-full" />
        </label>
        <label class="space-y-1 md:col-span-2">
          <span class="text-xs text-art-muted">简介前文</span>
          <input v-model="model.hero.bioBefore" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">高亮名称</span>
          <input v-model="model.hero.bioName" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">强调短语</span>
          <input v-model="model.hero.bioEmphasize" class="admin-input w-full" />
        </label>
        <label class="space-y-1 md:col-span-2">
          <span class="text-xs text-art-muted">简介中间文案</span>
          <input v-model="model.hero.bioMid" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">CTA 文案</span>
          <input v-model="model.hero.ctaLabel" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">CTA 链接</span>
          <input v-model="model.hero.ctaLink" class="admin-input w-full" placeholder="/works" />
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.hero.ctaClickable" type="checkbox" class="accent-art-accent" />
          CTA 可点击跳转
        </label>
      </div>
    </section>

    <!-- Latest work card -->
    <section class="space-y-4 pt-4 border-t border-white/5">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">最新作品卡</h3>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.latestWorkCard.visible" type="checkbox" class="accent-art-accent" />
          展示
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.latestWorkCard.clickable" type="checkbox" class="accent-art-accent" />
          可跳转
        </label>
      </div>
      <label class="space-y-1 block max-w-md">
        <span class="text-xs text-art-muted">卡片标签</span>
        <input v-model="model.latestWorkCard.label" class="admin-input w-full" />
      </label>
      <p class="text-xs text-art-muted">作品标题与链接取自作品列表最新一条</p>
    </section>

    <!-- Bento section -->
    <section class="space-y-4 pt-4 border-t border-white/5">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">Bento 区标题</h3>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <label class="space-y-1">
          <span class="text-xs text-art-muted">区块标题</span>
          <input v-model="model.bento.sectionTitle" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">右侧提示</span>
          <input v-model="model.bento.sectionHint" class="admin-input w-full" />
        </label>
      </div>
    </section>

    <!-- Featured post -->
    <section class="space-y-4 pt-4 border-t border-white/5">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">精选文章卡</h3>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.featuredPost.visible" type="checkbox" class="accent-art-accent" />
          展示
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.featuredPost.clickable" type="checkbox" class="accent-art-accent" />
          可跳转
        </label>
      </div>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.featuredPost.mode" type="radio" value="latest" class="accent-art-accent" />
          最新文章
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.featuredPost.mode" type="radio" value="fixed" class="accent-art-accent" />
          指定文章
        </label>
      </div>

      <div v-if="model.bento.featuredPost.mode === 'fixed'" class="space-y-3 p-4 rounded-lg border border-white/10 bg-white/[0.02]">
        <div class="flex gap-2">
          <input
            v-model="postKeyword"
            class="admin-input flex-1"
            placeholder="搜索文章标题…"
            @keyup.enter="searchPosts"
          />
          <button type="button" class="admin-btn-secondary text-sm shrink-0" :disabled="searchingPosts" @click="searchPosts">
            {{ searchingPosts ? '搜索中…' : '搜索' }}
          </button>
        </div>
        <p v-if="selectedPostTitle" class="text-sm text-art-accent">
          已选：#{{ model.bento.featuredPost.postId }} {{ selectedPostTitle }}
          <button type="button" class="ml-2 text-xs text-art-muted hover:text-white" @click="clearSelectedPost">清除</button>
        </p>
        <ul v-if="postOptions.length" class="max-h-48 overflow-y-auto space-y-1 custom-scrollbar">
          <li v-for="p in postOptions" :key="p.id">
            <button
              type="button"
              class="w-full text-left px-3 py-2 rounded text-sm transition-colors"
              :class="model.bento.featuredPost.postId === p.id
                ? 'bg-art-accent/20 text-art-accent border border-art-accent/40'
                : 'text-white/80 hover:bg-white/5 border border-transparent'"
              @click="selectPost(p)"
            >
              <span class="font-mono text-xs text-art-muted mr-2">#{{ p.id }}</span>
              {{ p.title }}
            </button>
          </li>
        </ul>
      </div>

      <ImagePicker
        v-model="model.bento.featuredPost.backgroundImage"
        label="背景图片"
        hint="留空或清除后前台使用默认 /bg/img.png"
        size="md"
      />
    </section>

    <!-- Stats -->
    <section class="space-y-4 pt-4 border-t border-white/5">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">统计卡</h3>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.stats.visible" type="checkbox" class="accent-art-accent" />
          展示
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.stats.clickable" type="checkbox" class="accent-art-accent" />
          可跳转
        </label>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <label class="space-y-1">
          <span class="text-xs text-art-muted">数值</span>
          <input v-model="model.bento.stats.value" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">跳转链接</span>
          <input v-model="model.bento.stats.link" class="admin-input w-full" placeholder="可选" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">主标签</span>
          <input v-model="model.bento.stats.label" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">副标签</span>
          <input v-model="model.bento.stats.sublabel" class="admin-input w-full" />
        </label>
      </div>
    </section>

    <!-- Snippets -->
    <section class="space-y-4 pt-4 border-t border-white/5">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">代码实验室卡</h3>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.snippets.visible" type="checkbox" class="accent-art-accent" />
          展示
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.snippets.clickable" type="checkbox" class="accent-art-accent" />
          可跳转
        </label>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <label class="space-y-1 md:col-span-2">
          <span class="text-xs text-art-muted">注释行</span>
          <input v-model="model.bento.snippets.comment" class="admin-input w-full font-mono text-sm" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">关键字</span>
          <input v-model="model.bento.snippets.codeLines.keyword" class="admin-input w-full font-mono text-sm" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">函数名</span>
          <input v-model="model.bento.snippets.codeLines.func" class="admin-input w-full font-mono text-sm" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">返回字符串</span>
          <input v-model="model.bento.snippets.codeLines.string" class="admin-input w-full font-mono text-sm" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">CTA 文案</span>
          <input v-model="model.bento.snippets.ctaLabel" class="admin-input w-full" />
        </label>
        <label class="space-y-1 md:col-span-2">
          <span class="text-xs text-art-muted">跳转链接</span>
          <input v-model="model.bento.snippets.link" class="admin-input w-full" />
        </label>
      </div>
    </section>

    <!-- Services -->
    <section class="space-y-4 pt-4 border-t border-white/5">
      <h3 class="text-sm font-medium text-art-accent uppercase tracking-wider">服务 CTA 卡</h3>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.services.visible" type="checkbox" class="accent-art-accent" />
          展示
        </label>
        <label class="flex items-center gap-2 text-sm text-white/80">
          <input v-model="model.bento.services.clickable" type="checkbox" class="accent-art-accent" />
          可跳转
        </label>
      </div>
      <div class="grid grid-cols-1 gap-4">
        <label class="space-y-1">
          <span class="text-xs text-art-muted">标题</span>
          <input v-model="model.bento.services.title" class="admin-input w-full" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">描述</span>
          <textarea v-model="model.bento.services.description" rows="3" class="admin-input w-full resize-none" />
        </label>
        <label class="space-y-1">
          <span class="text-xs text-art-muted">跳转链接</span>
          <input v-model="model.bento.services.link" class="admin-input w-full" />
        </label>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import ImagePicker from './ImagePicker.vue'
import { fetchPost, getAdminPosts, type Post } from '../../services/api'
import type { HomepageConfig } from '../../config/homepageConfig'
import { parseHomepageConfig } from '../../config/homepageConfig'

const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const model = ref<HomepageConfig>(parseHomepageConfig(props.modelValue))
const postKeyword = ref('')
const searchingPosts = ref(false)
const postOptions = ref<Post[]>([])
const selectedPostTitle = ref('')

let syncingFromParent = false

watch(
  () => props.modelValue,
  (val) => {
    syncingFromParent = true
    model.value = parseHomepageConfig(val)
    syncingFromParent = false
    if (model.value.bento.featuredPost.postId) {
      loadSelectedPostTitle(model.value.bento.featuredPost.postId)
    } else {
      selectedPostTitle.value = ''
    }
  }
)

watch(
  model,
  () => {
    if (syncingFromParent) return
    emit('update:modelValue', JSON.stringify(model.value))
  },
  { deep: true }
)

const selectPost = (p: Post) => {
  model.value.bento.featuredPost.postId = Number(p.id)
  selectedPostTitle.value = p.title
}

const clearSelectedPost = () => {
  model.value.bento.featuredPost.postId = null
  selectedPostTitle.value = ''
}

const searchPosts = async () => {
  searchingPosts.value = true
  try {
    const res = await getAdminPosts(1, 20, { keyword: postKeyword.value.trim() || undefined, isPublished: 1 })
    postOptions.value = res.list || []
  } catch {
    postOptions.value = []
  } finally {
    searchingPosts.value = false
  }
}

const loadSelectedPostTitle = async (id: number) => {
  try {
    const post = await fetchPost(id)
    selectedPostTitle.value = post?.title && post.id ? post.title : `文章 #${id}`
  } catch {
    selectedPostTitle.value = `文章 #${id}`
  }
}

onMounted(() => {
  if (model.value.bento.featuredPost.mode === 'fixed') {
    searchPosts()
    if (model.value.bento.featuredPost.postId) {
      loadSelectedPostTitle(model.value.bento.featuredPost.postId)
    }
  }
})

watch(
  () => model.value.bento.featuredPost.mode,
  (mode) => {
    if (mode === 'fixed' && postOptions.value.length === 0) {
      searchPosts()
    }
  }
)
</script>
