"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import {
  ArrowRight,
  BookOpenCheck,
  BriefcaseBusiness,
  CalendarClock,
  Network,
  Palette,
  Sparkles,
  Users,
  Wrench,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import AnimatedNumber from "@/components/ppdb/AnimatedNumber";
import { navigate, scrollToId } from "@/lib/router";
import type { PublicData } from "@/lib/types";

function useCountdown(target: number | null) {
  const [now, setNow] = useState<number | null>(null);
  useEffect(() => {
    const raf = requestAnimationFrame(() => setNow(Date.now()));
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => {
      cancelAnimationFrame(raf);
      clearInterval(t);
    };
  }, []);
  if (!target || now === null) return null;
  const diff = Math.max(0, target - now);
  return {
    hari: Math.floor(diff / 86400000),
    jam: Math.floor((diff % 86400000) / 3600000),
    menit: Math.floor((diff % 3600000) / 60000),
    detik: Math.floor((diff % 60000) / 1000),
  };
}

function CountChip({ value, label, delay }: { value: number; label: string; delay: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.85 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ delay, type: "spring", stiffness: 200, damping: 16 }}
      className="flex min-w-16 flex-col items-center rounded-2xl border border-yellow-500/30 bg-[#5d1420]/80 px-3 py-2 backdrop-blur"
    >
      <span className="text-xl sm:text-2xl font-extrabold tabular-nums text-[#F5C451]">
        {String(value).padStart(2, "0")}
      </span>
      <span className="text-[10px] sm:text-xs font-medium uppercase tracking-wider text-yellow-100/70">
        {label}
      </span>
    </motion.div>
  );
}

const ORBIT = [
  { Icon: Wrench, pos: "top-4 left-6", anim: "animate-float", color: "bg-amber-500/15 text-amber-300" },
  { Icon: Network, pos: "top-16 right-4", anim: "animate-float-alt", color: "bg-sky-500/15 text-sky-300" },
  { Icon: BriefcaseBusiness, pos: "bottom-16 left-10", anim: "animate-float-alt", color: "bg-emerald-500/15 text-emerald-300" },
  { Icon: Palette, pos: "bottom-4 right-8", anim: "animate-float", color: "bg-pink-500/15 text-pink-300" },
];

