import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import Link from "next/link";
import { formatNumber, formatDuration } from "@/lib/utils";
import { notFound } from "next/navigation";
import { incrementVisitorCount } from "@/lib/visitorTracking";
import { VideoPlayer } from "@/components/VideoPlayer";
import { RecommendedVideos } from "@/components/RecommendedVideos";
import { VideoActionButtons } from "@/components/VideoActionButtons";
import { AdBanner } from "@/components/AdBanner";

/**
 * ⚡ Extract high-converting n-grams, bigrams, and exact query phrases from title
 */
function extractTitleKeywords(title: string, category: string, rawTags: string[]): string[] {
  const cleanTitle = (title || "").trim();
  const words = cleanTitle
    .toLowerCase()
    .replace(/[^a-z0-9à-ÿ\s-]/gi, " ")
    .split(/\s+/)
    .filter((w) => w.length >= 3);

  const set = new Set<string>();

  // 1. Exact full title
  set.add(cleanTitle.toLowerCase());

  // 2. Bigrams (two-word phrases like "mon frere", "demi soeur", "salope francaise")
  for (let i = 0; i < words.length - 1; i++) {
    set.add(`${words[i]} ${words[i + 1]}`);
  }

  // 3. Trigrams (three-word phrases)
  for (let i = 0; i < words.length - 2; i++) {
    set.add(`${words[i]} ${words[i + 1]} ${words[i + 2]}`);
  }

  // 4. Individual meaningful tokens
  words.filter((w) => w.length >= 4).forEach((w) => set.add(w));

  // 5. Category & tags
  if (category) set.add(category.toLowerCase());
  rawTags.forEach((t) => set.add(t.toLowerCase().trim()));

  // 6. Intent modifiers (gratuit, streaming, hd, film complet)
  set.add(`${cleanTitle.slice(0, 45)} gratuit`);
  set.add(`${cleanTitle.slice(0, 45)} streaming`);
  set.add(`${cleanTitle.slice(0, 45)} hd`);
  set.add(`${cleanTitle.slice(0, 45)} porno`);
  set.add("porno gratuit");
  set.add("streaming hd");
  set.add("mtbr");
  set.add("madetobreakrules");
  set.add("video x");

  return Array.from(set).filter(Boolean).slice(0, 35);
}

/**
 * ⚡ Extract dynamic contextual hashtags linking to `/tag/[slug]`
 */
function extractDynamicHashtags(title: string, category: string, rawTags: string[]): { label: string; slug: string }[] {
  const hashtagsMap = new Map<string, string>();

  // Extract from title: key chunks
  const words = title
    .replace(/[^\w\sà-ÿ-]/gi, " ")
    .split(/\s+/)
    .filter((w) => w.length >= 3);

  // Bigrams from title
  for (let i = 0; i < Math.min(words.length - 1, 4); i += 2) {
    const phrase = `${words[i]} ${words[i + 1]}`;
    const slug = phrase.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
    if (slug.length >= 4) {
      hashtagsMap.set(slug, phrase);
    }
  }

  // Significant individual title words
  for (const w of words.slice(0, 5)) {
    const slug = w.toLowerCase().replace(/[^a-z0-9-]/g, "");
    if (slug.length >= 4 && !hashtagsMap.has(slug)) {
      hashtagsMap.set(slug, w);
    }
  }

  // Category
  if (category) {
    const catSlug = category.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
    if (!hashtagsMap.has(catSlug)) {
      hashtagsMap.set(catSlug, category);
    }
  }

  // Stored tags
  for (const t of rawTags.slice(0, 5)) {
    const cleanT = t.trim();
    const slug = cleanT.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
    if (slug.length >= 3 && !hashtagsMap.has(slug)) {
      hashtagsMap.set(slug, cleanT);
    }
  }

  return Array.from(hashtagsMap.entries())
    .slice(0, 8)
    .map(([slug, label]) => ({
      slug,
      label: label.charAt(0).toUpperCase() + label.slice(1),
    }));
}

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const media = await prisma.media.findUnique({ where: { id, type: "VIDEO" }, include: { category: true } });
  if (!media) return {};

  let tagsArr: string[] = [];
  try {
    tagsArr = media.tags ? (typeof media.tags === "string" ? JSON.parse(media.tags) : (media.tags as string[])) : [];
  } catch { tagsArr = []; }

  const cat = media.category?.name || "Vidéo";
  const kwList = extractTitleKeywords(media.title, cat, tagsArr);
  const metaTitle = `${media.title} - Vidéo HD Gratuite | MTBR`;
  const metaDescription = media.description
    ? media.description.slice(0, 160)
    : `Regardez ${media.title} en streaming HD sur MTBR (Made To Break Rules). Vidéo ${cat} complète sans inscription, qualité 1080p et 4K.`;

  return {
    title: metaTitle,
    description: metaDescription,
    keywords: kwList.join(", "),
    alternates: { canonical: `https://madetobreakrules.com/video/${id}` },
    openGraph: {
      title: metaTitle,
      description: metaDescription,
      images: [{ url: media.thumbnailUrl || "https://madetobreakrules.com/og-default.jpg", width: 1280, height: 720, alt: media.title }],
      type: "video.other",
      url: `https://madetobreakrules.com/video/${id}`,
      siteName: "MTBR",
      locale: "fr_FR",
      videos: media.url ? [{ url: media.url, secureUrl: media.url, type: "video/mp4" }] : undefined,
    },
    twitter: {
      card: "player",
      title: metaTitle,
      description: metaDescription,
      images: [media.thumbnailUrl || "https://madetobreakrules.com/og-default.jpg"],
    },
    robots: { index: true, follow: true },
  };
}

