import { Metadata } from 'next'
import { CartProvider } from '@/lib/cart'
import { PUBLIC_APP_URL } from '@/lib/api/config'

const APP_URL = PUBLIC_APP_URL

export async function generateMetadata({ params }: { params: Promise<{ businessSlug: string }> }): Promise<Metadata> {
  const { businessSlug } = await params
  // Unpublished storefronts must stay out of search indexes; only follow links
  // so owners retain control over their content once it goes live.
  const noIndex = { index: false, follow: true }
  try {
    const res = await fetch(`${APP_URL}/api/shop/business/${businessSlug}`, { cache: 'no-store' })
    if (res.ok) {
      const body = await res.json()
      if (body?.success && body?.data?.name) {
        const d = body.data
        const name: string = d.name
        const desc: string | null = d.description || null
        const title = d.hero_title ? `${name} | ${d.hero_title}` : `${name}`
        const description = desc && desc.trim().length > 10 ? desc.trim().slice(0, 160) : `${name} — browse products, categories and contact information.`
        const canonical = `${APP_URL}/shop/${businessSlug}`
        const published: boolean = d.store_published === true
        return {
          title,
          description,
          alternates: { canonical },
          robots: published ? undefined : noIndex,
          openGraph: {
            type: 'website',
            url: canonical,
            siteName: name,
            title,
            description,
            ...(d.logo_url ? { images: [{ url: d.logo_url, alt: name }] } : {}),
          },
          twitter: {
            card: d.logo_url ? 'summary_large_image' : 'summary',
            title,
            description,
            ...(d.logo_url ? { images: [d.logo_url] } : {}),
          },
        }
      }
    }
  } catch {}
  // Fallback: humanize slug instead of generic "Storefront"
  const fallback = businessSlug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
  return {
    title: fallback,
    description: `Browse products from ${fallback}.`,
    alternates: { canonical: `${APP_URL}/shop/${businessSlug}` },
    robots: noIndex,
  }
}

export default async function ShopLayout({
  children,
  params,
}: {
  children: React.ReactNode
  params: Promise<{ businessSlug: string }>
}) {
  const { businessSlug } = await params
  return (
    <CartProvider>
      <div className="min-h-screen bg-gray-50 dark:bg-gray-950">
        <main className="w-full">
          {children}
        </main>
      </div>
    </CartProvider>
  )
}