// src/Components/LandingPage/TuitionFee.jsx (Rombakan Total Pil)

import { useState, useEffect, useMemo } from 'react';
// ⭐ Penting: Menggunakan motion pada button tab
import { motion, AnimatePresence } from 'framer-motion'; 
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faShieldHalved, faFileInvoiceDollar, faWallet, faHeadset, faTag } from '@fortawesome/free-solid-svg-icons';
import { faWhatsapp } from '@fortawesome/free-brands-svg-icons';

const containerVariants = { hidden: {}, visible: { transition: { staggerChildren: 0.1 } } };
const itemVariants = { hidden: { opacity: 0, y: 30 }, visible: { opacity: 1, y: 0, transition: { type: 'spring', stiffness: 100 } } };
const whatsappButtonVariants = {
    initial: { scale: 1 },
    animate: { scale: [1, 1.05, 1], transition: { duration: 1.5, ease: "easeInOut", repeat: Infinity, delay: 1 } },
    hover: { scale: 1.05, transition: { duration: 0.3 } }
};

export default function TuitionFee({ campus }) {
    const theme = campus?.theme || { primary: 'bg-blue-600', textColor: 'text-blue-600', shadowColor: 'hover:shadow-blue-200/50', borderColor: 'border-blue-500' };
    
    const tuitionData = campus?.tuitionData || {};
    const currentCampus = campus || { name: "Kampus Kami", whatsappNumber: '6281234567890' };
    
    const availableTabs = useMemo(() => Object.keys(tuitionData), [tuitionData]);
    
    const [activeTab, setActiveTab] = useState(availableTabs[0]);
    
    useEffect(() => {
        if (availableTabs.length > 0 && !availableTabs.includes(activeTab)) {
            setActiveTab(availableTabs[0]);
        }
    }, [availableTabs, activeTab]);

    const currentProgramData = tuitionData[activeTab]?.tableData || [];
    const currentRegistrationFees = tuitionData[activeTab]?.registrationFees || [];

    const uniqueRegistrationFees = Array.from(new Map(currentRegistrationFees.map(fee => [fee.type, fee])).values());

    if (availableTabs.length === 0) {
        return (
            <section className="bg-slate-50 py-20 sm:py-24 text-center">
                <h2 className="text-3xl font-extrabold text-gray-900">Biaya Pendidikan</h2>
                <p className="mt-4 text-gray-500">Saat ini belum ada data biaya pendidikan yang tersedia untuk ditampilkan.</p>
            </section>
        );
    }

    // ⭐ KODE PERHITUNGAN tabWidthPercentage dan tabOffset DIHAPUS karena tidak diperlukan lagi

    return (
        <section className="bg-slate-50 py-20 sm:py-24">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                {/* Judul & Kotak Jaminan */}
                <motion.div initial={{ opacity: 0, y: -30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ duration: 0.5 }} className="text-center">
                    <h2 className="text-3xl font-extrabold text-gray-900 sm:text-5xl tracking-tight">Biaya Pendidikan Terjangkau</h2>
                </motion.div>

                <motion.div initial={{ opacity: 0, scale: 0.95 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }} transition={{ duration: 0.5, delay: 0.2 }}
                    className="mt-8 max-w-3xl mx-auto bg-white border-2 border-green-200 rounded-xl shadow-lg p-6 flex items-start space-x-5">
                    <div className="flex-shrink-0"><FontAwesomeIcon icon={faShieldHalved} className="text-4xl text-green-500" /></div>
                    <div>
                        <h3 className="text-lg font-bold text-gray-900">Jaminan Biaya Kuliah Tetap</h3>
                        <p className="mt-1 text-gray-600">
                            Nikmati ketenangan selama masa studi. Biaya kuliah dapat diangsur bulanan dengan nominal <span className="mx-1.5 inline-block bg-green-600 text-white font-bold px-2 py-0.5 rounded-md text-sm tracking-wider">FLAT</span> hingga Anda wisuda.
                        </p>
                    </div>
                </motion.div>

                {/* Info Biaya Pendaftaran (Pisahkan berdasarkan tipe) */}
                <motion.div initial={{ opacity: 0, scale: 0.9 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }} transition={{ duration: 0.5, delay: 0.2 }} className="mt-12 grid grid-cols-1 md:grid-cols-2 gap-8 max-w-4xl mx-auto">
                    {/* Kotak Biaya Pendaftaran */}
                    {uniqueRegistrationFees.length > 0 ? (
                        uniqueRegistrationFees.map((fee, index) => (
                            <div key={index} className={`relative bg-gradient-to-br ${fee.type === 'S2' ? 'from-rose-500 to-red-600' : 'from-sky-500 to-blue-600'} text-white p-8 rounded-xl shadow-lg transform hover:scale-105 transition-transform duration-300`}>
                                <FontAwesomeIcon icon={faFileInvoiceDollar} className="text-4xl text-white/50 absolute top-4 right-4" />
                                <motion.p key={fee.type} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} transition={{ duration: 0.2 }} className="text-lg font-medium">
                                    Biaya Pendaftaran {fee.type}
                                </motion.p>
                                <p className="text-4xl font-bold mt-2">
                                    Rp {fee.fee},-
                                </p>
                            </div>
                        ))
                    ) : (
                        <div className="relative bg-gradient-to-br from-rose-500 to-red-600 text-white p-8 rounded-xl shadow-lg transform hover:scale-105 transition-transform duration-300">
                            <FontAwesomeIcon icon={faFileInvoiceDollar} className="text-4xl text-white/50 absolute top-4 right-4" />
                            <h3 className="text-xl font-bold">Biaya Pendaftaran</h3>
                            <p className="text-4xl font-bold mt-2">Tidak Tersedia</p>
                        </div>
                    )}
                    
                    {/* Kotak Biaya Awal */}
                    <div className="relative bg-gradient-to-br from-sky-500 to-blue-600 text-white p-8 rounded-xl shadow-lg transform hover:scale-105 transition-transform duration-300">
                        <FontAwesomeIcon icon={faWallet} className="text-4xl text-white/50 absolute top-4 right-4" />
                        <h3 className="text-xl font-bold">Biaya Awal</h3>
                        <p className="text-sm mt-2">Termasuk Angsuran ke-1, Uang Masuk, dan Kartu Tanda Mahasiswa (KTM).</p>
                    </div>
                </motion.div>

                {/* Tab & Kartu Biaya */}
                <div className="mt-16 max-w-5xl mx-auto">
                    {/* Navigasi Tab */}
                    {/* Menghapus relative dan p-1 pada container dan menerapkan background default */}
                    <div className={`flex rounded-full max-w-xl mx-auto ${availableTabs.length >= 1 ? 'justify-center bg-slate-200' : 'justify-center'} p-1`}>
                        {availableTabs.map((tab) => {
                            const isActive = activeTab === tab;
                            return (
                                <motion.button // ⭐ Menggunakan motion.button
                                    key={tab}
                                    onClick={() => setActiveTab(tab)}
                                    // ⭐ layout ditambahkan untuk transisi halus
                                    layout 
                                    className={`flex-1 rounded-full py-2 text-sm font-medium transition-colors duration-300 focus:outline-none 
                                            ${isActive 
                                                // ⭐ Tombol aktif kini membawa styling pil merah
                                                ? `text-white shadow-md ${theme.primary}` 
                                                // ⭐ Tombol tidak aktif berwarna abu-abu/slate
                                                : 'text-slate-700 hover:text-slate-900 bg-transparent'}`
                                            }
                                    // Memberikan sedikit scale saat hover untuk efek interaktif
                                    whileHover={{ scale: 1.05 }} 
                                    whileTap={{ scale: 0.95 }}
                                >
                                    <span className="flex items-center justify-center text-center">
                                        {tab}
                                    </span>
                                </motion.button>
                            );
                        })}
                        
                        {/* ⭐ Active Tab Pill (Layout Indicator) DIHAPUS di sini */}
                        {/* {availableTabs.length >= 1 && (
                            <motion.div ... /> 
                        )} */}
                    </div>

                    {/* Konten Kartu Biaya */}
                    <AnimatePresence mode="wait">
                        <motion.div key={activeTab} variants={containerVariants} initial="hidden" animate="visible" exit="hidden"
                            className="mt-12 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
                            {currentProgramData.map((item) => (
                                <motion.div key={item.major} variants={itemVariants} whileHover={{ y: -8, scale: 1.03 }} transition={{ type: 'spring', stiffness: 300 }}
                                    className={`relative group bg-white rounded-2xl shadow-lg hover:shadow-2xl ${theme.shadowColor} transition-shadow duration-300 overflow-hidden`}>
                                    
                                    {/* Pita Sudut - Menggunakan activeTab sebagai label */}
                                    <div className="absolute top-0 right-0 transform translate-x-1/4 -translate-y-1/4">
                                        <div className={`w-48 h-10 ${theme.primary} flex items-center justify-center text-white font-bold uppercase text-xs sm:text-sm transform rotate-45`}>
                                            {activeTab}
                                        </div>
                                    </div>
                                    
                                    <div className="p-8 text-center">
                                        <h3 className="text-xl font-extrabold text-slate-800 h-16 flex items-center justify-center">{item.major}</h3>
                                        
                                        <p className="mt-4 text-sm text-slate-500">Angsuran per Bulan</p>
                                        
                                        {/* Promo */}
                                        <div className="mt-2 flex items-center justify-center gap-3">
                                            {item.oldMonthlyFee !== item.newMonthlyFee && (
                                                <p className="text-lg text-gray-400 line-through">Rp {item.oldMonthlyFee}</p>
                                            )}
                                            <FontAwesomeIcon icon={faTag} className={theme.textColor} />
                                        </div>
                                        
                                        <p className={`text-4xl font-bold ${theme.textColor} mt-1`}>
                                            Rp {item.newMonthlyFee}
                                        </p>
                                        
                                        <p className="mt-6 text-sm text-gray-500 border-t border-gray-200 pt-4">
                                            Biaya Awal <span className="font-bold text-gray-800 text-base">Rp {item.initialFee}</span>
                                        </p>
                                        
                                        {/* Keterangan Biaya Pendaftaran per Jurusan (Jika diperlukan) */}
                                        {item.singleRegistrationFee > 0 && (
                                             <p className="text-xs text-gray-400 mt-1">
                                                (Biaya Pendaftaran: **Rp {item.singleRegistrationFee.toLocaleString('id-ID')}**)
                                             </p>
                                        )}
                                        
                                    </div>
                                </motion.div>
                            ))}
                        </motion.div>
                    </AnimatePresence>
                </div>

                {/* CTA (Call to Action) */}
                <motion.div initial={{ opacity: 0, y: 50 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, amount: 0.5 }} transition={{ duration: 0.6, ease: "easeOut" }}
                    className="mt-24 max-w-xl lg:max-w-2xl mx-auto">
                    <motion.div 
                        className={`relative bg-white rounded-3xl shadow-2xl border-b-4 ${theme.borderColor} overflow-hidden p-8 md:p-10 text-center transform hover:scale-105 transition-all duration-500 ease-in-out`}
                        whileHover={{ y: -5 }}>
                        <FontAwesomeIcon icon={faHeadset} className={`text-5xl mb-4 animate-bounce ${theme.textColor}`} />
                        <h3 className="text-2xl sm:text-3xl font-extrabold text-gray-900 leading-tight">Punya Pertanyaan Seputar Pendaftaran?</h3>
                        <p className="mt-3 text-lg text-gray-600 max-w-md mx-auto">
                            Tim kami siap membantu Anda. Hubungi kami via WhatsApp untuk respon cepat dan informasi lengkap tentang <span className={`font-semibold ${theme.textColor}`}>{currentCampus.name}</span>.
                        </p>
                        <motion.a href={`https://wa.me/${currentCampus.whatsappNumber}`} target="_blank" rel="noopener noreferrer"
                            className="mt-8 inline-flex items-center justify-center bg-gradient-to-r from-green-500 to-green-600 text-white font-bold py-3.5 px-8 rounded-full shadow-lg hover:shadow-xl transform active:scale-95 transition-all duration-300 ease-in-out focus:outline-none focus:ring-4 focus:ring-green-300"
                            variants={whatsappButtonVariants} initial="initial" animate="animate" whileHover="hover">
                            <FontAwesomeIcon icon={faWhatsapp} className="text-2xl mr-3" />
                            <span>Tanya via WhatsApp</span>
                        </motion.a>
                    </motion.div>
                </motion.div>
            </div>
        </section>
    );
}