import { getClient } from "@/lib/apolloClient";
import { gql } from "@apollo/client";
import { Metadata } from "next";
import { notFound } from "next/navigation";

import PageHero from "@/components/PageHero";
export const dynamic = "force-dynamic";
export const PAGE_BY_SLUG_QUERY = gql`
  query PageBySlug($uri: ID!) {
    page(id: $uri, idType: URI) {
      title
      slug
      uri
      content
      seo {
        title
        metaDesc
        canonical
        opengraphTitle
        opengraphDescription
        opengraphImage {
          sourceUrl
        }
      }
    }
  }
`;

type PageBySlugResponse = {
  page: {
    title: string;
    slug: string;
    uri: string;
    content?: string | null;
    seo?: {
      title?: string | null;
      metaDesc?: string | null;
      canonical?: string | null;
      opengraphTitle?: string | null;
      opengraphDescription?: string | null;
      opengraphImage?: {
        sourceUrl?: string | null;
      } | null;
    } | null;
  } | null;
};


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

  const { data } = await getClient().query<PageBySlugResponse>({
    query: PAGE_BY_SLUG_QUERY,
    fetchPolicy: "no-cache",
    variables: { uri: `/${slug}/` },
  });

  const page = data?.page;
  const seo = page?.seo;

  if (!page) {
    return {
      title: "Page | Togwe",
      description: "Information page",
    };
  }

  // ✅ Correct canonical fallback
  const canonical =
    seo?.canonical && seo.canonical.trim() !== ""
      ? seo.canonical
      : page.uri || `/${slug}/`;

  return {
    metadataBase: new URL("https://www.togwe.com"),

    title: seo?.title || page.title,
    description: seo?.metaDesc || undefined,

    alternates: {
      canonical,
    },

    openGraph: {
      title: seo?.opengraphTitle || seo?.title || page.title,
      description:
        seo?.opengraphDescription || seo?.metaDesc || undefined,
      images: seo?.opengraphImage?.sourceUrl
        ? [{ url: seo.opengraphImage.sourceUrl }]
        : [],
    },
  };
}

export default async function UniversalPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {

  const { slug } = await params; // ✅ REQUIRED

  const { data } = await getClient().query<PageBySlugResponse>({
    query: PAGE_BY_SLUG_QUERY,
    variables: { uri: `/${slug}/` },
  });

  const page = data?.page;

  if (!page) {
    notFound(); // 👈 triggers app/not-found.tsx → redirects to "/"
  }

  return (
    <>
      <PageHero title={page.title} />
      <div className="container mx-auto px-4 py-10">
        <article
          className="prose prose-lg max-w-none text-lg text-[#202020] space-y-4"
          dangerouslySetInnerHTML={{ __html: page.content || "" }}
        />
      </div>
    </>
  );
}
