<template>
  <section id="home" class="page-section block">
    <!-- Hero -->
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-12 mb-24 items-center animate-reveal">
      <div class="lg:col-span-7 space-y-8">
        <p class="text-art-accent font-mono text-sm tracking-widest uppercase mb-4">{{ config.hero.eyebrow }}</p>
        <h1 class="font-serif text-5xl md:text-7xl lg:text-8xl leading-[1.1] text-art-text text-glow">
          <span class="block italic opacity-80">{{ config.hero.titleLines[0] }}</span>
          <span class="block font-bold">{{ config.hero.titleLines[1] }}</span>
          <span class="block font-bold pl-12 md:pl-24">{{ config.hero.titleLines[2] }}</span>
        </h1>
        <p class="text-art-muted text-lg md:text-xl max-w-xl leading-relaxed mt-8 font-light">
          {{ config.hero.bioBefore }}<span class="text-art-text font-bold">{{ config.hero.bioName }}</span>{{ config.hero.bioMid }}<span class="text-art-text border-b border-art-border pb-0.5">{{ config.hero.bioEmphasize }}</span>。
        </p>
        <div v-if="config.hero.ctaLabel" class="pt-8 flex items-center gap-6">
          <button
            type="button"
            class="group flex items-center gap-2 text-art-text border-b border-art-text pb-1 hover:text-art-accent hover:border-art-accent transition-all"
            :class="config.hero.ctaClickable ? 'cursor-pointer' : 'cursor-default'"
            @click="onHeroCta"
          >
            <span>{{ config.hero.ctaLabel }}</span>
            <Icon name="arrow-right" :size="16" class="transform group-hover:translate-x-1 transition-transform" />
          </button>
        </div>
      </div>
      <div class="lg:col-span-5 relative h-[400px] lg:h-[600px] w-full flex items-center justify-center">
        <div class="relative w-full h-full">
          <div class="absolute inset-0 border border-art-border rounded-full rotate-12 scale-90"></div>
          <div class="absolute inset-0 border border-art-border rounded-full -rotate-6 scale-75"></div>
          <div
            v-if="config.latestWorkCard.visible"
            id="home-hero-work"
            class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-80 bg-gradient-to-br from-art-text/5 to-transparent backdrop-blur-md border border-art-border rounded-sm shadow-2xl rotate-6 hover:rotate-0 transition-transform duration-700 z-10 flex flex-col p-6 justify-between"
            :class="config.latestWorkCard.clickable ? 'cursor-pointer' : 'cursor-default'"
            @click="onLatestWorkClick"
          >
            <div class="text-art-muted text-xs">{{ config.latestWorkCard.label }}</div>
            <div class="font-serif text-3xl italic text-art-text">{{ latestWork.title }}</div>
            <div class="flex justify-end"><Icon name="arrow-up-right" :size="24" class="text-art-text" /></div>
          </div>
          <div
            v-else
            class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-80 border border-dashed border-art-border rounded-sm bg-art-text/[0.03] backdrop-blur-md rotate-6 z-10 pointer-events-none flex flex-col items-center justify-center gap-3"
            aria-hidden="true"
          >
            <div class="absolute top-5 left-5 w-8 h-px bg-art-accent/40"></div>
            <div class="absolute top-5 left-5 w-px h-8 bg-art-accent/40"></div>
            <div class="absolute bottom-5 right-5 w-8 h-px bg-art-accent/30"></div>
            <div class="absolute bottom-5 right-5 w-px h-8 bg-art-accent/30"></div>
            <span class="font-mono text-[10px] tracking-[0.35em] uppercase text-art-muted/40">···</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Bento Grid -->
    <div class="space-y-6 animate-reveal" style="animation-delay: 0.2s;">
      <div class="flex items-end justify-between border-b border-art-border pb-4 mb-8">
        <h2 class="font-serif text-3xl italic text-art-text">{{ config.bento.sectionTitle }}</h2>
        <span class="font-mono text-xs text-art-muted">{{ config.bento.sectionHint }}</span>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 auto-rows-[300px]" id="bento-grid">
        <!-- Featured post -->
        <div
          v-if="config.bento.featuredPost.visible"
          class="md:col-span-2 art-card rounded-2xl p-8 flex flex-col justify-end group"
          :class="config.bento.featuredPost.clickable ? 'cursor-pointer' : 'cursor-default'"
          @click="onFeaturedPostClick"
        >
          <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent z-10"></div>
          <div
            class="absolute inset-0 bg-cover bg-center transition-transform duration-700 group-hover:scale-105 opacity-60 mix-blend-overlay"
            :style="{ backgroundImage: `url(${featuredBg})` }"
          ></div>
          <div class="relative z-20 space-y-2">
            <div class="flex items-center gap-3">
              <span class="px-2 py-1 text-[10px] font-mono border border-white/20 rounded-full text-white backdrop-blur-sm">{{ featuredPost.categoryName || '未分类' }}</span>
              <span class="text-xs text-white/60">{{ featuredPost.date }}</span>
            </div>
            <h3 class="font-serif text-3xl text-white group-hover:text-art-accent transition-colors">
              {{ featuredPost.title }}
            </h3>
            <AuthorInfo
              class="mt-3"
              :name="featuredPost.userName"
              :email="featuredPost.userEmail"
              :avatar="featuredPost.userAvatar"
              :user-id="featuredPost.userId"
              variant="compact"
              size="sm"
              theme="onImage"
            />
          </div>
        </div>
        <HomeBentoPlaceholder v-else :span="2" />

        <!-- Stats -->
        <div
          v-if="config.bento.stats.visible"
          class="art-card rounded-2xl p-8 flex flex-col justify-between group"
          :class="config.bento.stats.clickable && config.bento.stats.link ? 'cursor-pointer' : ''"
          @click="onStatsClick"
        >
          <div class="flex justify-between items-start">
            <Icon name="code-2" :size="32" class="text-art-muted group-hover:text-art-accent transition-colors" />
            <Icon name="arrow-up-right" :size="20" class="text-art-muted/60" />
          </div>
          <div>
            <div class="text-4xl font-mono font-bold text-art-text mb-2">{{ config.bento.stats.value }}</div>
            <div class="text-sm text-art-muted">{{ config.bento.stats.label }}</div>
            <div class="text-xs text-art-muted mt-2 opacity-60">{{ config.bento.stats.sublabel }}</div>
          </div>
        </div>
        <HomeBentoPlaceholder v-else :span="1" />

        <!-- Snippets -->
        <div
          v-if="config.bento.snippets.visible"
          class="art-card rounded-2xl p-6 md:p-8 flex flex-col justify-between group bg-art-bg"
          :class="config.bento.snippets.clickable ? 'cursor-pointer' : 'cursor-default'"
          @click="onSnippetsClick"
        >
          <div class="font-mono text-xs text-art-muted mb-4">{{ config.bento.snippets.comment }}</div>
          <div class="font-mono text-sm text-art-muted overflow-hidden opacity-60 group-hover:opacity-100 transition-opacity">
            <span class="code-keyword">{{ config.bento.snippets.codeLines.keyword }}</span>
            <span> </span>
            <span class="code-func">{{ config.bento.snippets.codeLines.func }}</span>
            <span> = () =&gt; {'{'}</span><br>
            &nbsp;&nbsp;<span class="code-keyword">return</span>
            <span> </span>
            <span class="code-string">"{{ config.bento.snippets.codeLines.string }}"</span>;<br>
            }
          </div>
          <div class="mt-4 flex items-center gap-2 text-sm font-medium text-art-text">
            <span>{{ config.bento.snippets.ctaLabel }}</span>
            <Icon name="chevron-right" :size="16" class="text-art-accent" />
          </div>
        </div>
        <HomeBentoPlaceholder v-else :span="1" />

        <!-- Services -->
        <div
          v-if="config.bento.services.visible"
          class="md:col-span-2 art-card rounded-2xl p-8 md:p-12 flex flex-col md:flex-row items-center justify-between gap-8 group bg-gradient-to-r from-art-surface to-transparent"
          :class="config.bento.services.clickable ? 'cursor-pointer' : 'cursor-default'"
          @click="onServicesClick"
        >
          <div class="space-y-4">
            <h3 class="font-serif text-3xl text-art-text">{{ config.bento.services.title }}</h3>
            <p class="text-art-muted max-w-sm">{{ config.bento.services.description }}</p>
          </div>
          <div class="h-16 w-16 rounded-full border border-art-border flex items-center justify-center group-hover:bg-art-text group-hover:text-black transition-all duration-300">
            <Icon name="arrow-right" :size="24" />
          </div>
        </div>
        <HomeBentoPlaceholder v-else :span="2" />
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { fetchWorks, fetchPosts, fetchPost, type Work, type Post } from '../services/api'
import { useScrollAnimation } from '../composables/useScrollAnimation'
import { loadPublicSettings } from '../composables/usePublicSettings'
import { parseHomepageConfig, type HomepageConfig } from '../config/homepageConfig'
import Icon from '../components/Icon.vue'
import AuthorInfo from '../components/AuthorInfo.vue'
import HomeBentoPlaceholder from '../components/HomeBentoPlaceholder.vue'

