import { notFound } from 'next/navigation';
import { Metadata } from 'next';
import { getLegalPageAsync, getAllLegalSlugs } from '@/lib/legal';
import LegalPageLayout from '@/components/layout/LegalPageLayout';

interface PageProps {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ locale?: string }>;
}

// Generate static params for all legal pages
export async function generateStaticParams() {
  const slugs = getAllLegalSlugs();
  return slugs.map((slug) => ({ slug }));
}

// Enable dynamic rendering to always fetch fresh content from DB
export const dynamic = 'force-dynamic';
export const revalidate = 60; // Revalidate every 60 seconds

const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://spanglish.com.py';

// Validate and normalize locale
function getValidLocale(locale?: string): 'en' | 'es' {
  if (locale === 'es') return 'es';
  return 'en'; // Default to English
}

// Generate metadata for SEO
export async function generateMetadata({ params, searchParams }: PageProps): Promise<Metadata> {
  const resolvedParams = await params;
  const resolvedSearchParams = await searchParams;
  const locale = getValidLocale(resolvedSearchParams.locale);
  const legalPage = await getLegalPageAsync(resolvedParams.slug, locale);
  
  if (!legalPage) {
    return {
      title: 'Not Found',
    };
  }
  
  return {
    // The root layout's title template appends " – Spanglish"; do not repeat it here.
    title: legalPage.title,
    description: `${legalPage.title} for Spanglish language exchange events in Asunción, Paraguay.`,
    robots: {
      index: true,
      follow: true,
    },
    alternates: {
      canonical: `${siteUrl}/legal/${resolvedParams.slug}`,
      languages: {
        'en': `${siteUrl}/legal/${resolvedParams.slug}`,
        'es': `${siteUrl}/legal/${resolvedParams.slug}?locale=es`,
      },
    },
  };
}

export default async function LegalPage({ params, searchParams }: PageProps) {
  const resolvedParams = await params;
  const resolvedSearchParams = await searchParams;
  const locale = getValidLocale(resolvedSearchParams.locale);
  const legalPage = await getLegalPageAsync(resolvedParams.slug, locale);
  
  if (!legalPage) {
    notFound();
  }
  
  return (
    <LegalPageLayout
      slug={resolvedParams.slug}
      initialLocale={locale}
      title={legalPage.title}
      content={legalPage.content}
      lastUpdated={legalPage.lastUpdated}
    />
  );
}
