import { prisma } from "@/lib/prisma";
import { Metadata } from "next";
import Link from "next/link";
import { VideoCard } from "@/components/VideoCard";
import { SEO_KEYWORDS } from "@/lib/seoKeywords";
import { Search } from "lucide-react";
import { getCached, setCached } from "@/lib/memoryCache";

interface Props { params: Promise<{ slug: string }> }

function slugToLabel(slug: string) {
  return decodeURIComponent(slug).replace(/-/g, " ");
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const metaCacheKey = `tag_meta_${slug}`;
  const cachedMeta = getCached<Metadata>(metaCacheKey);
  if (cachedMeta) return cachedMeta;

  const kw = slugToLabel(slug);
  const kwCap = kw.charAt(0).toUpperCase() + kw.slice(1);
  const meta: Metadata = {
    title: `${kwCap} - Vidéos Gratuites HD & Streaming Exclusif | MTBR`,
    description: `Regardez les meilleures vidéos ${kw} en streaming gratuit HD sur MTBR. Des milliers de scènes complètes ${kw} sans inscription, en qualité 1080p et 4K.`,
    keywords: [
      kw,
      `${kw} gratuit`,
      `${kw} streaming`,
      `${kw} hd`,
      `${kw} exclusif`,
      `film ${kw}`,
      `mtbr ${kw}`,
      "streaming hd",
      "mtbr",
      "madetobreakrules",
      "video",
    ],
    alternates: { canonical: `https://madetobreakrules.com/tag/${slug}` },
    openGraph: {
      title: `${kwCap} — Vidéos HD Gratuites sur MTBR`,
      description: `Toutes les vidéos ${kw} disponibles gratuitement en HD et 4K sur MTBR.`,
      url: `https://madetobreakrules.com/tag/${slug}`,
      siteName: "MTBR",
      locale: "fr_FR",
      type: "website",
    },
    robots: { index: true, follow: true },
  };
  setCached(metaCacheKey, meta, 86400000);
  return meta;
}

