import Image from "next/image";
import Link from "next/link";
import type { ReactNode } from "react";
import {
  BadgeCheck,
  CalendarDays,
  ChevronRight,
  CircleHelp,
  Clock3,
  Dice5,
  Gift,
  Search,
  Shield,
  ShieldCheck,
  TrendingUp,
  Trophy
} from "lucide-react";
import { miniGames } from "@/lib/casino-games";
import { getPresenceJackpotSnapshot, type PresenceJackpotSnapshot } from "@/server/promotions/presence-jackpot";

const popularGames = miniGames.filter((game) => ["dice", "mines", "plinko", "limbo", "blackjack"].includes(game.slug));

export const dynamic = "force-dynamic";

const sportCards = [
  { title: "Football", href: "/sports/football", image: "/images/home/football-card.png", tone: "from-felt/30 to-blue-500/25" },
  { title: "Tennis", href: "/sports/tennis", image: "/images/home/tennis-card.png", tone: "from-orange-400/25 to-rose-500/20" },
  { title: "Basketball", href: "/sports/basketball", image: "/images/home/basketball-card.png", tone: "from-red-500/25 to-felt/15" }
];

const faq = [
  {
    question: "Que représente ZiraBet ?",
    answer: "ZiraBet réunit un sportsbook crypto, un wallet indépendant et des mini-jeux originaux dans une interface pensée mobile."
  },
  {
    question: "Avec quelles devises puis-je déposer ?",
    answer: "Les dépôts crypto sont prévus en BTC, ETH, USDT et USDC, convertis en EUR au taux du dépôt."
  },
  {
    question: "Quels jeux sont disponibles ?",
    answer: "Dice, Limbo, Mines et Blackjack sont les premiers mini-jeux ZiraBet. Les slots et le casino live seront ajoutés ensuite."
  },
  {
    question: "Sur quels sports puis-je parier ?",
    answer: "La page Sports affiche les compétitions pré-match disponibles, triées par sport et compétition."
  }
];

