import type { Metadata } from 'next'
import ReboursPage from './ReboursPage'
import { getHomePage, getPublishedProducts, mediaUrl } from '@/lib/payload'

export async function generateMetadata(): Promise<Metadata> {
  const home = await getHomePage()
  return {
    title: home?.seoTitle || 'REBOURS — Mobilier d\u2019art contemporain | Collection 001',
    description:
      home?.seoDescription ||
      'REBOURS Studio crée du mobilier d\u2019art contemporain inspiré du Space Age et du mouvement Memphis. Pièces uniques fabriquées à Paris. Collection 001 en cours.',
    alternates: { canonical: '/' },
  }
}

export const dynamic = 'force-dynamic'

export default async function Page() {
  const [products, home] = await Promise.all([getPublishedProducts(), getHomePage()])

  const firstImage =
    mediaUrl(home?.heroImage as never, 'feature') ||
    (products[0]?.images?.[0] ? mediaUrl((products[0].images[0] as { image: unknown }).image as never, 'feature') : null)

  const schemaOrg = {
    '@context': 'https://schema.org',
    '@type': 'Store',
    name: 'REBOURS Studio',
    description: "Mobilier d'art contemporain. Space Age × Memphis. Pièces uniques fabriquées à Paris.",
    url: 'https://rebours.studio/',
    image: firstImage,
    address: { '@type': 'PostalAddress', addressLocality: 'Paris', addressCountry: 'FR' },
    hasOfferCatalog: {
      '@type': 'OfferCatalog',
      name: 'Collection 001',
      itemListElement: products
        .filter((p) => p.price)
        .map((p) => {
          const img = (p.images?.[0] as { image: unknown } | undefined)?.image
          return {
            '@type': 'Offer',
            itemOffered: {
              '@type': 'Product',
              name: p.productDisplayName,
              description: p.seoDescription || p.description?.substring(0, 155),
              image: mediaUrl(img as never, 'feature') ?? undefined,
            },
            price: String((p.price || 0) / 100),
            priceCurrency: p.currency || 'EUR',
            availability: p.availability,
          }
        }),
    },
  }

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaOrg) }} />
      <ReboursPage products={products} home={home} />
    </>
  )
}
