import type { Metadata } from "next";
import { HeroSection } from "@/components/landing/HeroSection";
import { StatsSection } from "@/components/landing/StatsSection";
import { FeaturedQuizzes } from "@/components/landing/FeaturedQuizzes";
import { FeaturesSection } from "@/components/landing/FeaturesSection";
import { CTASection } from "@/components/landing/CTASection";
import { prisma } from "@/lib/prisma";

export const metadata: Metadata = {
  title: "QuizB | Kuis Berkah: Asah Pengetahuan, Tantang Temanmu!",
};

export const dynamic = "force-dynamic";

async function getStats() {
  try {
    const [quizCount, userCount, resultCount] = await Promise.all([
      prisma.quiz.count({ where: { isPublished: true } }),
      prisma.user.count(),
      prisma.result.count(),
    ]);
    return { quizCount, userCount, resultCount };
  } catch {
    return { quizCount: 500, userCount: 12000, resultCount: 50000 };
  }
}

async function getFeaturedQuizzes() {
  try {
    return await prisma.quiz.findMany({
      where: { isPublished: true },
      orderBy: { playCount: "desc" },
      take: 6,
      include: {
        author: { select: { name: true, image: true } },
        category: { select: { name: true, icon: true, color: true } },
        _count: { select: { questions: true, results: true } },
      },
    });
  } catch {
    return [];
  }
}

export default async function HomePage() {
  const [stats, featuredQuizzes] = await Promise.all([
    getStats(),
    getFeaturedQuizzes(),
  ]);

  return (
    <>
      <HeroSection />
      <StatsSection stats={stats} />
      <FeaturedQuizzes quizzes={featuredQuizzes} />
      <FeaturesSection />
      <CTASection />
    </>
  );
}
