import { HomePageClient } from '@/components/HomePageClient'
import { BlogPost } from '@/types/blog'

async function getBlogPosts(category?: string): Promise<BlogPost[]> {
  const baseUrl = process.env.API_BASE_URL || process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:4005'

  try {
    let url = `${baseUrl}/posts`
    if (category) {
      url += `?category=${encodeURIComponent(category)}`
    }

    const response = await fetch(url, {
      cache: 'no-store',
      next: { revalidate: 0 }
    })

    if (!response.ok) {
      console.error(`[frontend] Failed to load posts: ${response.status}`)
      return []
    }

    const payload = await response.json()
    return Array.isArray(payload.data) ? payload.data : []
  } catch (error) {
    console.error('[frontend] Failed to load posts', error)
    return []
  }
}

export default async function HomePage({ searchParams }: { searchParams: { category?: string } }) {
  const posts = await getBlogPosts(searchParams.category)
  return <HomePageClient posts={posts} selectedCategory={searchParams.category} />
}