export default function Hero({ data, loading }: { data: PublicData | null; loading: boolean }) {
  const ta = data?.tahunAjaran || "";
  const selesai = data?.periodeSelesai ? new Date(data.periodeSelesai).getTime() : null;
  const mulai = data?.periodeMulai ? new Date(data.periodeMulai).getTime() : null;
  const isBefore = data?.periode.status === "BEFORE";
  const target = isBefore ? mulai : selesai;
  const cd = useCountdown(target);

  const total = data?.total ?? 0;
  const totalKuota = data?.perJurusan.reduce((a, j) => a + j.kuota, 0) ?? 0;
  const terisi = data?.perJurusan.reduce((a, j) => a + j.terisi, 0) ?? 0;

  return (
    <section id="beranda" className="relative overflow-hidden bg-[#4a121c]">
      {/* dekorasi latar */}
      <div className="pointer-events-none absolute inset-0 bg-gradient-to-br from-[#4a121c] via-[#5d1420] to-[#3a0e15]" />
      <div className="pointer-events-none absolute inset-0 bg-dots opacity-40" />
      <div className="animate-blob pointer-events-none absolute -top-24 -left-24 size-96 bg-[#7B1E28]/70 blur-2xl" />
      <div className="animate-blob pointer-events-none absolute top-1/3 -right-24 size-105 bg-[#D4A017]/20 blur-3xl [animation-delay:-4s]" />
      <div className="animate-blob pointer-events-none absolute -bottom-28 left-1/4 size-90 bg-[#a32838]/50 blur-2xl [animation-delay:-8s]" />

      <div className="relative mx-auto grid max-w-7xl gap-10 px-4 pb-16 pt-28 sm:px-6 lg:grid-cols-[1.15fr_0.85fr] lg:items-center lg:pb-24 lg:pt-36">
        {/* kolom teks */}
        <div className="text-center lg:text-left">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            className="inline-flex items-center gap-2 rounded-full border border-yellow-500/40 bg-yellow-500/10 px-4 py-1.5 text-xs font-semibold tracking-wide text-yellow-300"
          >
            <Sparkles className="size-4" />
            {loading ? "Memuat status pendaftaran…" : `PPDB Tahun Ajaran ${ta} ${data?.periode.status === "OPEN" ? "DIBUKA" : data?.periode.label.toUpperCase() || ""}`}
          </motion.div>

          <motion.h1
            initial={{ opacity: 0, y: 24 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.55, delay: 0.1 }}
            className="mt-5 text-4xl font-extrabold leading-[1.12] tracking-tight text-white sm:text-5xl lg:text-6xl"
          >
            Pendaftaran Siswa Baru
            <br />
            <span
              className="bg-clip-text text-transparent"
              style={{
                backgroundImage: "linear-gradient(100deg,#D4A017 15%,#F5D77A 40%,#C18E12 60%,#D4A017 80%)",
                backgroundSize: "200% auto",
                animation: "ppdb-shine 5s linear infinite",
              }}
            >
              SMK Al Aitaam
            </span>
          </motion.h1>

          <motion.p
            initial={{ opacity: 0, y: 24 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.55, delay: 0.2 }}
            className="mx-auto mt-5 max-w-xl text-base leading-relaxed text-white/75 sm:text-lg lg:mx-0"
          >
            Daftar online dengan mudah, pilih 4 program keahlian unggulan, dan pantau proses
            verifikasi secara transparan. Bergabunglah bersama generasi kompeten, berkarakter,
            dan siap kerja.
          </motion.p>

          {/* countdown */}
          {cd && data?.periode.status !== "AFTER" && (
            <motion.div
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.3 }}
              className="mt-7 flex flex-wrap items-center justify-center gap-2.5 lg:justify-start"
            >
              <span className="mr-1 inline-flex items-center gap-1.5 text-sm font-medium text-yellow-100/80">
                <CalendarClock className="size-4" />
                {isBefore ? "Dibuka dalam" : "Berakhir dalam"}
              </span>
              <CountChip value={cd.hari} label="Hari" delay={0.35} />
              <CountChip value={cd.jam} label="Jam" delay={0.4} />
              <CountChip value={cd.menit} label="Menit" delay={0.45} />
              <CountChip value={cd.detik} label="Detik" delay={0.5} />
            </motion.div>
          )}

          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.4 }}
            className="mt-7 flex flex-wrap items-center justify-center gap-3 lg:justify-start"
          >
            <Button
              size="lg"
              onClick={() => navigate("daftar")}
              className="group h-12 rounded-full bg-gradient-to-r from-[#D4A017] to-[#F0B429] px-7 text-base font-bold text-[#4a121c] shadow-xl shadow-yellow-900/30 transition-all hover:-translate-y-0.5 hover:shadow-2xl"
            >
              Daftar Sekarang
              <ArrowRight className="size-5 transition-transform group-hover:translate-x-1" />
            </Button>
            <Button
              size="lg"
              variant="outline"
              onClick={() => scrollToId("jurusan")}
              className="h-12 rounded-full border-white/25 bg-white/5 px-7 text-base font-semibold text-white backdrop-blur hover:bg-white/15 hover:text-white"
            >
              <BookOpenCheck className="size-5" />
              Lihat Jurusan
            </Button>
          </motion.div>

          {/* statistik */}
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.55 }}
            className="mt-9 grid max-w-xl grid-cols-3 gap-3 lg:mx-0"
          >
            <div className="rounded-2xl border border-white/10 bg-white/5 p-4 backdrop-blur">
              <AnimatedNumber value={total} className="text-2xl font-extrabold text-white sm:text-3xl" />
              <p className="mt-1 flex items-center gap-1 text-xs text-white/60">
                <Users className="size-3.5" /> Total Pendaftar
              </p>
            </div>
            <div className="rounded-2xl border border-white/10 bg-white/5 p-4 backdrop-blur">
              <AnimatedNumber value={Math.max(0, totalKuota - terisi)} className="text-2xl font-extrabold text-white sm:text-3xl" />
              <p className="mt-1 flex items-center gap-1 text-xs text-white/60">
                <BookOpenCheck className="size-3.5" /> Kuota Tersedia
              </p>
            </div>
            <div className="rounded-2xl border border-white/10 bg-white/5 p-4 backdrop-blur">
              <span className="text-2xl font-extrabold text-white sm:text-3xl">4</span>
              <p className="mt-1 flex items-center gap-1 text-xs text-white/60">
                <Sparkles className="size-3.5" /> Program Keahlian
              </p>
            </div>
          </motion.div>
        </div>

        {/* kolom visual orbit */}
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.7, delay: 0.3 }}
          className="relative mx-auto hidden aspect-square w-full max-w-md lg:block"
          aria-hidden
        >
          <div className="animate-spin-slow absolute inset-6 rounded-full border-2 border-dashed border-yellow-500/25" />
          <div className="absolute inset-16 rounded-full border border-white/10" />
          <div className="absolute inset-0 grid place-items-center">
            <div className="glass-card flex size-56 flex-col items-center justify-center rounded-[2rem] border-yellow-500/30 p-6 text-center shadow-2xl">
              <svg viewBox="0 0 64 64" className="size-16" role="img" aria-label="Logo SMK Al Aitaam">
                <rect x="2" y="2" width="60" height="60" rx="14" fill="#7B1E28" />
                <rect x="6" y="6" width="52" height="52" rx="11" fill="none" stroke="#D4A017" strokeWidth="2.5" />
                <path d="M32 16 L52 25 L32 34 L12 25 Z" fill="#D4A017" />
                <path d="M22 29 L22 38 C22 42 27 45 32 45 C37 45 42 42 42 38 L42 29 L32 33.5 Z" fill="#F5E6C8" />
                <rect x="46" y="26" width="3" height="12" rx="1.5" fill="#D4A017" />
                <circle cx="47.5" cy="41" r="2.2" fill="#D4A017" />
              </svg>
              <p className="mt-3 text-lg font-extrabold text-[#4a1520]">SMK Al Aitaam</p>
              <p className="text-xs font-medium text-[#8a6a10]">PPDB Online {ta}</p>
            </div>
          </div>
          {ORBIT.map(({ Icon, pos, anim, color }, i) => (
            <div key={i} className={`absolute ${pos} ${anim} grid size-16 place-items-center rounded-2xl border border-white/15 backdrop-blur ${color}`}>
              <Icon className="size-7" />
            </div>
          ))}
        </motion.div>
      </div>
    </section>
  );
}