export default async function HomePage() {
  const presenceJackpot = await getPresenceJackpotSnapshot();

  return (
    <main className="mx-auto max-w-[1180px] space-y-4 sm:space-y-5">
      <section className="space-y-3">
        <PresenceJackpotCard jackpot={presenceJackpot} />
        <div className="grid grid-cols-2 gap-3">
          <HeroTile href="/casino" title="Casino" image="/images/home/casino-hero.png" icon={<Dice5 className="h-4 w-4" />} />
          <HeroTile href="/sports" title="Sports" image="/images/home/sports-hero.png" icon={<Trophy className="h-4 w-4" />} />
        </div>
      </section>

      <Link
        href="/sports"
        className="flex h-12 items-center gap-3 rounded-lg border border-white/10 bg-[#111923] px-3 text-sm font-semibold text-slate-400 shadow-panel transition hover:border-felt/25 hover:text-white"
      >
        <Search className="h-5 w-5 text-slate-500" />
        <span className="min-w-0 flex-1 truncate">Rechercher un match, un jeu ou une promotion</span>
        <ChevronRight className="h-4 w-4 text-slate-600" />
      </Link>

      <CompactRail
        title="Jeux populaires"
        href="/casino"
        icon={<TrendingUp className="h-5 w-5 text-felt" />}
      >
        {popularGames.map((game) => (
          <Link key={game.slug} href={`/casino/games/${game.slug}`} className="group min-w-0">
            <div className="relative aspect-[150/205] overflow-hidden rounded-lg border border-white/10 bg-[#151a22] shadow-panel">
              <Image src={game.image} alt="" fill sizes="(max-width: 640px) 42vw, 180px" className="object-cover transition duration-300 group-hover:scale-[1.04]" />
              <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black via-black/55 to-transparent p-2.5">
                <p className="truncate text-[14px] font-black uppercase leading-none text-white sm:text-[16px]">{game.title}</p>
                <span className="mt-1 inline-flex items-center gap-1 text-[10px] font-bold text-felt">
                  <span className="h-1.5 w-1.5 rounded-full bg-felt" />
                  Disponible
                </span>
              </div>
            </div>
          </Link>
        ))}
      </CompactRail>

      <CompactRail title="Sports en vogue" href="/sports" icon={<Trophy className="h-5 w-5 text-felt" />}>
        {sportCards.map((sport) => (
          <Link key={sport.title} href={sport.href} className="group min-w-0">
            <div className="relative aspect-[5/4] overflow-hidden rounded-lg border border-white/10 bg-[#151a22] shadow-panel">
              <Image src={sport.image} alt="" fill sizes="(max-width: 640px) 42vw, 220px" className="object-cover transition duration-300 group-hover:scale-[1.04]" />
              <div className={`absolute inset-0 bg-gradient-to-t ${sport.tone}`} />
              <div className="absolute inset-x-0 bottom-0 p-3">
                <p className="max-w-full whitespace-normal break-words text-[15px] font-black uppercase leading-[1.05] text-white sm:text-[18px]">{sport.title}</p>
                <span className="mt-1 inline-flex items-center gap-1 text-[10px] font-bold text-felt">
                  <span className="h-1.5 w-1.5 rounded-full bg-felt" />
                  Pré-match
                </span>
              </div>
            </div>
          </Link>
        ))}
      </CompactRail>

      <section className="space-y-2.5">
        <SectionHeader title="Promotions" href="/promotions" icon={<Gift className="h-5 w-5 text-felt" />} />
        <div className="-mx-5 overflow-x-auto px-5 [scrollbar-width:none] sm:mx-0 sm:px-0 [&::-webkit-scrollbar]:hidden">
          <div className="flex gap-3">
            <PromoCard href="/promotions" image="/images/home/promo-sport-boosts.png" title="Cotes boostées" />
            <PromoCard href="/promotions" image="/images/home/promo-sport-offers.png" title="Offres sport" />
            <PromoCard href="/promotions" image="/images/promos/deposit-x3.png" title="Offre de bienvenue" />
          </div>
        </div>
      </section>

      <section className="grid gap-3 lg:grid-cols-[360px_minmax(0,1fr)]">
        <div className="rounded-lg border border-white/10 bg-[#121923] p-4 shadow-panel">
          <div className="flex items-center gap-2 text-[11px] font-black uppercase tracking-[0.08em] text-felt">
            <ShieldCheck className="h-4 w-4" />
            Plateforme
          </div>
          <h2 className="mt-2 text-xl font-extrabold text-white">Une base claire pour jouer sereinement.</h2>
          <div className="mt-4 grid gap-2 text-xs font-bold text-slate-300">
            <TrustRow label="Wallet crypto-only" />
            <TrustRow label="Mini-jeux avec équité vérifiable" />
            <TrustRow label="Interface optimisée mobile" />
          </div>
        </div>
        <div className="rounded-lg border border-white/10 bg-[#121923] p-4 shadow-panel">
          <div className="mb-3 flex items-center gap-2">
            <CircleHelp className="h-5 w-5 text-felt" />
            <h2 className="text-lg font-extrabold text-white">Vous avez encore des questions ?</h2>
          </div>
          <div className="space-y-2">
            {faq.map((item) => (
              <details key={item.question} className="group rounded-lg border border-white/10 bg-white/[0.035] px-3 py-2.5">
                <summary className="flex cursor-pointer list-none items-center justify-between gap-3 text-[13px] font-extrabold text-white">
                  {item.question}
                  <ChevronRight className="h-4 w-4 shrink-0 text-slate-500 transition group-open:rotate-90" />
                </summary>
                <p className="mt-2 text-xs font-medium leading-5 text-slate-400">{item.answer}</p>
              </details>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

function PresenceJackpotCard({ jackpot }: { jackpot: PresenceJackpotSnapshot }) {
  const currentAmount = Number(jackpot.currentDraw.amount);
  const nextAmount = Number(jackpot.nextDraw.amountIfUnclaimed);

  return (
    <section className="relative overflow-hidden rounded-lg border border-white/10 bg-[#07110f] p-3.5 shadow-panel sm:p-4">
      <Image
        src="/images/home/jackpot-presence.png"
        alt=""
        fill
        priority
        sizes="(max-width: 768px) 100vw, 1180px"
        className="object-cover object-[62%_center] opacity-90"
      />
      <div className="absolute inset-0 bg-[linear-gradient(90deg,#07100f_0%,rgba(7,16,15,.96)_30%,rgba(7,16,15,.65)_58%,rgba(7,16,15,.22)_100%)]" />
      <div className="absolute inset-x-0 bottom-0 h-28 bg-gradient-to-t from-[#07100f] to-transparent" />

      <div className="relative z-10 max-w-[560px] py-0.5 sm:py-2">
        <div className="inline-flex h-7 items-center gap-1.5 rounded-full border border-felt/20 bg-felt/10 px-2.5 text-[10px] font-black uppercase tracking-[0.08em] text-felt">
          <Gift className="h-3.5 w-3.5" />
          Promo quotidienne
        </div>
        <h1 className="mt-3 text-[26px] font-extrabold leading-[1.02] text-white sm:text-[34px]">Jackpot Présence</h1>
        <div className="mt-1 text-[54px] font-black leading-none text-[#b8ffe6] drop-shadow-[0_0_22px_rgba(15,191,143,.45)] sm:text-[72px]">
          {formatHomeEuro(currentAmount)}
        </div>
        <p className="mt-2.5 max-w-[480px] text-[13px] font-medium leading-5 text-slate-300 sm:text-sm">
          Chaque jour, un client est tiré au sort. S’il se connecte, il remporte le jackpot. Sinon, le montant augmente de{" "}
          <span className="font-black text-felt">+5€</span> pour le lendemain.
        </p>
        <div className="mt-2.5 flex flex-wrap gap-1.5 text-[11px] font-extrabold text-slate-300">
          <span className="inline-flex h-7 items-center gap-1.5 rounded-full border border-felt/15 bg-felt/10 px-2.5 text-felt">
            <CalendarDays className="h-3.5 w-3.5" />
            Aujourd’hui : {formatHomeEuro(currentAmount)}
          </span>
          <span className="inline-flex h-7 items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.06] px-2.5">
            Demain : <span className="text-felt">{formatHomeEuro(nextAmount)}</span> si non réclamé
          </span>
        </div>
        <div className="mt-2.5 flex flex-wrap gap-1.5">
          <InfoPill icon={<Clock3 className="h-3.5 w-3.5" />} label={`Tirage à ${jackpot.rules.drawTime}`} />
          <InfoPill icon={<Shield className="h-3.5 w-3.5" />} label="24h pour réclamer" />
        </div>
        <div className="mt-3 grid grid-cols-2 gap-2 sm:max-w-[520px]">
          <Link href="/jackpot-presence" className="grid h-10 place-items-center rounded-lg bg-felt px-3 text-xs font-black text-ink-950 shadow-[0_12px_26px_rgba(15,191,143,.22)] sm:px-4 sm:text-[13px]">
            <span className="whitespace-nowrap">
              Vérifier maintenant
            </span>
          </Link>
          <Link href="/jackpot-presence" className="grid h-10 place-items-center rounded-lg border border-white/10 bg-[#0d1821]/80 px-3 text-xs font-extrabold text-white backdrop-blur sm:px-4 sm:text-[13px]">
            <span className="whitespace-nowrap">
              En savoir plus
            </span>
          </Link>
        </div>
      </div>
    </section>
  );
}

function formatHomeEuro(value: number) {
  if (!Number.isFinite(value)) return "--";
  return `${Math.round(value)}€`;
}

function InfoPill({ icon, label }: { icon: ReactNode; label: string }) {
  return (
    <span className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-felt/15 bg-[#081b18]/80 px-2.5 text-[11px] font-extrabold text-slate-200 backdrop-blur">
      <span className="text-felt">{icon}</span>
      {label}
    </span>
  );
}

function HeroTile({ href, title, image, icon }: { href: string; title: string; image: string; icon: ReactNode }) {
  return (
    <Link href={href} className="group relative min-h-[132px] overflow-hidden rounded-lg border border-white/10 bg-[#151a22] shadow-panel">
      <Image src={image} alt="" fill priority sizes="(max-width: 1024px) 50vw, 420px" className="object-cover transition duration-300 group-hover:scale-[1.03]" />
      <div className="absolute inset-0 bg-gradient-to-t from-black/82 via-black/20 to-transparent" />
      <div className="absolute inset-x-0 bottom-0 flex items-center justify-between p-3">
        <div>
          <span className="mb-1 inline-flex items-center gap-1.5 rounded-md bg-black/40 px-2 py-1 text-[10px] font-black uppercase text-felt backdrop-blur">
            {icon}
            ZiraBet
          </span>
          <h2 className="text-xl font-black text-white">{title}</h2>
        </div>
        <ChevronRight className="h-5 w-5 text-white/75" />
      </div>
    </Link>
  );
}

function CompactRail({ title, href, icon, children }: { title: string; href: string; icon: ReactNode; children: ReactNode }) {
  return (
    <section className="space-y-2.5">
      <SectionHeader title={title} href={href} icon={icon} />
      <div className="grid grid-cols-3 gap-2.5 sm:grid-cols-4 lg:grid-cols-6">{children}</div>
      <Link href={href} className="flex items-center gap-3 text-center text-xs font-black text-slate-500">
        <span className="h-px flex-1 bg-white/10" />
        Voir plus
        <span className="h-px flex-1 bg-white/10" />
      </Link>
    </section>
  );
}

function SectionHeader({ title, href, icon }: { title: string; href: string; icon: ReactNode }) {
  return (
    <div className="flex items-center justify-between gap-3">
      <div className="flex min-w-0 items-center gap-2">
        {icon}
        <h2 className="truncate text-lg font-extrabold text-white">{title}</h2>
      </div>
      <Link href={href} className="shrink-0 text-xs font-black text-slate-300 transition hover:text-felt">
        Voir tout
      </Link>
    </div>
  );
}

function PromoCard({ href, image, title }: { href: string; image: string; title: string }) {
  return (
    <Link href={href} className="relative aspect-[720/300] w-[78vw] max-w-[560px] shrink-0 overflow-hidden rounded-lg border border-white/10 bg-[#151a22] shadow-panel sm:w-[420px]">
      <Image src={image} alt="" fill sizes="(max-width: 640px) 78vw, 420px" className="object-cover" />
      <div className="absolute inset-0 bg-gradient-to-t from-black/82 via-black/12 to-transparent" />
      <div className="absolute inset-x-0 bottom-0 p-3">
        <p className="text-sm font-black text-white">{title}</p>
      </div>
    </Link>
  );
}

function TrustRow({ label }: { label: string }) {
  return (
    <div className="flex h-9 items-center gap-2 rounded-lg bg-white/[0.035] px-3">
      <BadgeCheck className="h-4 w-4 text-felt" />
      {label}
    </div>
  );
}
