<script lang='ts' setup>
import type { Treaty } from "@elysiajs/eden";
import type { InfiniteScrollCustomEvent } from "@ionic/vue";
import type { Action } from "./";
import type { TreatyQuery } from "@/api/types";
import { chevronForwardOutline, eyeOutline, megaphoneOutline, timeOutline } from "ionicons/icons";
import { client, safeClient } from "@/api";
import banner2 from "@/assets/images/home-banner2.jpg?url";
import banner1 from "@/assets/images/home-banner.jpg?url";
import { actions } from "./";

type NewsItem = Treaty.Data<typeof client.api.news.get>["data"][number];
type NewsQuery = TreatyQuery<typeof client.api.news.get>;

const router = useRouter();
const [query] = useResetRef<NewsQuery>({
  offset: 0,
  limit: 10,
});
const data = ref<NewsItem[]>([]);
const isFinished = ref(false);

const banners = ref([
  { id: 1, image: banner1, title: "横幅1" },
  { id: 2, image: banner2, title: "横幅2" },
]);
const currentBannerIndex = ref(0);

// 公告数据
interface Announcement {
  id: number;
  title: string;
  onClick?: () => void;
}

const announcements = ref<Announcement[]>([
  {
    id: 1,
    title: "欢迎使用我们的服务平台，祝您投资顺利！",
    onClick: () => {
      console.log("点击了第一条公告");
    },
  },
]);

// 横幅自动切换
let bannerTimer: ReturnType<typeof setInterval> | null = null;
function startBannerCarousel() {
  bannerTimer = setInterval(() => {
    currentBannerIndex.value = (currentBannerIndex.value + 1) % banners.value.length;
  }, 3000);
}

function stopBannerCarousel() {
  if (bannerTimer) {
    clearInterval(bannerTimer);
    bannerTimer = null;
  }
}

onMounted(() => {
  startBannerCarousel();
});

onUnmounted(() => {
  stopBannerCarousel();
});

async function fetchNews() {
  const { data: responseData } = await safeClient(client.api.news.get({ query: { ...query.value } }));
  data.value.push(...(responseData.value?.data || []));
  isFinished.value = responseData.value?.pagination.hasNextPage === false;
}

async function handleInfinite(event: InfiniteScrollCustomEvent) {
  if (isFinished.value) {
    event.target.complete();
    event.target.disabled = true;
    return;
  }
  query.value.offset! += query.value.limit!;
  await fetchNews();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}

function handleQuickAction(action: Action) {
  switch (action.id) {
    case "check_in":
      router.push("/check_in");
      break;
    case "team":
      router.push("/team");
      break;
    case "invite":
      router.push("/invite");
      break;
    case "support":
      window.open("https://chat.riwsan.com", "_blank");
      break;
  }
}

function handleNewsClick(news: NewsItem) {
  console.log("查看新闻:", news.title);
}

onMounted(() => {
  fetchNews();
});
</script>

