import { notFound } from "next/navigation";
import { getPageAction } from "../../lib/actions/pageAction";

export const dynamic = "force-dynamic";

interface CMSDynamicPageProps {
  params: Promise<{
    slug: string;
  }>;
}

export default async function CMSDynamicPage({ params }: CMSDynamicPageProps) {
  const resolvedParams = await params;
  const { slug } = resolvedParams;

  // 1. Fetch page data using the X-Domain logic inside the action
  const response = await getPageAction(slug);

  // 2. Not found if API fails or page doesn't exist
  if (!response?.status || !response?.data) {
    return notFound();
  }

  const pageData = response.data;

  // 3. Handle specific templates
  if (pageData.template?.slug === "iframe-template" || pageData.slug === "iframe") {
    const iframeUrl = pageData.content?.iframe?.iframeurl;

    if (!iframeUrl) {
      return (
        <div className="flex h-[50vh] items-center justify-center">
          <p className="text-xl text-gray-500">Iframe content not found</p>
        </div>
      );
    }

    return (
      <main className="w-full flex-grow relative">
        <iframe
          src={iframeUrl}
          title={pageData.title || "Embedded Content"}
          className="w-full min-h-[calc(100vh-80px)] border-none bg-white" 
          allowFullScreen
          loading="lazy"
          sandbox="allow-scripts allow-same-origin allow-popups allow-forms"
        />
      </main>
    );
  }

  // 4. Fallback for other template types if needed in the future
  return (
    <main className="container mx-auto px-4 py-8 min-h-[100dvh]">
      <h1 className="text-4xl font-bold mb-6">{pageData.title}</h1>
      <div className="bg-gray-50 p-6 rounded-lg shadow-sm">
        <pre className="text-sm overflow-auto">
          {JSON.stringify(pageData.content, null, 2)}
        </pre>
      </div>
    </main>
  );
}
