import { getPayload } from 'payload'
import config from '@/payload.config'
import { HeroImgOnly } from '@/components/shared/HeroImgOnly'
import { Media } from '@/payload-types'
import { ReviewsSectionClient } from '@/components/pages/ReviewsPage/ReviewsSectionClient'
import { ContactSectionForm } from '@/globals/ContactForm/Component'
import { getCurrentLocale } from '@/locales/server'

export default async function ReviewsPage({ searchParams }: { searchParams: { limit?: string } }) {
  const payloadConfig = await config
  const payload = await getPayload({ config: payloadConfig })
  const locale = await getCurrentLocale()
  const { hero, reviews: reviewsBlock } = await payload.findGlobal({
    slug: 'reviews-page',
    depth: 1,
    locale,
  })

  // Лимит из searchParams или из блока или дефолт
  const urlLimit = Number(searchParams?.limit)
  const fallbackLimit =
    typeof reviewsBlock === 'object' &&
    'limit' in reviewsBlock &&
    Number((reviewsBlock as any).limit)
      ? Number((reviewsBlock as any).limit)
      : 6

  const reviewsLimit = urlLimit > 0 ? urlLimit : fallbackLimit

  const result = await payload.find({
    collection: 'reviews',
    limit: reviewsLimit,
    pagination: true,
    depth: 2,
  })
  return (
    <>
      {hero?.bg && <HeroImgOnly bg={hero.bg as Media} />}
      <ReviewsSectionClient
        title={reviewsBlock?.title || ''}
        subtitle={reviewsBlock?.subtitle || ''}
        initialDocs={result.docs}
        totalCount={result.totalDocs}
        initialLimit={reviewsLimit}
      />
      <ContactSectionForm />
    </>
  )
}