const router = useRouter()
const { initObserver } = useScrollAnimation()

const config = ref<HomepageConfig>(parseHomepageConfig())

const latestWork = ref<Work>({
  id: 'nova',
  title: 'Nova 交易平台',
  category: '金融科技',
  year: '2023',
  heroImg: '',
  desc: '',
  techStack: [],
  gallery: [],
  links: {},
  next: '',
})

const featuredPost = ref<Post>({
  id: 0,
  title: '当极简主义遇见复杂数据',
  categoryId: 0,
  date: '2025-10-24',
  excerpt: '',
  content: '',
})

const featuredBg = computed(() => {
  const url = config.value.bento.featuredPost.backgroundImage?.trim()
  return url || '/bg/img.png'
})

const navigate = (link: string) => {
  if (!link) return
  if (/^https?:\/\//i.test(link)) {
    window.open(link, '_blank', 'noopener,noreferrer')
    return
  }
  router.push(link)
}

const onHeroCta = () => {
  if (!config.value.hero.ctaClickable) return
  navigate(config.value.hero.ctaLink || '/works')
}

const onLatestWorkClick = () => {
  if (!config.value.latestWorkCard.clickable) return
  router.push(`/works/${latestWork.value.id}`)
}

const onFeaturedPostClick = () => {
  if (!config.value.bento.featuredPost.clickable) return
  if (!featuredPost.value.id) return
  router.push(`/blog/${featuredPost.value.id}`)
}

