import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { LayoutGrid } from "lucide-react";
import { formatNumber } from "@/lib/utils";
import { getCached, setCached } from "@/lib/memoryCache";

export const dynamic = "force-dynamic";
export const metadata = { title: "Catégories – MTBR" };

export default async function CategoriesPage() {
  const cached = getCached<any[]>("categories_page_all");
  let enriched: any[] = [];

  // ⚡ Cache global mémoire 1 heure pour réponse instantanée (0.1ms)
  if (cached && cached.length > 0) {
    enriched = cached;
  } else {
    try {
      const categories = await prisma.category.findMany({
        orderBy: { name: "asc" },
        include: {
          _count: { select: { media: { where: { isPublished: true, type: "VIDEO" } } } },
        },
      });

      // Enrichit chaque catégorie avec sa miniature via index composite (0.07ms par cat)
      enriched = await Promise.all(
        categories.map(async (cat) => {
          if (cat.image) return { ...cat, cover: cat.image };
          const top = await prisma.media.findFirst({
            where: { categoryId: cat.id, isPublished: true, type: "VIDEO", thumbnailUrl: { not: null } },
            orderBy: { views: "desc" },
            select: { thumbnailUrl: true },
          }).catch(() => null);
          return { ...cat, cover: top?.thumbnailUrl ?? null };
        })
      );

      setCached("categories_page_all", enriched, 3600000); // 1 heure
    } catch (err) {
      enriched = cached || [];
    }
  }

  return (
    <div className="max-w-7xl mx-auto px-3 md:px-4 py-4 md:py-8">
      <div className="flex items-center gap-3 mb-8">
        <LayoutGrid className="text-[#e05a68]" size={28} />
        <div>
          <h1 className="text-xl md:text-2xl font-black text-white">Toutes les Catégories</h1>
          <p className="text-[#aaaaaa] text-sm">{enriched.length} catégories disponibles</p>
        </div>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-2 md:gap-3">
        {enriched.map((category) => (
          <Link
            key={category.id}
            href={`/categories/${category.slug}`}
            prefetch={true}
            className="group relative aspect-[4/3] rounded-xl overflow-hidden bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] transition-all duration-200 block"
          >
            {/* Cover image — thumbnail réelle de la catégorie */}
            {category.cover ? (
              <img
                src={category.cover}
                alt={category.name}
                className="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:opacity-90 group-hover:scale-105 transition-all duration-300"
              />
            ) : (
              <div className="absolute inset-0 bg-gradient-to-br from-[#12080b] to-[#070406]" />
            )}

            {/* Gradient overlay */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/95 via-black/40 to-transparent" />

            {/* Text */}
            <div className="absolute bottom-0 left-0 right-0 p-3">
              <h2 className="text-white font-bold text-sm leading-tight truncate group-hover:text-[#e05a68] transition-colors">
                {category.name}
              </h2>
              <p className="text-[#888888] text-[11px] font-semibold mt-0.5">
                {formatNumber(category._count.media)} vidéos
              </p>
            </div>
          </Link>
        ))}

        {enriched.length === 0 && (
          <div className="col-span-full py-20 text-center text-[#aaaaaa]">
            Import en cours, revenez dans quelques secondes...
          </div>
        )}
      </div>
    </div>
  );
}

