import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getCustomPageBySlug } from '@/lib/custom-pages';
import { getHomepageContent } from '@/lib/homepage-content';
import { PageRenderer } from '@/components/renderers/PageRenderer';

const DOMAIN = process.env.NEXT_PUBLIC_SITE_URL || 'ten-sura-game.com';

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const page = await getCustomPageBySlug(slug);
  
  if (!page) {
    return {};
  }
  
  const isIndexable = page.indexable !== false;
  const canonicalUrl = page.canonicalUrl || `https://${DOMAIN}/${slug}`;
  const pageTitle = page.metaTitle || page.title || '';
  const pageDesc = page.metaDescription || '';
  const ogImageUrl = `https://${DOMAIN}/api/og?title=${encodeURIComponent(pageTitle)}`;

  return {
    title: pageTitle,
    description: pageDesc,
    alternates: { canonical: canonicalUrl },
    robots: {
      index: isIndexable,
      follow: isIndexable,
      googleBot: { index: isIndexable, follow: isIndexable },
    },
    openGraph: {
      title: pageTitle,
      description: pageDesc,
      url: canonicalUrl,
      siteName: 'ten-sura-game.com',
      type: 'website',
      locale: 'ja_JP',
      images: [{ url: ogImageUrl, width: 1200, height: 630 }],
    },
    twitter: {
      card: 'summary_large_image',
      title: pageTitle,
      description: pageDesc,
      images: [ogImageUrl],
    },
  };
}

export const dynamic = 'force-dynamic';
export const revalidate = 0;

export default async function CustomPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const page = await getCustomPageBySlug(slug);
  
  if (!page) {
    notFound();
  }
  
  const { puckData } = await getHomepageContent(`/${slug}`);
  const canonicalUrl = page.canonicalUrl || `https://${DOMAIN}/${slug}`;
  const pageTitle = page.metaTitle || page.title || '';
  
  return (
    <main className="bg-deep-black min-h-screen">
      {/* Auto WebPage JSON-LD */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'WebPage',
            name: pageTitle,
            description: page.metaDescription || undefined,
            url: canonicalUrl,
            inLanguage: 'ja',
            isPartOf: { '@type': 'WebSite', name: 'ten-sura-game.com', url: `https://${DOMAIN}` },
          })
        }}
      />
      {/* Manual Schema JSON if provided */}
      {page.schemaJson && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: typeof page.schemaJson === 'string'
              ? page.schemaJson
              : JSON.stringify(page.schemaJson)
          }}
        />
      )}

      {!puckData || !puckData.content || puckData.content.length === 0 ? (
        <div className="container mx-auto py-20 text-center">
          <h1 className="text-2xl text-white font-bold mb-4">{pageTitle}</h1>
          <p className="text-gray-400">このページにはまだコンテンツがありません。管理画面からコンテンツを追加してください。</p>
        </div>
      ) : (
        <PageRenderer dataToRender={puckData.content} fullPuckData={puckData} />
      )}
    </main>
  );
}
