import type { Metadata } from 'next'
import Navbar from '@/components/Navbar'
import Footer from '@/components/Footer'
import HomePage from './home-page'
import prisma from '@/lib/prisma'

export const dynamic = 'force-dynamic'

export const metadata: Metadata = {
  title: 'AmaneNime Store — Top Up Game & Digital Products Terpercaya',
  description: 'Top up game murah, cepat & terpercaya. Mobile Legends, Free Fire, PUBG. Juga Netflix, Spotify, YouTube Premium, ChatGPT Plus dan produk digital lainnya.',
}

export default async function Page() {
  const [totalOrders, totalUsers, totalVipGames, totalDigital, dbCategories, dbDigitalProducts, dbBanners, dbPopup] = await Promise.all([
    prisma.order.count({ where: { status: 'SUCCESS' } }),
    prisma.user.count(),
    prisma.vipProduct.count({ where: { status: true, isActive: true } }),
    prisma.digitalProduct.count({ where: { isActive: true } }),
    prisma.gameCategory.findMany({ where: { isActive: true }, orderBy: { sortOrder: 'asc' } }),
    prisma.digitalProduct.findMany({ where: { isActive: true }, orderBy: { sortOrder: 'asc' } }),
    prisma.setting.findUnique({ where: { key: 'frontend_banners' } }),
    prisma.setting.findUnique({ where: { key: 'frontend_popup' } }),
  ])
  
  const formatStat = (num: number) => {
    if (num === 0) return '0'
    if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M+'
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K+'
    return num.toString() + '+'
  }

  const realStats = {
    orders: formatStat(totalOrders),
    users: formatStat(totalUsers),
    games: formatStat(totalVipGames + totalDigital),
  }

  const banners = dbBanners?.value ? JSON.parse(dbBanners.value) : []
  const popup = dbPopup?.value ? JSON.parse(dbPopup.value) : null

  return (
    <main style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <HomePage 
        realStats={realStats} 
        dbCategories={dbCategories} 
        dbDigitalProducts={dbDigitalProducts}
        banners={banners}
        popup={popup}
      />
      <Footer />
    </main>
  )
}