const onStatsClick = () => {
  if (!config.value.bento.stats.clickable || !config.value.bento.stats.link) return
  navigate(config.value.bento.stats.link)
}

const onSnippetsClick = () => {
  if (!config.value.bento.snippets.clickable) return
  navigate(config.value.bento.snippets.link || '/snippets')
}

const onServicesClick = () => {
  if (!config.value.bento.services.clickable) return
  navigate(config.value.bento.services.link || '/services')
}

const fetchHomeData = async () => {
  try {
    const settings = await loadPublicSettings()
    config.value = parseHomepageConfig(settings.homepage_config)

    const worksPromise = fetchWorks()
    let postPromise: Promise<void>

    const fp = config.value.bento.featuredPost
    if (fp.visible && fp.mode === 'fixed' && fp.postId) {
      postPromise = fetchPost(fp.postId).then((post) => {
        if (post && post.id) featuredPost.value = post
      })
    } else {
      postPromise = fetchPosts(undefined, undefined, undefined, undefined, 1, 1).then((posts) => {
        const postsList = 'list' in posts ? posts.list : []
        if (postsList && postsList.length > 0) {
          featuredPost.value = postsList[0]
        }
      })
    }

    const [works] = await Promise.all([worksPromise, postPromise])
    if (works && works.length > 0) {
      latestWork.value = works[0]
    }
  } catch (err) {
    console.error('Error fetching home data:', err)
  } finally {
    initObserver()
  }
}

onMounted(() => {
  fetchHomeData()
})
</script>
