import { Metadata } from 'next';
import { setRequestLocale } from 'next-intl/server';
import { notFound } from 'next/navigation';
import { getPayload } from 'payload';
import configPromise from '@payload-config';
import PayloadRichText from '@/components/PayloadRichText';

export async function generateMetadata(props: any): Promise<Metadata> {
  const { locale } = await props.params;
  if (locale !== 'de' && locale !== 'en') return {};
  
  return {
    title: locale === 'de' ? 'Startseite' : 'Home',
  };
}

export default async function Home(props: any) {
  const { locale } = await props.params;
  
  // Guard against invalid locales (e.g. favicon.ico) hitting the DB
  if (locale !== 'de' && locale !== 'en') {
    notFound();
  }
  
  setRequestLocale(locale);

  const payload = await getPayload({ config: configPromise });
  
  // 1. Fetch references for the ReferencesSlider (passed globally to PayloadRichText)
  const { docs: references } = await payload.find({
    collection: 'references',
    locale: locale as any,
    limit: 10,
  });

  const mappedReferences = references.map((ref: any) => ({
    id: ref.id,
    title: ref.title,
    slug: ref.slug,
    category: ref.category,
    image: ref.image,
  }));

  // 2. Fetch the Home page content
  const { docs: pages } = await payload.find({
    collection: 'pages',
    where: {
      slug: {
        equals: 'home',
      },
    },
    locale: locale as any,
    limit: 1,
    draft: true, // Allow finding drafts in development
  });

  const page = pages[0];

  // Fallback to static components if page doesn't exist in CMS yet
  // This prevents the site from breaking before the first seed/save
  if (!page) {
    console.warn(`[Home] Page slug "home" not found in CMS for locale "${locale}".`);
    const { totalDocs: allPages } = await payload.find({ collection: 'pages', locale: 'all' });
    console.log(`[Home] Total pages in CMS (all locales): ${allPages}`);
    return (
      <main className="min-h-screen flex items-center justify-center bg-neutral-dark text-white p-10 text-center">
        <div>
          <h1 className="text-4xl font-bold mb-4">Willkommen bei E-TIB</h1>
          <p className="text-xl text-white/60">Die CMS-Inhalte für diese Seite müssen noch angelegt werden.</p>
        </div>
      </main>
    );
  }

  return (
    <main>
      <PayloadRichText data={page.content} references={mappedReferences} />
    </main>
  );
}