<template>
  <ion-page>
    <ion-header class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <img slot="start" src="@/assets/images/icon-1.png" class="h-8 w-8 ml-2" alt="Logo">
        <ion-title>国务院深化改革战略推进委员会</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content :fullscreen="true" class="home-page">
      <div class="ion-padding-horizontal">
        <!-- 横幅轮播 -->
        <div class="rounded-2xl overflow-hidden relative mt-4 shadow-md">
          <div class="relative h-50 w-full">
            <transition-group name="banner-fade">
              <img
                v-for="(banner, index) in banners"
                v-show="index === currentBannerIndex"
                :key="banner.id"
                :src="banner.image"
                class="absolute inset-0 h-full w-full object-cover"
                :alt="banner.title"
              >
            </transition-group>
          </div>
          <!-- 指示点 -->
          <div class="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2 z-10">
            <div
              v-for="(banner, index) in banners"
              :key="banner.id"
              class="w-2 h-2 rounded-full transition-all duration-300 cursor-pointer"
              :class="index === currentBannerIndex ? 'bg-white w-4' : 'bg-white/50'"
              @click="currentBannerIndex = index"
            />
          </div>
        </div>

        <!-- 公告栏 -->
        <div
          v-for="announcement in announcements"
          :key="announcement.id"
          class="mt-3 bg-linear-to-r from-[#fff7e6] to-[#fffbe6] rounded-xl px-4 py-2.5 flex items-center gap-2 overflow-hidden"
        >
          <ion-icon :icon="megaphoneOutline" class="text-lg text-[#fa8c16] shrink-0" />
          <div class="flex-1 overflow-hidden">
            <div class="announcement-scroll">
              <div

                class="announcement-item text-sm text-[#d48806] cursor-pointer hover:text-[#fa8c16] transition-colors"
                @click="announcement.onClick?.()"
              >
                {{ announcement.title }}
              </div>
            </div>
          </div>
        </div>

        <section class="my-5 grid grid-cols-4 gap-4">
          <div
            v-for="action in actions"
            :key="action.id"
            class="flex flex-col items-center gap-2 cursor-pointer transition-transform active:scale-95"
            @click="handleQuickAction(action)"
          >
            <div
              class="w-12 h-12 rounded-xl flex-center shadow-lg"
              :style="{ background: action.color }"
            >
              <ion-icon :icon="action.icon" class="text-xl text-white" />
            </div>
            <span class="text-xs text-[#333] font-medium text-center">{{ action.name }}</span>
          </div>
        </section>

        <!-- 新闻列表区域 -->
        <section class="mt-10 mb-5">
          <div class="flex justify-between items-center mb-4">
            <div class="flex items-center gap-2">
              <img src="@/assets/images/icon.png" class="size-7">
              <div class="text-xl font-bold text-[#1a1a1a]">
                新闻动态
              </div>
            </div>
            <ion-button fill="clear" size="small" class="text-sm h-8" @click="router.push('/layout/service')">
              更多
              <ion-icon slot="end" :icon="chevronForwardOutline" />
            </ion-button>
          </div>
          <empty v-if="data.length === 0" class="my-10" />
          <div v-else class="flex flex-col gap-4">
            <div
              v-for="item in data"
              :key="item.id"
              class="bg-white rounded-2xl overflow-hidden card cursor-pointer transition-all active:translate-y-0.5 active:shadow-sm flex"
              @click="handleNewsClick(item)"
            >
              <div class="relative w-28 h-28 shrink-0 overflow-hidden">
                <img v-if="item.thumbnailId" :src="item.thumbnailId" :alt="item.title" class="w-full h-full object-cover">
                <div class="news-badge absolute top-2 left-2 bg-linear-to-br from-[#c41e3a] to-[#8b1a2e] text-white px-2 py-0.5 rounded-lg text-xs font-semibold shadow-lg">
                  热点
                </div>
              </div>
              <div class="flex-1 p-4 flex flex-col justify-between">
                <div>
                  <div class="text-base font-bold text-[#1a1a1a] mb-1 leading-snug line-clamp-2">
                    {{ item.title }}
                  </div>
                  <p class="text-sm text-[#666] leading-relaxed line-clamp-2">
                    {{ item.summary }}
                  </p>
                </div>
                <div class="flex items-center gap-4 text-xs text-[#999] mt-2">
                  <span class="flex items-center gap-1">
                    <ion-icon :icon="timeOutline" class="text-sm" />
                    {{ useDateFormat(item.createdAt, 'YYYY-MM-DD') }}
                  </span>
                  <span class="flex items-center gap-1">
                    <ion-icon :icon="eyeOutline" class="text-sm" />
                    {{ item.viewCount }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>

      <ion-infinite-scroll threshold="100px" disabled @ion-infinite="handleInfinite">
        <ion-infinite-scroll-content loading-spinner="bubbles" loading-text="加载更多..." />
      </ion-infinite-scroll>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
.card {
  box-shadow: 0 0 7px 4px rgba(0, 0, 0, 0.05);
}
/* 新闻标签渐变 */
.news-badge {
  box-shadow: 0 2px 8px rgba(196, 30, 58, 0.3);
}

/* 横幅轮播动画 */
.banner-fade-enter-active,
.banner-fade-leave-active {
  transition: opacity 0.8s ease;
}

.banner-fade-enter-from {
  opacity: 0;
}

.banner-fade-leave-to {
  opacity: 0;
}

.banner-fade-enter-to,
.banner-fade-leave-from {
  opacity: 1;
}

/* 公告滚动动画 */
.announcement-scroll {
  display: flex;
  animation: scroll-announcement 5s linear infinite;
  white-space: nowrap;
}

.announcement-item {
  padding-right: 100px;
  display: inline-block;
}

@keyframes scroll-announcement {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-33.333%);
  }
}

.announcement-scroll:hover {
  animation-play-state: paused;
}
</style>