export default async function TagPage({ params }: Props) {
  const { slug } = await params;
  const kw = slugToLabel(slug);
  const kwCap = kw.charAt(0).toUpperCase() + kw.slice(1);

  const tagCacheKey = `tag_data_${slug}`;
  let videos = getCached<any[]>(tagCacheKey);

  if (!videos) {
    // High-precision tokenization: exclude grammatical fillers and keep core intent keywords
    const stopWords = new Set([
      "pour", "avec", "dans", "sur", "les", "des", "une", "est", "par", "and", "the",
      "for", "with", "from", "2026", "hd", "4k", "full", "free", "gratuit", "streaming",
      "vostfr", "sans", "tout", "mon", "ton", "son", "ses", "mes", "tes", "notre", "votre",
      "leur", "cet", "cette", "ces", "lui", "elle", "ils", "elles", "fait", "font", "qui",
      "que", "quoi", "dont", "bien", "plus", "très", "tres", "une"
    ]);

    const rawTokens = kw
      .split(/\s+/)
      .map((w) => w.trim().toLowerCase())
      .filter((w) => w.length >= 3 && !stopWords.has(w));

    const meaningfulTokens = rawTokens.length > 0 ? rawTokens : [kw.split(/\s+/)[0] || kw];

    // 1. High-precision multi-token match: find videos matching all primary tokens in title
    if (meaningfulTokens.length >= 2) {
      videos = await prisma.media.findMany({
        where: {
          type: "VIDEO",
          isPublished: true,
          AND: meaningfulTokens.slice(0, 3).map((t) => ({
            title: { contains: t },
          })),
        },
        select: {
          id: true,
          title: true,
          thumbnailUrl: true,
          duration: true,
          views: true,
          tags: true,
          category: { select: { name: true, slug: true } },
          uploader: { select: { name: true, image: true, isVerified: true } },
        },
        orderBy: { views: "desc" },
        take: 36,
      });
    }

    // 2. Fallback: single primary token match or full phrase contains
    if (!videos || videos.length === 0) {
      videos = await prisma.media.findMany({
        where: {
          type: "VIDEO",
          isPublished: true,
          OR: [
            { title: { contains: meaningfulTokens[0] } },
            { title: { contains: kw } },
          ],
        },
        select: {
          id: true,
          title: true,
          thumbnailUrl: true,
          duration: true,
          views: true,
          tags: true,
          category: { select: { name: true, slug: true } },
          uploader: { select: { name: true, image: true, isVerified: true } },
        },
        orderBy: { views: "desc" },
        take: 36,
      });
    }

    // 3. Fallback: if still few, grab top trending
    if (!videos || videos.length < 6) {
      const fallback = await prisma.media.findMany({
        where: { type: "VIDEO", isPublished: true },
        select: {
          id: true,
          title: true,
          thumbnailUrl: true,
          duration: true,
          views: true,
          tags: true,
          category: { select: { name: true, slug: true } },
          uploader: { select: { name: true, image: true, isVerified: true } },
        },
        orderBy: { views: "desc" },
        take: 24,
      });
      const existingIds = new Set((videos || []).map((v) => v.id));
      videos = [...(videos || []), ...fallback.filter((v) => !existingIds.has(v.id))].slice(0, 36);
    }

    setCached(tagCacheKey, videos, 180000); // 3 min cache
  }

  // Related tags
  const relatedTags = SEO_KEYWORDS
    .filter((k) => k !== kw && (k.includes(kw.split(" ")[0]) || kw.includes(k.split(" ")[0])))
    .slice(0, 16);

  // JSON-LD structured data
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    "name": `${kwCap} - Vidéos HD | MTBR`,
    "description": `Collection complète de vidéos ${kw} en streaming gratuit HD sur MTBR.`,
    "url": `https://madetobreakrules.com/tag/${slug}`,
    "mainEntity": {
      "@type": "ItemList",
      "numberOfItems": videos.length,
      "itemListElement": videos.slice(0, 10).map((v, i) => ({
        "@type": "ListItem",
        "position": i + 1,
        "url": `https://madetobreakrules.com/video/${v.id}`,
        "name": v.title,
      })),
    },
  };

  return (
    <div className="min-h-screen bg-[#070406] text-white">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />

      <div className="max-w-[1600px] mx-auto px-4 lg:px-8 py-8">

        {/* Breadcrumb */}
        <nav className="text-xs text-[#8c7e84] flex items-center gap-1.5 mb-6">
          <Link href="/" className="hover:text-white transition-colors">Accueil</Link>
          <span>→</span>
          <Link href="/categories" className="hover:text-white transition-colors">Catégories</Link>
          <span>→</span>
          <span className="text-white capitalize">{kw}</span>
        </nav>

        {/* Hero Header */}
        <div className="mb-8">
          <h1 className="text-3xl md:text-4xl font-black text-white mb-3 capitalize">
            🔥 {kwCap} — Vidéos Gratuites HD
          </h1>
          <p className="text-[#d8cbd0] text-sm max-w-2xl">
            Découvrez les meilleures vidéos <strong className="text-white">{kw}</strong> en streaming gratuit.
            {videos.length > 0
              ? ` ${videos.length} scènes disponibles en HD et 4K, sans inscription.`
              : " Parcourez notre catalogue complet ou lancez une recherche."}
          </p>

          {/* Search bar button */}
          <div className="mt-4 flex items-center gap-3">
            <Link
              href={`/search?q=${encodeURIComponent(kw)}`}
              className="flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-[#c93f52] to-[#e05a68] rounded-full text-white text-sm font-bold hover:opacity-95 shadow-[0_0_15px_rgba(224,90,104,0.35)] transition-all"
            >
              <Search size={16} />
              Voir tous les résultats "{kw}"
            </Link>
          </div>
        </div>

        {/* Video Grid */}
        {videos.length > 0 ? (
          <>
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-3 mb-10">
              {videos.map((v) => (
                <VideoCard key={v.id} media={v} />
              ))}
            </div>
          </>
        ) : (
          <div className="text-center py-20">
            <p className="text-5xl mb-4">🔍</p>
            <p className="text-[#9c8e92] text-lg mb-6">Aucune vidéo "{kw}" directement, mais notre moteur en trouve !</p>
            <Link
              href={`/search?q=${encodeURIComponent(kw)}`}
              className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-[#c93f52] to-[#e05a68] rounded-full text-white font-bold hover:opacity-95 shadow-[0_0_15px_rgba(224,90,104,0.35)] transition-all"
            >
              <Search size={18} />
              Rechercher "{kw}"
            </Link>
          </div>
        )}

        {/* Related Tags */}
        {relatedTags.length > 0 && (
          <div className="border-t border-[#2e1217] pt-8">
            <h2 className="text-lg font-bold text-white mb-4">Tags similaires</h2>
            <div className="flex flex-wrap gap-2">
              {relatedTags.map((tag) => {
                const tagSlug = tag.trim().toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
                return (
                  <Link
                    key={tag}
                    href={`/tag/${tagSlug}`}
                    className="px-4 py-1.5 bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] text-[#d8cbd0] hover:text-white text-sm rounded-full transition-all"
                  >
                    {tag}
                  </Link>
                );
              })}
            </div>
          </div>
        )}

        {/* SEO Text block */}
        <div className="mt-10 p-6 bg-[#12080b] border border-[#2e1217] rounded-2xl">
          <h2 className="text-xl font-bold text-white mb-3">Vidéos {kwCap} en streaming gratuit</h2>
          <p className="text-[#8c7e84] text-sm leading-relaxed">
            MTBR est la plateforme de référence pour regarder des vidéos <strong className="text-[#d8cbd0]">{kw}</strong> gratuitement en qualité HD et 4K.
            Notre catalogue est mis à jour en continu avec les meilleures scènes <strong className="text-[#d8cbd0]">{kw}</strong> du web.
            Sans inscription, sans abonnement, accédez instantanément à des milliers de vidéos <strong className="text-[#d8cbd0]">{kw}</strong> en streaming direct.
            Retrouvez aussi toutes les catégories : amateur, milf, teen, lesbienne, anal, hentai, et bien plus sur <strong className="text-white">madetobreakrules.com</strong>.
          </p>
        </div>

      </div>
    </div>
  );
}
