import type { Metadata } from "next";
import prisma from "@/lib/prisma";
import { cache } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { withAvatarUrls } from "@/lib/media";
import StickySearchBar from "@/components/shared/sticky-search-bar";
import QuickFilters from "@/components/shared/quick-filters";
import Breadcrumbs from "@/components/shared/breadcrumbs";
import InfiniteEscortGrid from "@/components/shared/infinite-escort-grid";

export const revalidate = 600;

// React.cache() dedups the country lookup between generateMetadata and the
// page body. Earlier metadata ran 3 sequential queries (country findFirst,
// user count, city findMany) and the page body re-queried country.
const getCountry = cache(async (slug: string) =>
  prisma.country.findFirst({
    where: { slug, active: true },
    include: { cities: { orderBy: { name: "asc" } } },
  })
);

interface Props {
  params: Promise<{ countrySlug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { countrySlug } = await params;
  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";
  const country = await getCountry(countrySlug);
  if (!country) return { title: "Escorts" };
  // Parallel — earlier these were sequential awaits.
  const [totalCount] = await Promise.all([
    prisma.user.count({
      where: { user_type: "escort", country_id: country.id },
    }),
  ]);
  const cityNames = country.cities.slice(0, 8).map((c) => c.name).join(", ");
  const description = `Browse ${totalCount.toLocaleString()} verified escorts in ${country.name}. Top cities: ${cityNames}. Find independent escorts with photos, rates, and reviews.`;
  const countryUrl = `${baseUrl}/escorts/${country.slug}`;
  return {
    title: `Escorts in ${country.name} | AdultWorld`,
    description,
    alternates: {
      canonical: countryUrl,
      languages: {
        en: countryUrl,
        es: countryUrl,
        de: countryUrl,
        fr: countryUrl,
        "x-default": countryUrl,
      },
    },
    openGraph: {
      title: `Escorts in ${country.name} | AdultWorld`,
      description,
    },
    twitter: {
      card: "summary_large_image",
      title: `Escorts in ${country.name} | AdultWorld`,
      description,
    },
  };
}

export default async function EscortsByCountryPage({
  params,
}: {
  params: Promise<{ countrySlug: string }>;
}) {
  const { countrySlug } = await params;

  // Cached — same call as generateMetadata; React.cache() dedupes.
  const country = await getCountry(countrySlug);

  if (!country) {
    // If slug looks like an escort ID (aw12345), redirect to profile
    if (countrySlug.startsWith("aw") && /^aw\d+$/.test(countrySlug)) {
      const { redirect } = await import("next/navigation");
      redirect(`/view/${countrySlug}`);
    }
    notFound();
  }

  const escortWhere = {
    user_type: "escort" as const,
    country_id: country.id,
    active: true,
    banned_at: null,
  };

  const [escortsRaw, totalCount] = await Promise.all([
    prisma.user.findMany({
      where: escortWhere,
      // Only the columns rendered in the listing card + JSON-LD. Earlier
      // `include: { city: true }` pulled every column on the cities table
      // (potentially large SEO description columns) for each of 48 escorts.
      // A.10: Round 10 stripped is_verified / is_vip / status from the select
      // to slim the query, but those drove the gold "VIP" and "Verified"
      // badges on the cards. Restore them so paying VIPs see their badges
      // on the highest-traffic SEO surface.
      select: {
        id: true,
        id_aw: true,
        username: true,
        profile_photo: true,
        lastonline_at: true,
        is_verified: true,
        is_vip: true,
        status: true,
        city: { select: { name: true, slug: true } },
      },
      orderBy: { lastonline_at: "desc" },
      take: 48,
    }),
    prisma.user.count({ where: escortWhere }),
  ]);
  const escorts = await withAvatarUrls(escortsRaw);

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "ItemList",
    name: `Escorts in ${country.name}`,
    description: `Browse verified escorts in ${country.name} on AdultWorld.`,
    numberOfItems: totalCount,
    itemListElement: escorts.slice(0, 20).map((escort, index) => ({
      "@type": "ListItem",
      position: index + 1,
      url: `${baseUrl}/view/${escort.id_aw}`,
      name: escort.username,
    })),
  };

  return (
    <>
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
    />
    <div className="space-y-6">
      <StickySearchBar />
      <QuickFilters countrySlug={countrySlug} />
      <div>
        <div className="mb-2">
          <Breadcrumbs items={[
            { label: "Escorts", href: "/escorts" },
            { label: country.name },
          ]} />
        </div>
        <h1 className="text-2xl font-bold">
          {totalCount.toLocaleString()} {totalCount === 1 ? "escort" : "escorts"} in {country.name}
        </h1>
      </div>

      {/* City Quick Links */}
      {country.cities.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {country.cities.map((city) => (
            <Link
              key={city.id}
              href={`/escorts/${countrySlug}/${city.slug}`}
              className="bg-surface hover:bg-surface-light text-text-muted hover:text-white px-3 py-1 rounded-full text-sm transition-colors"
            >
              {city.name}
            </Link>
          ))}
        </div>
      )}

      {/* Escort Grid with Infinite Scroll */}
      <InfiniteEscortGrid
        initialEscorts={escorts}
        initialHasMore={escorts.length === 48}
        sort="recently-active"
        countryId={country.id}
      />

      {escorts.length === 0 && (
        <div className="text-center py-16 text-text-muted">
          <p className="text-lg">No escorts found in {country.name}</p>
        </div>
      )}

      {/* SEO Content */}
      <section className="mt-8 border-t border-surface-light pt-6">
        <h2 className="text-lg font-semibold text-white mb-3">
          Escorts in {country.name}
        </h2>
        <div className="text-sm text-text-muted space-y-3">
          <p>
            Discover {totalCount.toLocaleString()} verified escorts in {country.name} on AdultWorld.ai.
            Browse detailed profiles with photos, rates, services offered, and genuine client reviews.
          </p>
          <p>
            Whether you&apos;re looking for companionship, a dinner date, massage services, or a memorable evening,
            our verified providers across {country.name} offer a range of services tailored to your preferences.
            All profiles are verified for your safety and peace of mind.
          </p>
          <p>
            New to AdultWorld? <Link href="/for-clients" className="text-gold hover:underline">Learn how it works</Link> or
            browse our <Link href="/safety" className="text-gold hover:underline">safety guidelines</Link> before your first booking.
            Use our{" "}
            <Link href="/search" className="text-gold hover:underline">advanced search</Link> with filters for city, services, appearance, and availability.
          </p>
        </div>
      </section>
    </div>
    </>
  );
}
