import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import Script from 'next/script'
import { SITE_URL } from '@/lib/seo'
import BlogPostClient from './BlogPostClient'
import type { BlogPost } from './types'

async function fetchPostMeta(slug: string): Promise<BlogPost | null> {
  try {
    // Build API URL correctly:
    // - BACKEND_URL is just the host (e.g. http://127.0.0.1:8000)
    // - NEXT_PUBLIC_API_URL already includes /api/v1 (e.g. https://pounce.ch/api/v1)
    // - SITE_URL is just the frontend host (e.g. https://pounce.ch)
    let apiUrl: string
    
    if (process.env.BACKEND_URL) {
      apiUrl = `${process.env.BACKEND_URL.replace(/\/$/, '')}/api/v1/blog/posts/${encodeURIComponent(slug)}/meta`
    } else if (process.env.NEXT_PUBLIC_API_URL) {
      apiUrl = `${process.env.NEXT_PUBLIC_API_URL.replace(/\/$/, '')}/blog/posts/${encodeURIComponent(slug)}/meta`
    } else {
      apiUrl = `${SITE_URL.replace(/\/$/, '')}/api/v1/blog/posts/${encodeURIComponent(slug)}/meta`
    }
    
    const res = await fetch(apiUrl, {
      next: { revalidate: 3600 },
    })
    if (res.status === 404) return null
    if (!res.ok) {
      console.error(`[fetchPostMeta] Failed: ${res.status} from ${apiUrl}`)
      return null
    }
    return (await res.json()) as BlogPost
  } catch (error) {
    console.error(`[fetchPostMeta] Error fetching ${slug}:`, error)
    return null
  }
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>
}): Promise<Metadata> {
  const { slug } = await params
  const meta = await fetchPostMeta(slug)

  if (!meta) {
    return {
      title: 'Article not found | Pounce',
      robots: { index: false, follow: false },
    }
  }

  const title = meta.meta_title || meta.title
  const description = meta.meta_description || meta.excerpt || 'Pounce blog article.'

  return {
    title,
    description,
    alternates: { canonical: `${SITE_URL}/blog/${encodeURIComponent(meta.slug)}` },
    openGraph: {
      title,
      description,
      url: `${SITE_URL}/blog/${encodeURIComponent(meta.slug)}`,
      type: 'article',
      images: meta.cover_image ? [{ url: meta.cover_image }] : undefined,
    },
  }
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = await params
  const meta = await fetchPostMeta(slug)
  if (!meta) notFound()

  const publishedAt = meta.published_at || meta.created_at
  const modifiedAt = meta.updated_at || meta.created_at

  const schema = {
    '@context': 'https://schema.org',
    '@graph': [
      {
        '@type': 'BreadcrumbList',
        itemListElement: [
          { '@type': 'ListItem', position: 1, name: 'Home', item: SITE_URL },
          { '@type': 'ListItem', position: 2, name: 'Blog', item: `${SITE_URL}/blog` },
          {
            '@type': 'ListItem',
            position: 3,
            name: meta.title,
            item: `${SITE_URL}/blog/${encodeURIComponent(meta.slug)}`,
          },
        ],
      },
      {
        '@type': 'Article',
        headline: meta.title,
        description: meta.meta_description || meta.excerpt || undefined,
        datePublished: publishedAt,
        dateModified: modifiedAt,
        mainEntityOfPage: {
          '@type': 'WebPage',
          '@id': `${SITE_URL}/blog/${encodeURIComponent(meta.slug)}`,
        },
        author: {
          '@type': 'Person',
          name: meta.author?.name || 'Pounce Team',
        },
        publisher: {
          '@type': 'Organization',
          name: 'Pounce',
          url: SITE_URL,
        },
        image: meta.cover_image ? [meta.cover_image] : undefined,
        keywords: meta.tags?.length ? meta.tags.join(', ') : undefined,
      },
    ],
  }

  return (
    <>
      <Script
        id="blog-article-schema"
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
      />
      <BlogPostClient initialPost={meta} />
    </>
  )
}
