import { getFeaturedBlogs, getFeaturedYouTubeVideos } from "../../../../lib/directQueries/allqueries";
import HeroSection from "../../../components/HeroSection";
import TextDisplay from "../../../components/clientcomponents/TextDisplay";
import LatestArticles from "../../../components/organisms/LatestArticles";
import YouTubeVideos from "../../../components/YouTubeVideos";
import FAQSchema from "../../../components/FAQSchema";
import WebPageSchema from "../../../components/WebPageSchema";

// ✅ Inline API call for silo route detail by slug
async function getSiloRouteDetail(slug) {
  const response = await fetch(
    `${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/silo-route-detail/${slug}`
  );

  if (!response.ok) return null;

  const data = await response.json();
  return data?.data || null;
}

// ✅ Dynamic metadata based on slug
export async function generateMetadata({ params }) {
  const { slug } = await params;
  const page = await getSiloRouteDetail(slug);

  return {
    title: page?.meta_title || "Trusted Study Abroad Consultants in Pakistan",
    description: page?.meta_description || "Looking for trusted study abroad consultants in Pakistan? Expert guidance on universities, scholarships, visas, and applications.",
    openGraph: {
      title: page?.meta_title || "Trusted Study Abroad Consultants in Pakistan",
      description: page?.meta_description || "Looking for trusted study abroad consultants in Pakistan?",
      url: `${process.env.NEXT_PUBLIC_APP_URL}/universities-abroad/${slug}`,
      siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
      type: "website",
    },
    twitter: {
      card: "summary_large_image",
      title: page?.meta_title || "Trusted Study Abroad Consultants in Pakistan",
      description: page?.meta_description || "Looking for trusted study abroad consultants in Pakistan?",
    },
    alternates: {
      canonical: `${process.env.NEXT_PUBLIC_APP_URL}/universities-abroad/${slug}`,
    },
    robots: {
      index: true,
      follow: true,
      nocache: false,
      googleBot: {
        index: true,
        follow: true,
        noimageindex: false,
        "max-video-preview": -1,
        "max-image-preview": "large",
        "max-snippet": -1,
      },
    },
  };
}

async function fetchData(slug) {
  const [featuredBlog, featuredVideos, pageData] = await Promise.all([
    getFeaturedBlogs(),
    getFeaturedYouTubeVideos(),
    getSiloRouteDetail(slug),
  ]);

  return {
    featuredBlog,
    featuredVideos: featuredVideos?.data || [],
    pageData,
  };
}

export default async function TestPreparationSlugPage({ params }) {
  const { slug } = await params;

  try {
    const { featuredBlog, featuredVideos, pageData } = await fetchData(slug);

    let faqs = [];
    try {
      const raw = pageData?.faqs;
      faqs = raw ? JSON.parse(raw) : [];
    } catch {
      faqs = [];
    }

    return (
      <>
        <WebPageSchema
          pageSlug={slug}
          pageData={pageData}
          breadcrumbs={[
            { name: "Home", href: "/" },
            { name: "University Abroad", href: "/universities-abroad" },
            { name: `${pageData?.simple_title} ${pageData?.color_title}`, href: `/universities-abroad/${slug}` },
          ]}
        />
        {faqs && faqs.length > 0 && <FAQSchema faqs={faqs} />}
        <HeroSection
          toptitle=""
          simple_title={pageData?.simple_title}
          color_title={pageData?.color_title}
          description={pageData?.short_description}
        />

        <div className="py-12 md:py-16 lg:py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
              <div className="p-6 md:p-8 lg:p-12">
                <TextDisplay
                  content={pageData?.top_content}
                  className="prose prose-lg max-w-none sn-content"
                />
              </div>
            </div>
          </div>
        </div>

        <div className="py-12 md:py-16 lg:py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
              <div className="p-6 md:p-8 lg:p-12">
                <TextDisplay
                  content={pageData?.middle_content}
                  className="prose prose-lg max-w-none sn-content"
                />
              </div>
            </div>
          </div>
        </div>

        <YouTubeVideos videoData={featuredVideos} />

        <div className="py-12 md:py-16 lg:py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
              <div className="p-6 md:p-8 lg:p-12">
                <TextDisplay
                  content={pageData?.bottom_content}
                  className="prose prose-lg max-w-none sn-content"
                />
              </div>
            </div>
          </div>
        </div>

        <LatestArticles data={featuredBlog} />
      </>
    );

  } catch (error) {
    console.error("Error in TestPreparationSlugPage:", error);
  }
}