export default async function VideoPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await auth();
  const isPremium = (session?.user as any)?.isPremium;

  const media = await prisma.media.findUnique({
    where: { id },
    include: {
      category: true,
      uploader: true,
      _count: { select: { likes: true, favorites: true, comments: true } },
    },
  });

  if (!media || media.type !== "VIDEO" || !media.isPublished) notFound();

  // Incrémenter les vues en arrière-plan sans bloquer le rendu
  prisma.media.update({ where: { id }, data: { views: { increment: 1 } } }).catch(() => {});
  try { const p = incrementVisitorCount(1); if (p && typeof (p as any).catch === 'function') (p as any).catch(() => {}); } catch (e) {}

  const isLocked = media.isPremium && !isPremium;

  let tagsArr: string[] = [];
  try {
    tagsArr = media.tags ? (typeof media.tags === "string" ? JSON.parse(media.tags) : (media.tags as string[])) : [];
  } catch { tagsArr = []; }

  // Récupérer les vidéos pour la colonne latérale droite (À regarder ensuite)
  const sidebarVideos = await prisma.media.findMany({
    where: {
      type: "VIDEO",
      isPublished: true,
      id: { not: id },
    },
    take: 8,
    orderBy: { views: "desc" },
    include: {
      uploader: { select: { name: true } },
    },
  });

  const catName = media.category?.name || "Vidéos";
  const dynamicHashtags = extractDynamicHashtags(media.title, catName, tagsArr);
  const kwList = extractTitleKeywords(media.title, catName, tagsArr);

  const jsonLdVideo = {
    "@context": "https://schema.org",
    "@type": "VideoObject",
    "name": media.title,
    "description": media.description || `Regardez ${media.title} en streaming HD sur MTBR.`,
    "thumbnailUrl": media.thumbnailUrl || "https://madetobreakrules.com/og-default.jpg",
    "uploadDate": media.createdAt.toISOString(),
    "duration": media.duration ? `PT${Math.floor(media.duration / 60)}M${media.duration % 60}S` : "PT5M0S",
    "embedUrl": `https://madetobreakrules.com/embed/${media.id}`,
    "url": `https://madetobreakrules.com/video/${media.id}`,
    "keywords": kwList.join(", "),
    "publisher": {
      "@type": "Organization",
      "name": "MTBR",
      "logo": { "@type": "ImageObject", "url": "https://madetobreakrules.com/logo.png" }
    },
    "isFamilyFriendly": false,
    "inLanguage": "fr",
    "interactionStatistic": {
      "@type": "InteractionCounter",
      "interactionType": { "@type": "WatchAction" },
      "userInteractionCount": media.views
    },
    ...(media.category ? { "genre": media.category.name } : {}),
  };

  const jsonLdBreadcrumb = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [
      { "@type": "ListItem", "position": 1, "name": "Accueil", "item": "https://madetobreakrules.com" },
      { "@type": "ListItem", "position": 2, "name": catName, "item": media.category ? `https://madetobreakrules.com/categories/${media.category.slug}` : "https://madetobreakrules.com/videos" },
      { "@type": "ListItem", "position": 3, "name": media.title, "item": `https://madetobreakrules.com/video/${media.id}` },
    ]
  };

  return (
    <div className="min-h-screen bg-[#070406] text-white">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLdVideo) }} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLdBreadcrumb) }} />

      <div className="max-w-[1600px] mx-auto px-4 lg:px-6 py-6">
        
        {/* 📌 Fil d'Ariane (Breadcrumb) */}
        <div className="mb-4 text-[12px] font-bold text-[#8c7e84] flex items-center gap-1.5">
          <Link href="/" className="hover:text-white transition-colors">Accueil</Link>
          <span>→</span>
          <Link href={media.category ? `/categories/${media.category.slug}` : "/videos"} className="hover:text-white transition-colors">{catName}</Link>
          <span>→</span>
          <span className="text-white truncate max-w-[400px]">{media.title}</span>
        </div>

        {/* 📌 Disposition 2 Colonnes (Bureau) / 1 Colonne (Mobile) */}
        <div className="flex flex-col lg:flex-row gap-6 items-start">
          
          {/* 👈 COLONNE PRINCIPALE (Lecteur + Titre + Auteur + Actions + Commentaires) */}
          <div className="w-full lg:flex-1 min-w-0">
            {/* 📌 Lecteur Vidéo Principal */}
            <div className="w-full mb-4 md:mb-6 -mx-4 md:mx-0">
              <div className="relative aspect-video bg-black rounded-none md:rounded-2xl overflow-hidden border-y md:border border-[#2e1217] group shadow-2xl">
                <VideoPlayer mediaUrl={media.url} isLocked={isLocked} />

                {/* Overlay Bas-Droite (Timer) */}
                <div className="absolute bottom-[14px] right-[14px] bg-black/85 px-2 py-0.5 rounded-[4px] text-white text-[11px] font-bold border border-white/10 z-20">
                  {media.duration ? formatDuration(media.duration) : "02:11"}
                </div>

                {/* Overlay Haut-Droit (Drapeau 🇫🇷) */}
                <div className="absolute top-[14px] right-[14px] text-[20px] drop-shadow z-20">
                  🇫🇷
                </div>
              </div>
            </div>

            {/* 📌 Zone Méta Vidéo & Action Bar (Sous le Lecteur) */}
            <div className="mt-4 mb-6 pb-6 border-b border-[#2e1217]">
              {/* Titre H1 */}
              <h1 className="text-[20px] md:text-[22px] font-extrabold text-white mb-4 leading-tight">
                {media.title}
              </h1>

              {/* Ligne d'Action Flex */}
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 flex-wrap">
                
                {/* Partie Gauche (Créateur avec Nom d'Acteur/Modèle) */}
                <div className="flex items-center gap-[12px]">
                  <div className="relative">
                    <div className="w-[42px] h-[42px] rounded-full border border-[#e05a68] overflow-hidden bg-[#18080c] flex items-center justify-center">
                      {media.uploader?.image ? (
                        <img src={media.uploader.image} alt="avatar" className="w-full h-full object-cover" />
                      ) : (
                        <span className="text-[#e05a68] font-black text-sm">{(media.uploader?.name || media.title)[0].toUpperCase()}</span>
                      )}
                    </div>
                    <span className="absolute -bottom-1 -right-1 bg-[#c93f52] text-white text-[7px] font-extrabold px-1 rounded-full border border-black">
                      #156
                    </span>
                  </div>

                  <div>
                    <p className="font-extrabold text-[14px] text-white flex items-center gap-1.5">
                      {media.uploader?.name || "Modèle Vérifié"}
                    </p>
                    <p className="text-[11px] text-[#e05a68] font-bold">@{media.uploader?.name ? media.uploader.name.toLowerCase().replace(/[^a-z0-9]/g, '') : "mtbr"}</p>
                  </div>

                  <a 
                    href="https://discord.gg/mtbr" 
                    target="_blank" 
                    rel="noreferrer"
                    className="h-[36px] px-[14px] bg-gradient-to-r from-[#c93f52] to-[#e05a68] rounded-full text-white text-[11px] font-extrabold hover:opacity-95 transition-opacity ml-2 flex items-center justify-center shadow-[0_0_15px_rgba(224,90,104,0.35)]"
                  >
                    🔗 Réseaux MTBR
                  </a>
                </div>

                {/* Partie Centre (Interactions : ❤️ Aimer, 📑 Enregistrer, 🔗 Partager, 🚩 Signaler) */}
                <VideoActionButtons mediaId={media.id} videoTitle={media.title} />

                {/* Partie Droite (Stats & Dynamic Hashtags linking to /tag/[slug]) */}
                <div className="text-right flex flex-col items-end">
                  <p className="text-[12px] font-extrabold text-[#d8cbd0] tracking-wide">
                    HIER · {formatNumber(media.views + 1)} VUES
                  </p>
                  <div className="flex flex-wrap justify-end gap-1.5 mt-1.5 max-w-[440px]">
                    {dynamicHashtags.map((tagItem) => (
                      <Link
                        key={tagItem.slug}
                        href={`/tag/${tagItem.slug}`}
                        className="text-[10px] font-bold text-[#e05a68] bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] hover:text-white px-2.5 py-0.5 rounded-full transition-all"
                      >
                        #{tagItem.label}
                      </Link>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* 📌 Section Commentaires */}
            <div className="mt-4 pt-4 border-t border-[#2e1217] mb-6">
              <h3 className="text-[16px] font-extrabold text-white">0 commentaire</h3>
              <div className="flex items-center gap-[12px] mt-[12px]">
                <div className="w-[36px] h-[36px] rounded-full bg-[#18080c] border border-[#2e1217] flex items-center justify-center text-xs font-bold text-white shrink-0">
                  U
                </div>
                <input
                  type="text"
                  placeholder="Ajoute un commentaire..."
                  className="flex-1 bg-transparent border-none border-b border-[#38151c] focus:border-[#e05a68] py-2 text-[13px] text-white placeholder-[#8c7e84] outline-none transition-colors"
                />
              </div>
            </div>
          </div>

          {/* 👉 COLONNE LATÉRALE DROITE (Pub + À regarder ensuite) */}
          <aside className="w-full lg:w-[320px] xl:w-[340px] shrink-0 flex flex-col gap-6">
            
            <div className="w-full flex justify-center">
              <AdBanner zoneId="6041250" className="my-0" />
            </div>

            {/* 📌 File "À regarder ensuite" */}
            <div className="flex flex-col gap-3">
              <div className="flex items-center justify-between pb-2 border-b border-[#2e1217]">
                <h3 className="text-[14px] font-extrabold text-white flex items-center gap-2">
                  <span>▶️</span> À regarder ensuite
                </h3>
                <span className="text-[11px] font-bold text-[#e05a68]">Recommandés</span>
              </div>

              <div className="flex flex-col gap-3">
                {sidebarVideos.map((vid) => (
                  <Link
                    key={vid.id}
                    href={`/video/${vid.id}`}
                    className="flex gap-3 group items-start hover:bg-[#12080b] p-1.5 rounded-xl transition-all border border-transparent hover:border-[#2e1217]"
                  >
                    {/* Vignette compacte 16:9 */}
                    <div className="relative w-[120px] sm:w-[130px] aspect-video shrink-0 rounded-lg overflow-hidden bg-[#18080c] border border-[#2e1217]">
                      <img
                        src={vid.thumbnailUrl || "https://madetobreakrules.com/og-default.jpg"}
                        alt={vid.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                        loading="lazy"
                      />
                      {vid.duration && (
                        <span className="absolute bottom-1 right-1 bg-black/85 px-1 py-0.5 rounded text-[10px] font-bold text-white border border-white/10">
                          {formatDuration(vid.duration)}
                        </span>
                      )}
                    </div>

                    {/* Infos Vidéo */}
                    <div className="flex-1 min-w-0">
                      <h4 className="text-[12px] font-bold text-white group-hover:text-[#e05a68] line-clamp-2 leading-tight">
                        {vid.title}
                      </h4>
                      <p className="text-[11px] text-[#8c7e84] mt-1 truncate">
                        {vid.uploader?.name || "Modèle Vérifié"}
                      </p>
                      <p className="text-[10px] font-bold text-[#5c3038] mt-0.5">
                        {formatNumber(vid.views)} vues
                      </p>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          </aside>

        </div>

        {/* 📌 Section Recommandations Complètes & Grille Vidéo (Sous le bloc 2 colonnes) */}
        <div className="mt-10 pt-8 border-t border-[#2e1217]">
          <RecommendedVideos mediaId={media.id} isPremium={media.isPremium} />
        </div>

      </div>
    </div>
  );
}
