import type { Metadata } from 'next'
import Script from 'next/script'
import { SITE_URL } from '@/lib/seo'

type TldCompareResponse = {
  tld: string
  type?: string
  description?: string
  registry?: string
  introduced?: number | null
  registrars: Array<{
    name: string
    registration_price: number
    renewal_price: number
    transfer_price?: number | null
    source?: string
  }>
  cheapest_registrar: string
  cheapest_price: number
  price_range: { min: number; max: number; avg: number }
  registrar_count: number
}

async function fetchTldCompare(tld: string): Promise<TldCompareResponse | null> {
  try {
    // Build API URL correctly
    let apiUrl: string
    if (process.env.BACKEND_URL) {
      apiUrl = `${process.env.BACKEND_URL.replace(/\/$/, '')}/api/v1/tld-prices/${encodeURIComponent(tld)}/compare`
    } else if (process.env.NEXT_PUBLIC_API_URL) {
      apiUrl = `${process.env.NEXT_PUBLIC_API_URL.replace(/\/$/, '')}/tld-prices/${encodeURIComponent(tld)}/compare`
    } else {
      apiUrl = `${SITE_URL.replace(/\/$/, '')}/api/v1/tld-prices/${encodeURIComponent(tld)}/compare`
    }
    
    const res = await fetch(apiUrl, {
      next: { revalidate: 3600 },
    })
    if (res.status === 404) return null
    if (!res.ok) {
      console.error(`[fetchTldCompare] Failed: ${res.status} from ${apiUrl}`)
      return null
    }
    return (await res.json()) as TldCompareResponse
  } catch (error) {
    console.error(`[fetchTldCompare] Error fetching ${tld}:`, error)
    return null
  }
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ tld: string }>
}): Promise<Metadata> {
  const { tld } = await params
  const tldLower = String(tld).toLowerCase().replace(/^\./, '')
  const tldUpper = tldLower.toUpperCase()

  const compare = await fetchTldCompare(tldLower)
  if (!compare) {
    return {
      title: `.${tldUpper} — Not found | Pounce`,
      robots: { index: false, follow: false },
    }
  }

  const title = `.${tldUpper} Domain Pricing & Renewal Costs — Compare Registrars | Pounce`
  const description = `Compare real registrar pricing for .${tldUpper} domains. Cheapest registration: $${compare.cheapest_price.toFixed(
    2
  )} at ${compare.cheapest_registrar}. Track renewals and avoid renewal traps.`

  return {
    title,
    description,
    alternates: { canonical: `${SITE_URL}/discover/${tldLower}` },
    openGraph: {
      title,
      description,
      url: `${SITE_URL}/discover/${tldLower}`,
      type: 'article',
    },
  }
}

export default async function DiscoverTldLayout({
  children,
  params,
}: {
  children: React.ReactNode
  params: Promise<{ tld: string }>
}) {
  const { tld } = await params
  const tldLower = String(tld).toLowerCase().replace(/^\./, '')
  const tldUpper = tldLower.toUpperCase()

  const compare = await fetchTldCompare(tldLower)
  const registrars = compare?.registrars || []
  const low = compare?.price_range?.min
  const high = compare?.price_range?.max

  const schema = compare
    ? {
        '@context': 'https://schema.org',
        '@graph': [
          {
            '@type': 'BreadcrumbList',
            itemListElement: [
              { '@type': 'ListItem', position: 1, name: 'Home', item: SITE_URL },
              { '@type': 'ListItem', position: 2, name: 'Discover', item: `${SITE_URL}/discover` },
              { '@type': 'ListItem', position: 3, name: `.${tldUpper}`, item: `${SITE_URL}/discover/${tldLower}` },
            ],
          },
          {
            '@type': 'Product',
            name: `.${tldUpper} Domain Extension`,
            description: compare.description || `Registrar comparison and pricing for .${tldUpper} domains.`,
            category: compare.type || 'Domain Extension',
            url: `${SITE_URL}/discover/${tldLower}`,
            offers: {
              '@type': 'AggregateOffer',
              priceCurrency: 'USD',
              ...(typeof low === 'number' ? { lowPrice: low } : {}),
              ...(typeof high === 'number' ? { highPrice: high } : {}),
              offerCount: registrars.length,
              offers: registrars.slice(0, 8).map(r => ({
                '@type': 'Offer',
                price: r.registration_price,
                priceCurrency: 'USD',
                seller: { '@type': 'Organization', name: r.name },
                availability: 'https://schema.org/InStock',
                url: `${SITE_URL}/discover/${tldLower}`,
              })),
            },
          },
        ],
      }
    : null

  return (
    <>
      {schema ? (
        <Script
          id="discover-tld-schema"
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
        />
      ) : null}
      {children}
    </>
  )
}

