<template>
  <section class="sites" aria-label="站点导航" :aria-busy="loading">
    <div v-if="loading" class="site-grid site-grid--loading" aria-label="正在加载站点">
      <span v-for="index in 6" :key="index" class="site-skeleton"></span>
    </div>
    <div v-else-if="sites.length" ref="swiperElement" class="swiper sites-swiper">
      <div class="swiper-wrapper">
        <div v-for="(siteChunk, index) in chunkedSites" :key="index" class="swiper-slide">
          <div class="site-grid">
            <a
              v-for="site in siteChunk"
              :key="site.id || site.url"
              :href="site.url"
              :target="config.openLinksInNewTab ? '_blank' : undefined"
              :rel="config.openLinksInNewTab ? 'noopener noreferrer' : undefined"
              class="site-box"
            >
              <AppIcon :icon="site.icon" aria-hidden="true" />
              <span>{{ site.name }}</span>
            </a>
          </div>
        </div>
      </div>
      <div ref="paginationElement" class="swiper-pagination"></div>
    </div>
    <div v-else class="site-empty"><i class="fas fa-link" aria-hidden="true"></i><span>暂无站点</span></div>
  </section>
</template>

<script setup>
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import Swiper from 'swiper/bundle'
import 'swiper/swiper-bundle.css'
import { getSites } from '../api'
import fallbackSites from '../config/site.json'
import { loadPublicConfig, publicConfig as config } from '../composables/usePublicConfig'
import AppIcon from './AppIcon.vue'

const sites = ref([])
const loading = ref(true)
const swiperElement = ref(null)
const paginationElement = ref(null)
const chunkedSites = computed(() => sites.value.reduce((chunks, site, index) => {
  const chunkIndex = Math.floor(index / (Number(config.sitePageSize) || 6))
  if (!chunks[chunkIndex]) chunks[chunkIndex] = []
  chunks[chunkIndex].push(site)
  return chunks
}, []))
let swiperInstance = null
let configChannel = null

const initializeSwiper = async () => {
  await nextTick()
  swiperInstance?.destroy(true, true)
  if (!swiperElement.value || chunkedSites.value.length < 1) return
  swiperInstance = new Swiper(swiperElement.value, {
    slidesPerView: 1,
    spaceBetween: 18,
    pagination: { el: paginationElement.value, clickable: true },
    mousewheel: { forceToAxis: true },
    keyboard: { enabled: true },
  })
}

const loadSites = async () => {
  loading.value = true
  try {
    const [{ data }] = await Promise.all([getSites(), loadPublicConfig()])
    sites.value = Array.isArray(data) ? data : []
  } catch {
    sites.value = fallbackSites
  } finally {
    loading.value = false
    initializeSwiper()
  }
}

onMounted(async () => {
  await loadSites()
  if (window.BroadcastChannel) {
    configChannel = new BroadcastChannel('config-update')
    configChannel.onmessage = ({ data }) => {
      if (data?.type === 'config-updated') loadSites()
    }
  }
})

onUnmounted(() => {
  swiperInstance?.destroy(true, true)
  configChannel?.close()
})
</script>

<style scoped lang="less">
.sites { width: min(100%, 700px); min-height: 185px; margin: 30px 0 20px; }
.sites-swiper { overflow: hidden; padding: 10px; }
.site-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 15px; }
.site-box,
.site-skeleton {
  min-width: 0;
  min-height: 72px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: rgba(var(--background-color-rgb), 0.2);
}
.site-box { display: flex; align-items: center; justify-content: center; gap: 9px; padding: 30px; font-weight: 600; backdrop-filter: blur(10px); transition: all 0.3s ease; }
.site-box:hover { transform: translateY(-3px); box-shadow: 0 1px 8px var(--shadow-color); }
.site-box :deep(.app-icon) { flex: 0 0 auto; font-size: var(--icon-size); }
.site-box span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.site-grid--loading { padding: 10px; }
.site-empty { min-height: 150px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; color: var(--text-muted); font-size: 13px; }
.site-empty i { color: var(--hover-link-color); font-size: 22px; }
.site-skeleton { animation: pulse 1.2s ease-in-out infinite alternate; }
@keyframes pulse { to { opacity: 0.45; } }
:deep(.swiper-pagination-bullet) { background: var(--text-muted); transition: width 0.3s ease; }
:deep(.swiper-pagination-bullet-active) { width: 20px; border-radius: 5px; background: #8c8c8c94; }

@media (max-width: 600px) {
  .sites { min-height: 160px; }
  .site-grid { gap: 15px; }
  .site-box,
  .site-skeleton { min-height: 60px; }
  .site-box { flex-direction: column; gap: 5px; padding: 15px 6px; border-radius: 8px; font-size: 14px; }
}
</style>
