export const dynamic = "force-dynamic";

import { Suspense } from "react";
import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { LayoutGrid, ChevronLeft, ChevronRight } from "lucide-react";
import { HorizontalCarousel } from "@/components/HorizontalCarousel";
import { VideoCard } from "@/components/VideoCard";
import { CustomInFeedAdCard, InFeedAd } from "@/components/CustomInFeedAdCard";
import { PersonalizedFeed } from "@/components/PersonalizedFeed";
import { PromoHeroCards } from "@/components/PromoHeroCards";
import { formatNumber } from "@/lib/utils";
import { AdBanner } from "@/components/AdBanner";
import { getCached, setCached } from "@/lib/memoryCache";
import { MobileStoriesBar } from "@/components/MobileStoriesBar";

const PER_PAGE = 32;

export default async function HomePage({
  searchParams,
}: {
  searchParams: any;
}) {
  let resolvedParams: any = {};
  try {
    resolvedParams = (await searchParams) || {};
  } catch {
    resolvedParams = {};
  }

  const pageParam = resolvedParams.page;
  const cat = resolvedParams.cat;
  const tab = resolvedParams.tab || "foryou";
  const page = Math.max(1, parseInt(pageParam || "1") || 1);

  const showForYou = tab === "foryou" && !cat;
  const where: any = { 
    type: "VIDEO", 
    isPublished: true,
  };
  if (cat) where.categoryId = cat;

  let trendingVideos: any[] = [];
  let allCategories: any[] = [];
  let videos: any[] = [];
  let latestVideos: any[] = [];
  let topCreatorsData: any[] = [];

  const cacheKey = `home_${tab}_${cat || "all"}_${page}`;
  const cached = page === 1 ? getCached<any>(cacheKey) : null;

  if (cached) {
    trendingVideos = cached.trendingVideos || [];
    allCategories = cached.allCategories || [];
    videos = cached.videos || [];
    latestVideos = cached.latestVideos || [];
    topCreatorsData = cached.topCreatorsData || [];
  } else {
    try {
      const [tV, aC, vD, lV, tC] = await Promise.all([
        page === 1
          ? prisma.media.findMany({
              where: { 
                type: "VIDEO", 
                isPublished: true,
              },
              orderBy: { createdAt: "desc" },
              take: 5,
              select: {
                id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true,
                uploader: { select: { id: true, name: true, image: true, isVerified: true } }
              }
            }).catch(() => [])
          : Promise.resolve([]),
        prisma.category.findMany({
          take: 40,
          select: { id: true, name: true, slug: true },
        }).catch(() => []),
        !showForYou
          ? (async () => {
              if (cat) {
                return prisma.media.findMany({
                  where,
                  orderBy: { createdAt: "desc" },
                  skip: (page - 1) * PER_PAGE,
                  take: PER_PAGE,
                  select: {
                    id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true,
                    uploader: { select: { id: true, name: true, image: true, isVerified: true } },
                    category: { select: { name: true, slug: true } }
                  }
                }).catch(() => []);
              }
              const vQuota = 24;
              const sQuota = 8;
              const [longVRaw, shortVRaw] = await Promise.all([
                prisma.media.findMany({
                  where: {
                    type: "VIDEO",
                    isPublished: true,
                  },
                  orderBy: { createdAt: "desc" },
                  skip: (page - 1) * vQuota,
                  take: vQuota * 2,
                  select: {
                    id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true, format: true, url: true,
                    uploader: { select: { id: true, name: true, image: true, isVerified: true } },
                    category: { select: { name: true, slug: true } }
                  }
                }).catch(() => []),
                prisma.media.findMany({
                  where: {
                    format: "SHORT",
                    isPublished: true,
                  },
                  orderBy: { createdAt: "desc" },
                  skip: (page - 1) * sQuota,
                  take: sQuota * 2,
                  select: {
                    id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true, format: true, url: true,
                    uploader: { select: { id: true, name: true, image: true, isVerified: true } },
                    category: { select: { name: true, slug: true } }
                  }
                }).catch(() => [])
              ]);
              const longV = longVRaw.filter((v: any) => (!v.url || !v.url.includes("/embed/pm")) && v.format !== "SHORT");
              const shortV = shortVRaw.filter((v: any) => !v.url || !v.url.includes("/embed/pm"));
              const res: any[] = [];
              let vi = 0, si = 0;
              while (res.length < PER_PAGE && (vi < longV.length || si < shortV.length)) {
                for (let k = 0; k < 3 && vi < longV.length && res.length < PER_PAGE; k++) res.push(longV[vi++]);
                if (si < shortV.length && res.length < PER_PAGE) res.push(shortV[si++]);
              }
              while (vi < longV.length && res.length < PER_PAGE) res.push(longV[vi++]);
              while (si < shortV.length && res.length < PER_PAGE) res.push(shortV[si++]);
              return res;
            })()
          : Promise.resolve([]),
        page === 1 && showForYou
          ? prisma.media.findMany({
              where: { 
                type: "VIDEO", 
                isPublished: true,
              },
              orderBy: { views: "desc" },
              take: 8,
              select: {
                id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true,
                uploader: { select: { id: true, name: true, image: true, isVerified: true } },
                category: { select: { name: true, slug: true } }
              }
            }).catch(() => [])
          : Promise.resolve([]),
        page === 1 && showForYou
          ? (async () => {
              try {
                const topToday = await prisma.media.findMany({
                  where: { 
                    type: "VIDEO", 
                    isPublished: true, 
                    uploaderId: { not: null },
                  },
                  orderBy: { views: "desc" },
                  take: 40,
                  select: { uploader: { select: { id: true, name: true, image: true, isVerified: true } } }
                });
                const map = new Map();
                (topToday || []).forEach(m => {
                  if (m?.uploader && !map.has(m.uploader.id)) {
                    map.set(m.uploader.id, m.uploader);
                  }
                });
                return Array.from(map.values()).slice(0, 10);
              } catch {
                return [];
              }
            })()
          : Promise.resolve([]),
      ]);

      trendingVideos = tV || [];
      allCategories = aC || [];
      videos = vD || [];
      latestVideos = lV || [];
      topCreatorsData = tC || [];

      if (page === 1) {
        setCached(cacheKey, { trendingVideos, allCategories, videos, latestVideos, topCreatorsData }, 60000);
      }
    } catch (e) {
      console.error("Error fetching homepage data:", e);
    }
  }

  // Fetch Continue Watching if ForYou and user is logged in
  let continueWatching: any[] = [];
  if (showForYou && page === 1) {
    try {
      const session = await import("@/lib/auth").then(m => m.auth()).catch(() => null);
      const userId = (session?.user as any)?.id;
      if (userId) {
        const history = await prisma.watchHistory.findMany({
          where: { userId },
          orderBy: { updatedAt: "desc" },
          take: 4,
          select: {
            media: {
              select: {
                id: true, title: true, thumbnailUrl: true, duration: true, views: true, isPremium: true, isPublished: true, type: true,
                category: { select: { id: true, name: true, slug: true } }
              }
            }
          }
        }).catch(() => []);
        continueWatching = (history || []).map(h => h.media).filter(m => m && m.isPublished && m.type === "VIDEO");
      }
    } catch (e) {
      console.error("Error loading continue watching:", e);
    }
  }

  const total = 10000;
  const topCreators = (topCreatorsData || []).map((user: any, index: number) => ({
    id: user?.id || String(index),
    name: user?.name || "Anonyme",
    image: user?.image || "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=400&q=80",
    isOnline: index % 2 === 0,
    rank: index + 1,
  }));

  const totalPages = Math.ceil(total / PER_PAGE);
  const isCleanName = (name: string) => Boolean(name && typeof name === "string" && !/^[\d°\s.\-/°]+$/.test(name) && name.length > 2);
  const topCategories = (allCategories || []).filter((c) => c && isCleanName(c.name)).slice(0, 18);

  const buildUrl = (p: number) => {
    const sp = new URLSearchParams();
    if (cat) sp.set("cat", cat);
    if (tab && tab !== "foryou") sp.set("tab", tab);
    sp.set("page", String(p));
    return `/?${sp.toString()}`;
  };

  // Site Builder layout config

  let layoutConfig: any[] = [
    { id: "s1", type: "hero", visible: false },
    { id: "s2", type: "categories", visible: true },
    { id: "s5", type: "continue", visible: true },
    { id: "s6", type: "ad", visible: true },
    { id: "s3", type: "trending", visible: true },
    { id: "s7", type: "latest", visible: true }
  ];
  try {
    const layoutSetting = await prisma.siteSetting.findUnique({ where: { key: "homepage_layout" } });
    if (layoutSetting && layoutSetting.value) {
      layoutConfig = JSON.parse(layoutSetting.value);
    }
  } catch (e) {}

  return (
    <div className="w-full pb-8 min-h-screen relative">
      {/* 🚀 Schema.org Rich Snippets JSON-LD pour Google Search */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            "@context": "https://schema.org",
            "@graph": [
              {
                "@type": "WebSite",
                "@id": "https://madetobreakrules.com/#website",
                "url": "https://madetobreakrules.com",
                "name": "MTBR",
                "description": "Plateforme officielle MTBR — Vidéos & Contenus Exclusifs",
                "potentialAction": {
                  "@type": "SearchAction",
                  "target": "https://madetobreakrules.com/videos?q={search_term_string}",
                  "query-input": "required name=search_term_string"
                },
                "inLanguage": "fr-FR"
              },
              {
                "@type": "Organization",
                "@id": "https://madetobreakrules.com/#organization",
                "name": "MTBR Media",
                "url": "https://madetobreakrules.com",
                "logo": "https://madetobreakrules.com/logo.png"
              }
            ]
          })
        }}
      />

      <div className="absolute top-0 inset-x-0 h-[500px] bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-[#e05a68]/15 via-[#070406]/0 to-transparent pointer-events-none -z-10" />

      <div className="max-w-[2000px] mx-auto pt-0">
        
        {layoutConfig.find(s => s.type === "categories")?.visible && (
          <div 
            style={{ gap: "var(--custom-cat-gap, 12px)" }}
            className="sticky top-[94px] z-30 bg-[#070406]/95 backdrop-blur-2xl py-3.5 flex overflow-x-auto px-3 md:px-4 lg:px-8 scrollbar-hide border-b border-[#2e1217] shadow-lg items-center"
          >
            <Link
              href="/?tab=all"
              prefetch={true}
              style={{ 
                height: "var(--custom-cat-height, 44px)", 
                fontSize: "var(--custom-cat-font, 14.5px)",
                borderRadius: "var(--custom-cat-radius, 16px)"
              }}
              className={`flex-shrink-0 flex items-center gap-2 px-6 font-black transition-all duration-300 ${
                tab === "all" && !cat
                  ? "bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white shadow-[0_0_25px_rgba(224,90,104,0.4)] scale-105"
                  : "bg-[#12080b] border border-[#2e1217] text-[#d8cbd0] hover:border-[#e05a68]/50 hover:text-white hover:bg-[#1a0a0f]"
              }`}
            >
              Toutes les vidéos
            </Link>
            <div className="w-px h-7 bg-[#2e1217] mx-1 self-center flex-shrink-0" />
            {topCategories.map((c) => (
              <Link
                key={c.id || c.slug || c.name}
                href={`/?cat=${c.id}`}
                prefetch={true}
                style={{ 
                  height: "var(--custom-cat-height, 44px)", 
                  fontSize: "var(--custom-cat-font, 14.5px)",
                  borderRadius: "var(--custom-cat-radius, 16px)"
                }}
                className={`flex-shrink-0 flex items-center px-6 font-extrabold transition-all duration-300 ${
                  cat === c.id
                    ? "bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white shadow-[0_0_25px_rgba(224,90,104,0.4)] scale-105"
                    : "bg-[#12080b] border border-[#2e1217] text-[#d8cbd0] hover:border-[#e05a68]/50 hover:text-white hover:bg-[#1a0a0f]"
                }`}
              >
                {c.name}
              </Link>
            ))}
            <Link
              href="/categories"
              prefetch={true}
              style={{ 
                height: "var(--custom-cat-height, 44px)", 
                fontSize: "var(--custom-cat-font, 14.5px)",
                borderRadius: "var(--custom-cat-radius, 16px)"
              }}
              className="flex-shrink-0 flex items-center gap-2 px-6 font-black bg-[#12080b] border border-[#e05a68]/40 text-[#e05a68] hover:bg-[#e05a68]/15 hover:border-[#e05a68] transition-all duration-300"
            >
              <LayoutGrid size={17} /> Tout voir
            </Link>
          </div>
        )}

        {showForYou ? (
          <>
            {/* 📱 Mobile Stories / Trending Models & Shorts Bar */}
            <MobileStoriesBar creators={topCreators} />

            <div style={{ paddingLeft: "var(--custom-hero-pl, 8px)" }} className="pr-2 md:pr-3 lg:pr-4 pt-2.5">
              <PromoHeroCards />
            </div>

            {layoutConfig.map((section) => {
              if (!section.visible) return null;
              
              if (section.type === "ad") return null;

              if (section.type === "continue" && continueWatching.length > 0) return (
                <Suspense key={section.id} fallback={null}>
                  <HorizontalCarousel title="Reprendre la lecture" videos={continueWatching} />
                </Suspense>
              );

              if (section.type === "trending" && latestVideos.length > 0) return (
                <Suspense key={section.id} fallback={null}>
                  <HorizontalCarousel title="Tendances 🔥" videos={latestVideos} viewAllLink="/?tab=all" />
                </Suspense>
              );

              if (section.type === "latest") return (
                <div key={section.id} className="px-3 md:px-4 lg:px-8">
                  <Suspense fallback={<div className="h-96 animate-pulse bg-[#0e0800] rounded-2xl" />}>
                    <PersonalizedFeed />
                  </Suspense>
                </div>
              );

              return null;
            })}
          </>
        ) : (
          <div className="px-3 md:px-4 lg:px-8">
            <div className="flex items-center justify-between mb-5">
              <p className="text-[#c4906a] text-sm">
                <span className="text-white font-bold">{formatNumber(total)}</span> vidéos
                {totalPages > 1 && (
                  <span className="ml-2 text-[#5f5f7a]">· Page {page}/{totalPages}</span>
                )}
              </p>
            </div>

            {await (async () => {
              let gridAds: InFeedAd[] = [];
              try {
                const setting = await prisma.siteSetting.findFirst({
                  where: { key: { in: ["infeed_grid_ads_mtbr", "infeed_grid_ads_dorohub"] } }
                });
                if (setting?.value) {
                  gridAds = JSON.parse(setting.value).filter((a: any) => a.active);
                }
              } catch {}

              const items: any[] = [];
              const adsByPos = new Map<number, InFeedAd>();
              gridAds.forEach(a => adsByPos.set(a.position, a));
              let vIdx = 0;
              let slot = 1;
              const totalItems = videos.length + gridAds.length;
              while (vIdx < videos.length && slot <= totalItems + 5) {
                if (adsByPos.has(slot)) {
                  const ad = adsByPos.get(slot)!;
                  items.push(<CustomInFeedAdCard key={`ad-${ad.id}-${slot}`} ad={ad} />);
                } else {
                  items.push(<VideoCard key={videos[vIdx].id} media={videos[vIdx]} />);
                  vIdx++;
                }
                slot++;
              }
              while (vIdx < videos.length) {
                items.push(<VideoCard key={videos[vIdx].id} media={videos[vIdx]} />);
                vIdx++;
              }

              return (
                <div 
                  style={{ gap: "var(--custom-video-gap, 18px)" }}
                  className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 mb-10"
                >
                  {items}
                </div>
              );
            })()}

            {totalPages > 1 && (
              <div className="flex items-center justify-center gap-4 pt-4 pb-8 border-t border-[#2e1217]">
                {page > 1 ? (
                  <a
                    href={buildUrl(page - 1)}
                    className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] text-sm font-bold text-[#d8cbd0] hover:text-white transition-colors"
                  >
                    <ChevronLeft size={16} /> Précédent
                  </a>
                ) : (
                  <span className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#0a0507] border border-[#1f0d11] text-sm font-bold text-[#5c3038] cursor-not-allowed">
                    <ChevronLeft size={16} /> Précédent
                  </span>
                )}

                <span className="text-sm text-[#9c8e92] font-medium px-2">{page} / {totalPages}</span>

                {page < totalPages ? (
                  <a
                    href={buildUrl(page + 1)}
                    className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white border border-[#e05a68] text-sm font-bold transition-all shadow-[0_0_15px_rgba(224,90,104,0.35)] hover:opacity-95"
                  >
                    Suivant <ChevronRight size={16} />
                  </a>
                ) : (
                  <span className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#0a0507] border border-[#1f0d11] text-sm font-bold text-[#5c3038] cursor-not-allowed">
                    Suivant <ChevronRight size={16} />
                  </span>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
