import { Button } from "@/components/ui/button";
import { PlayCircle, GraduationCap, Users, Calendar, Newspaper, ImageIcon, ArrowRight, Trophy, Mic2, Award, FileText, Activity, Terminal } from "lucide-react";
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { getKabinetAktif } from "@/lib/data";
import { format } from "date-fns";
import { id } from "date-fns/locale";
import KomentarSection from "@/components/public/komentar-section";
import FeedbackSection from "@/components/public/feedback-section";
import { getKomentarPublik } from "@/lib/komentar-actions";
import KabarFeedSection from "@/components/public/kabar-feed-section";

export const revalidate = 60;

export default async function HomePage() {
  let recentArticles: any[] = [];

  try {
    const [beritas, prestasis, rangers, laporans] = await Promise.all([
      prisma.beritaHMF.findMany({ orderBy: { createdAt: 'desc' }, take: 10 }).catch(() => []),
      prisma.prestasi.findMany({ orderBy: { createdAt: 'desc' }, take: 10 }).catch(() => []),
      prisma.rangersTalk.findMany({ orderBy: { createdAt: 'desc' }, take: 10 }).catch(() => []),
      prisma.laporanKeuangan.findMany({ orderBy: { createdAt: 'desc' }, take: 10 }).catch(() => []),
    ]);

    const combinedMedia: any[] = [
      ...beritas.map(b => ({ ...b, type: 'berita' as const, tipeDisplay: 'Berita HMF' })),
      ...prestasis.map(p => ({ ...p, type: 'prestasi' as const, tipeDisplay: 'Prestasi' })),
      ...rangers.map(r => ({ ...r, type: 'rangers-talk' as const, tipeDisplay: 'Rangers Talk' })),
      ...laporans.map(l => ({ ...l, type: 'laporan-keuangan' as const, tipeDisplay: 'Laporan Keuangan', narasi: l.narasi || `Periode: ${l.periode}` })),
    ].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    recentArticles = combinedMedia.slice(0, 4);
  } catch (err) {
    console.error("Gagal load media untuk homepage:", err);
  }

  // 1. Dapatkan Kabinet Aktif
  const kabinet = await getKabinetAktif();
  const namaKabinet = kabinet?.namaKabinet || "Niskala Cakra Murni";
  const periode = kabinet?.periode || "2026-2027";
  const logoUrl = kabinet?.logoUrl || "/niskala.png";
  const visi = kabinet?.visi || "Mewujudkan HMF FPMIPA UPI sebagai tempat pengembangan yang unggul, inovatif, strategis, dan efisien.";
  const misiRaw = kabinet?.misi || "";
  const misiList = misiRaw
    ? misiRaw.split('\n').map((m: string) => m.trim()).filter((m: string) => m.length > 0)
    : ["Mendorong Prestasi Mahasiswa di Bidang Akademik dan Non-Akademik.", "Mengembangkan kapasitas mahasiswa fisika yang adaptif and profesional.", "Mengembangkan SDM yang Kompeten, Adaptif, dan Berkarakter.", "Meningkatkan eksistensi HMF FPMIPA UPI di internal maupun di eksternal kampus.", "Mempererat Kekeluargaan dan kenyamanan di organisasi."];

  const formatDriveLink = (url?: string | null) => {
    if (!url) return url;
    const matchFile = url.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
    if (matchFile && matchFile[1]) return `https://lh3.googleusercontent.com/d/${matchFile[1]}`;
    const matchUc = url.match(/id=([a-zA-Z0-9_-]+)/);
    if (matchUc && matchUc[1] && url.includes('drive.google.com/uc')) return `https://lh3.googleusercontent.com/d/${matchUc[1]}`;
    return url;
  };

  // Foto Default Jika Kosong
  const kabinetAny = kabinet as any;
  const h1 = formatDriveLink(kabinetAny?.heroPhoto1) || "https://images.unsplash.com/photo-1523240795612-9a054b0db644?q=80&w=2000";
  const h2 = formatDriveLink(kabinetAny?.heroPhoto2) || "https://images.unsplash.com/photo-1517048676732-d65bc937f952?q=80&w=2000";
  const h3 = formatDriveLink(kabinetAny?.heroPhoto3) || "https://images.unsplash.com/photo-1552664730-d307ca884978?q=80&w=2000";
  const h4 = formatDriveLink(kabinetAny?.heroPhoto4) || "https://images.unsplash.com/photo-1521737604893-d14cc237f11d?q=80&w=2000";

  // Fetch data for new sections
  const [semuaPengurus, komentarPublik] = await Promise.all([
    prisma.pengurus.findMany({ select: { id: true, nama: true, jabatan: true, fotoUrl: true } }).catch(() => []),
    getKomentarPublik(),
  ]);

  // Temukan Penanggung Jawab Web jika diset di Kabinet
  const penanggungJawabWebId = kabinetAny?.penanggungJawabWebId;
  const webManager = penanggungJawabWebId 
    ? semuaPengurus.find(p => p.id === penanggungJawabWebId) 
    : null;

  // Duplicate array for infinite marquee effect
  const marqueePengurus = [...semuaPengurus, ...semuaPengurus, ...semuaPengurus];

  return (
    <div className="flex flex-col min-h-screen bg-white font-sans">

      {/* 1. Hero Section — Dark Minimal Style */}
      <section className="relative w-full min-h-screen flex items-center justify-center overflow-hidden bg-[#07090f]">
        {/* Background: bg-hero.png + dark overlay */}
        <div className="absolute inset-0 z-0">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src="/bg-hero.png" alt="" className="w-full h-full object-cover object-center" />
          {/* Dark overlay — sangat gelap agar teks tetap terbaca */}
          <div className="absolute inset-0 bg-[#07090f]/82"></div>
        </div>

        {/* Subtle grid */}
        <div className="absolute inset-0 z-[1] pointer-events-none">
          <div className="absolute inset-0 opacity-[0.04]" style={{backgroundImage: 'linear-gradient(#fff 1px, transparent 1px), linear-gradient(90deg, #fff 1px, transparent 1px)', backgroundSize: '60px 60px'}}></div>
        </div>

        <div className="container px-4 md:px-8 relative z-10 w-full max-w-3xl mx-auto flex flex-col items-center text-center pt-28 pb-16">

          {/* Headline 3 baris — sedikit lebih compact */}
          <h1 className="animate-in fade-in slide-in-from-bottom-6 duration-700 delay-100 font-sans leading-[1.05] tracking-tight mb-6">
            <span className="block text-4xl md:text-6xl lg:text-7xl font-black text-white">
              Himpunan
            </span>
            <span className="block text-4xl md:text-6xl lg:text-7xl font-black text-white/30">
              Mahasiswa Fisika
            </span>
            <span className="block text-base md:text-xl lg:text-2xl font-semibold text-white/20 mt-2 tracking-widest uppercase">
              FPMIPA UPI
            </span>
          </h1>

          {/* Subtext */}
          <p className="animate-in fade-in slide-in-from-bottom-8 duration-700 delay-200 text-gray-400 text-base md:text-lg max-w-xl leading-relaxed mb-10">
            Wadah pengembangan diri mahasiswa fisika yang inovatif, strategis, dan kolaboratif. Bersama membangun ilmu dan karakter.
          </p>

          {/* CTA Buttons */}
          <div className="animate-in fade-in slide-in-from-bottom-10 duration-700 delay-300 flex flex-wrap justify-center gap-3">
            <Link href="/kabinet">
              <button className="inline-flex items-center gap-2 px-7 py-3.5 rounded-full bg-white text-[#0B1F3A] font-bold text-sm hover:bg-gray-100 hover:-translate-y-0.5 transition-all duration-200 shadow-xl shadow-white/10 group">
                Kenali Kabinet <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
              </button>
            </Link>
            <Link href="/program-kerja">
              <button className="inline-flex items-center gap-2 px-7 py-3.5 rounded-full border border-white/15 bg-white/5 text-gray-200 font-bold text-sm hover:bg-white/10 hover:-translate-y-0.5 transition-all duration-200 backdrop-blur-md">
                Program Kerja
              </button>
            </Link>
          </div>

        </div>
      </section>

      {/* 2. Profil Kabinet Section — Full Glassmorphism & Centered Layout */}
      <section className="w-full py-16 bg-[#f8fafc] relative overflow-hidden">
        {/* Background Gradients & Textures for Glassmorphism Context */}
        <div className="absolute top-0 left-0 w-full h-full pointer-events-none z-0">
          {/* Dot Grid Pattern */}
          <div className="absolute inset-0 opacity-[0.04]" style={{backgroundImage: 'radial-gradient(#0B1F3A 2px, transparent 2px)', backgroundSize: '32px 32px'}}></div>
          
          {/* Colorful Ambient Blobs */}
          <div className="absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] bg-[#3b82f6]/15 rounded-full blur-[100px]"></div>
          <div className="absolute bottom-[-10%] right-[-10%] w-[40rem] h-[40rem] bg-[#c9a24d]/15 rounded-full blur-[100px]"></div>
          
          <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full h-full bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.4)_0%,rgba(248,250,252,0.9)_100%)]"></div>
        </div>

        <div className="container px-4 md:px-8 max-w-[1200px] mx-auto relative z-10">
          
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-6 items-center lg:items-stretch">
            
            {/* KIRI (3/12): Logo & Title */}
            <div className="lg:col-span-3 flex flex-col justify-center items-center lg:items-start text-center lg:text-left space-y-4">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={logoUrl} alt="Logo Kabinet" className="w-24 h-24 md:w-32 md:h-32 object-contain drop-shadow-2xl hover:scale-105 transition-transform" />
              
              <div>
                <h2 className="font-extrabold text-3xl lg:text-4xl text-[#0B1F3A] tracking-tighter leading-tight">
                  {namaKabinet}
                </h2>
                <p className="text-[#3b82f6] font-bold tracking-[0.15em] text-[13px] md:text-sm uppercase mt-2">
                  Kabinet {periode}
                </p>
              </div>

              <div className="pt-3 hidden lg:block">
                <Link href="/kabinet">
                  <button className="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#0B1F3A] text-white font-bold text-[13px] hover:bg-[#1a2f4c] hover:-translate-y-0.5 transition-all duration-200 shadow-lg shadow-[#0B1F3A]/20 group border border-transparent">
                    Formasi Kabinet <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
                  </button>
                </Link>
              </div>
            </div>

            {/* TENGAH (5/12): Visi & Misi Glass Card */}
            <div className="lg:col-span-5 flex flex-col justify-center">
              <div className="bg-white/40 backdrop-blur-2xl p-6 md:p-8 rounded-[1.5rem] shadow-[0_8px_30px_rgba(0,0,0,0.04)] border border-white/60 hover:shadow-2xl transition-all duration-500 relative overflow-hidden group h-full flex flex-col justify-center">
                <div className="absolute top-[-20%] right-[-20%] w-32 h-32 bg-[#3b82f6]/10 rounded-full blur-2xl group-hover:bg-[#3b82f6]/20 transition-colors pointer-events-none"></div>
                <div className="absolute bottom-[-20%] left-[-20%] w-32 h-32 bg-[#c9a24d]/10 rounded-full blur-2xl group-hover:bg-[#c9a24d]/20 transition-colors pointer-events-none"></div>
                
                <div className="relative z-10">
                  {/* Visi */}
                  <div className="mb-2">
                    <h3 className="font-extrabold text-[#0B1F3A] text-xl mb-2 tracking-tight">Visi</h3>
                    <p className="text-[#0B1F3A]/80 text-[14px] md:text-[15px] leading-relaxed font-medium">
                      {visi}
                    </p>
                  </div>

                  <div className="w-full border-t border-[#0B1F3A]/10 my-4"></div>

                  {/* Misi */}
                  <div>
                    <h3 className="font-extrabold text-[#0B1F3A] text-xl mb-3 tracking-tight">Misi</h3>
                    <ul className="text-[#0B1F3A]/80 text-[14px] md:text-[15px] leading-relaxed space-y-2">
                      {misiList.map((m: string, idx: number) => (
                        <li key={idx} className="flex gap-2">
                          <span className="text-[#3b82f6] font-bold">&bull;</span>
                          <span>{m}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>
            </div>

            {/* KANAN (4/12): 2 Landscape Photos */}
            <div className="lg:col-span-4 flex flex-col justify-center gap-4">
              <div className="relative w-full h-[180px] lg:h-[130px] xl:h-[170px] rounded-2xl bg-white/40 backdrop-blur-2xl border border-white/70 p-1.5 md:p-2 shadow-lg hover:shadow-2xl hover:-translate-y-1 transition-all duration-500 group">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={h1} alt="Hero 1" className="w-full h-full object-cover rounded-xl grayscale-[15%] group-hover:grayscale-0 transition-all duration-500" />
              </div>
              <div className="relative w-full h-[180px] lg:h-[130px] xl:h-[170px] rounded-2xl bg-white/40 backdrop-blur-2xl border border-white/70 p-1.5 md:p-2 shadow-lg hover:shadow-2xl hover:-translate-y-1 transition-all duration-500 group">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={h2} alt="Hero 2" className="w-full h-full object-cover rounded-xl grayscale-[15%] group-hover:grayscale-0 transition-all duration-500" />
              </div>
            </div>

            {/* Mobile/Tablet Only Button */}
            <div className="lg:hidden w-full flex justify-center mt-2">
              <Link href="/kabinet">
                <button className="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-[#0B1F3A] text-white font-bold text-[13px] hover:bg-[#1a2f4c] hover:-translate-y-0.5 transition-all duration-200 shadow-lg shadow-[#0B1F3A]/20 group border border-transparent">
                  Selami Formasi Kabinet <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
                </button>
              </Link>
            </div>

          </div>
        </div>
      </section>

      {/* Bagian Fitur & Navigasi telah dihapus */}

      {/* 4. Artikel Section (Kabar HMF Redesigned) */}
      <KabarFeedSection items={recentArticles} />

      {/* ===== SECTION MARQUEE PENGURUS HARIAN ===== */}
      <section className="w-full py-16 md:py-24 bg-[#f8fafc] relative overflow-hidden">
          {/* Background Style: Light Glassmorph */}
          <div className="absolute top-0 left-0 w-full h-full pointer-events-none z-0">
            <div className="absolute inset-0 opacity-[0.04]" style={{backgroundImage: 'radial-gradient(#0B1F3A 2px, transparent 2px)', backgroundSize: '32px 32px'}}></div>
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full h-full bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.4)_0%,rgba(248,250,252,0.9)_100%)]"></div>
          </div>
          
          <div className="container mx-auto px-4 mb-10 text-center relative z-10 flex flex-col items-center">
              <h2 className="text-3xl md:text-4xl font-extrabold text-[#0B1F3A] tracking-tighter">
                  Pengurus Harian HMF
              </h2>
          </div>

          <div className="relative flex overflow-x-hidden group z-10 w-full mask-edges-large">
              <div className="animate-marquee-cards flex whitespace-nowrap gap-4 md:gap-6 py-6 items-center w-max">
                  {marqueePengurus.map((p, idx) => (
                      <div key={idx} className="relative shrink-0 w-[140px] md:w-[160px] xl:w-[180px] aspect-[3/4] rounded-2xl overflow-hidden shadow-sm border border-gray-200 hover:shadow-lg hover:-translate-y-1 transition-all duration-500 bg-gray-50">
                          {/* Image Only (No Text Overlay) */}
                          {p.fotoUrl ? (
                              // eslint-disable-next-line @next/next/no-img-element
                              <img src={p.fotoUrl} alt={p.nama} title={p.nama} className="absolute inset-0 w-full h-full object-cover grayscale-[30%] hover:grayscale-0 transition-all duration-700" />
                          ) : (
                              <div className="absolute inset-0 flex flex-col items-center justify-center bg-gray-100">
                                  <Users className="w-8 h-8 text-gray-300" />
                              </div>
                          )}
                      </div>
                  ))}
              </div>
          </div>

          {/* Marquee Animations */}
          <style dangerouslySetInnerHTML={{__html: `
            @keyframes marqueeCards {
              0% { transform: translateX(0%); }
              100% { transform: translateX(-33.33%); }
            }
            .animate-marquee-cards {
              /* Kecepatan sangat diperlambat menjadi 80 detik */
              animation: marqueeCards 80s linear infinite;
            }
            .mask-edges-large {
              -webkit-mask-image: linear-gradient(to right, transparent, black 5%, black 95%, transparent);
              mask-image: linear-gradient(to right, transparent, black 5%, black 95%, transparent);
            }
          `}} />
      </section>

      {/* ===== SECTION BENTO MEDIA ===== */}
      <section data-theme="dark" className="w-full py-20 md:py-28 bg-[#07090f] relative overflow-hidden">
          {/* Ambient Backgrounds (Dark Glassmorphism) */}
          <div className="absolute inset-0 z-0 pointer-events-none">
              <div className="absolute inset-0 opacity-[0.03]" style={{backgroundImage: 'radial-gradient(#ffffff 2px, transparent 2px)', backgroundSize: '40px 40px'}}></div>
              <div className="absolute top-1/2 left-1/4 w-[40rem] h-[40rem] bg-indigo-600/10 rounded-full blur-[120px] -translate-y-1/2"></div>
              <div className="absolute bottom-[-10%] right-[-10%] w-[40rem] h-[40rem] bg-blue-600/10 rounded-full blur-[120px]"></div>
          </div>

          <div className="container mx-auto px-4 relative z-10 max-w-[1200px]">
              <div className="text-center max-w-2xl mx-auto mb-16">
                  <h2 className="text-3xl md:text-5xl font-extrabold text-white tracking-tight mb-4">
                      Eksplorasi Media
                  </h2>
                  <p className="text-gray-400 text-sm md:text-base leading-relaxed">
                      Jelajahi seluruh dokumentasi, program, dan publikasi resmi dari HMF FPMIPA UPI. Fitur-fitur andalan yang membantu Anda mengakses informasi lebih cepat dari sebelumnya.
                  </p>
              </div>
              
              {/* Bento Grid */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-6">
                    
                    {/* 1. Berita HMF (Span 2) */}
                    <Link href="/berita" className="md:col-span-2 bg-white/[0.03] border border-white/10 rounded-[1.5rem] p-6 md:p-8 hover:bg-white/[0.06] hover:border-white/20 hover:-translate-y-1 transition-all group flex flex-col justify-start relative text-left">
                        <div className="w-10 h-10 rounded-lg bg-blue-500/10 flex items-center justify-center mb-6">
                            <Newspaper className="w-5 h-5 text-blue-400" />
                        </div>
                        <h3 className="text-xl font-bold text-white mb-2 tracking-tight">Berita HMF</h3>
                        <p className="text-gray-400 text-sm max-w-sm">Berita terkini, liputan, dan press release seputar kegiatan yang telah sukses dilaksanakan.</p>
                    </Link>

                    {/* 2. Galeri (Span 1) */}
                    <Link href="/galeri" className="md:col-span-1 bg-white/[0.03] border border-white/10 rounded-[1.5rem] p-6 md:p-8 hover:bg-white/[0.06] hover:border-white/20 hover:-translate-y-1 transition-all group flex flex-col justify-start text-left">
                        <div className="w-10 h-10 rounded-lg bg-pink-500/10 flex items-center justify-center mb-6">
                            <ImageIcon className="w-5 h-5 text-pink-400" />
                        </div>
                        <h3 className="text-xl font-bold text-white mb-2 tracking-tight">Galeri Karya</h3>
                        <p className="text-gray-400 text-sm">Dokumentasi visual dan arsip kegiatan kebersamaan seluruh warga HMF.</p>
                    </Link>

                    {/* 3. Prestasi (Span 1) */}
                    <Link href="/prestasi" className="md:col-span-1 bg-white/[0.03] border border-white/10 rounded-[1.5rem] p-6 md:p-8 hover:bg-white/[0.06] hover:border-white/20 hover:-translate-y-1 transition-all group flex flex-col justify-start text-left">
                        <div className="w-10 h-10 rounded-lg bg-amber-500/10 flex items-center justify-center mb-6">
                            <Trophy className="w-5 h-5 text-amber-400" />
                        </div>
                        <h3 className="text-xl font-bold text-white mb-2 tracking-tight">Prestasi</h3>
                        <p className="text-gray-400 text-sm">Deretan prestasi gemilang mahasiswa fisika di kancah nasional maupun internasional.</p>
                    </Link>

                    {/* 4. Rangers Talk (Span 2) */}
                    <Link href="/rangers-talk" className="md:col-span-2 bg-white/[0.03] border border-white/10 rounded-[1.5rem] p-6 md:p-8 hover:bg-white/[0.06] hover:border-white/20 hover:-translate-y-1 transition-all group flex flex-col justify-start relative text-left">
                        <div className="w-10 h-10 rounded-lg bg-indigo-500/10 flex items-center justify-center mb-6">
                            <Mic2 className="w-5 h-5 text-indigo-400" />
                        </div>
                        <h3 className="text-xl font-bold text-white mb-2 tracking-tight">Rangers Talk</h3>
                        <p className="text-gray-400 text-sm max-w-md">Podcast dan obrolan asyik seputar dunia fisika, kampus, dan pengalaman inspiratif langsung dari ahlinya.</p>
                    </Link>

                    {/* 5. Laporan Keuangan (Span 2) */}
                    <Link href="/laporan-keuangan" className="md:col-span-2 bg-white/[0.03] border border-white/10 rounded-[1.5rem] p-6 md:p-8 hover:bg-white/[0.06] hover:border-white/20 hover:-translate-y-1 transition-all group flex flex-col justify-start relative text-left">
                        <div className="w-10 h-10 rounded-lg bg-emerald-500/10 flex items-center justify-center mb-6">
                            <FileText className="w-5 h-5 text-emerald-400" />
                        </div>
                        <h3 className="text-xl font-bold text-white mb-2 tracking-tight">Laporan Keuangan</h3>
                        <p className="text-gray-400 text-sm max-w-sm">Transparansi dan akuntabilitas keuangan organisasi kepada seluruh civitas akademika.</p>
                    </Link>

                    {/* 6. Awardee PH (Span 1) */}
                    <Link href="/awardee" className="md:col-span-1 bg-white/[0.03] border border-white/10 rounded-[1.5rem] p-6 md:p-8 hover:bg-white/[0.06] hover:border-white/20 hover:-translate-y-1 transition-all group flex flex-col justify-start text-left">
                        <div className="w-10 h-10 rounded-lg bg-cyan-500/10 flex items-center justify-center mb-6">
                            <Award className="w-5 h-5 text-cyan-400" />
                        </div>
                        <h3 className="text-xl font-bold text-white mb-2 tracking-tight">Awardee PH</h3>
                        <p className="text-gray-400 text-sm">Penghargaan untuk pengurus paling berdedikasi.</p>
                    </Link>

                </div>
          </div>
      </section>

      {/* ===== SECTION KOMENTAR TAMU ===== */}
      <KomentarSection komentarAwal={komentarPublik as any} />

      {/* ===== SECTION FEEDBACK & PENANGGUNG JAWAB ===== */}
      <FeedbackSection webManager={webManager} />

    </div>
  );
}
