'use client';

import Link from 'next/link';
import { IoMdCheckmarkCircleOutline } from 'react-icons/io';
import { FaCamera, FaStar, FaMapMarkerAlt, FaPhone, FaEnvelope } from "react-icons/fa";
import { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import Container from '../../../app/components/atoms/Container';
import Heading from '../../../app/components/atoms/Heading';
import UniversityOverview from '../../../app/components/organisms/UniversityOverview';
import UniversityPhotos from '../../../app/components/organisms/UniversityPhotos';
import UniversityReviews from '../../../app/components/organisms/UniversityReviews';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { Users, Calendar, Award, BookOpen, MapPin, ChevronRight, GraduationCap, Mail, Phone, Users as UsersIcon, Award as AwardIcon, BookOpen as BookOpenIcon, Calendar as CalendarIcon } from 'lucide-react';
import { useUserStore } from '../../../store/useUserStore';
import FreeConsultationModal from '../../../app/components/organisms/FreeConsultationModal';
import ApplyNowModal from '../../../app/components/clientcomponents/ApplyNowModal';

// Stat Card Component with exact comparison tool gradients
const StatCard = ({ icon: Icon, number, label, color = 'teal' }) => {
  const colorClasses = {
    teal: 'bg-gradient-to-r from-teal-500 to-blue-500',
    blue: 'bg-gradient-to-r from-blue-500 to-cyan-500',
    emerald: 'bg-gradient-to-r from-emerald-500 to-teal-500',
    amber: 'bg-gradient-to-r from-amber-500 to-orange-500'
  };

  return (
    <div className="text-center group">
      <div className={`inline-flex items-center justify-center w-16 h-16 ${colorClasses[color]} text-white rounded-2xl mb-4 shadow-lg group-hover:scale-105 transition-transform duration-300`}>
        <Icon className="w-7 h-7" />
      </div>
      <div className="text-2xl font-bold text-gray-900 mb-1">{number}</div>
      <div className="text-gray-600 text-sm">{label}</div>
    </div>
  );
};

const UniversityDetails = ({uniData, subjectsData}) => {
  const [activeTab, setActiveTab] = useState('overview');
  const [university, setUniversity] = useState(null);
  const [relatedUniversities, setRelatedUniversities] = useState([]);
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { user, isLoggedIn } = useUserStore();

  // Modal states
  const [isConsultationModalOpen, setIsConsultationModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  const router = useRouter();

  // Consultation modal functions
  const openConsultationModal = (item) => {
    setSelectedItem(item);
    setIsConsultationModalOpen(true);
  };

  const closeConsultationModal = () => {
    setIsConsultationModalOpen(false);
    setSelectedItem(null);
  };

  // Apply Now modal function
  const openApplyNowModal = (university) => {
    if (window.openApplyNowModal) {
      const universityData = {
        ...university,
        type: 'university',
        university: university.name,
        name: university.name
      };
      window.openApplyNowModal(universityData);
    }
  };

  // Keep your EXACT handleAdmissionRequest function as is
  const handleAdmissionRequest = async (item) => {
    if (!isLoggedIn) {
      const result = await Swal.fire({
        title: 'Login Required',
        html: `
          <div class="text-center">
            <div class="mb-4">
              <svg class="w-16 h-16 mx-auto text-[#0B6F78]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
              </svg>
            </div>
            <h3 class="text-xl font-bold text-gray-800 mb-2">Please Login to Continue</h3>
            <p class="text-gray-600 mb-4">You need to be logged in as a student to request admission information.</p>
            <div class="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] p-0.5 rounded-lg">
              <div class="bg-white rounded-lg p-4">
                <p class="text-sm text-gray-700 font-medium">You're requesting information for:</p>
                <p class="text-lg font-bold text-[#0B6F78] mt-1">${item.name || 'This University'}</p>
              </div>
            </div>
          </div>
        `,
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Login Now',
        cancelButtonText: 'Maybe Later',
        confirmButtonColor: '#0B6F78',
        cancelButtonColor: '#6b7280',
        background: 'linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%)',
        customClass: {
          popup: 'rounded-2xl shadow-2xl border border-gray-200',
          title: 'text-2xl font-bold text-gray-900',
        }
      });

      if (result.isConfirmed) {
        window.location.href = '/student-login?redirect='+item.name;
      }
      return;
    }

    if (!item.alternate_email && !item.email) {
      await Swal.fire({
        title: 'Email Not Found',
        html: `
          <div class="text-center">
            <div class="mb-3">
              <svg class="w-12 h-12 mx-auto text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.35 16.5c-.77.833.192 2.5 1.732 2.5z"/>
              </svg>
            </div>
            <p class="text-gray-700">Sorry, we couldn't find an email address for <strong class="text-[#0B6F78]">${item.name}</strong>.</p>
            <p class="text-sm text-gray-600 mt-2">Please contact support or try another university.</p>
          </div>
        `,
        icon: 'warning',
        confirmButtonColor: '#0B6F78',
        background: 'linear-gradient(135deg, #fefce8 0%, #fef9c3 100%)',
        customClass: {
          popup: 'rounded-2xl shadow-xl'
        }
      });
      return;
    }

    const { value: formValues } = await Swal.fire({
      title: 'Complete Your Request',
      html: `
        <div class="text-center">
          <!-- Header Section -->
          <div class="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-2xl p-6 text-white mb-6 relative overflow-hidden">
            <div class="absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -mr-12 -mt-12"></div>
            <div class="absolute bottom-0 left-0 w-16 h-16 bg-white/10 rounded-full -ml-8 -mb-8"></div>
            
            <div class="relative z-10">
              <svg class="w-16 h-16 mx-auto mb-3 drop-shadow-lg" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
              </svg>
              <h3 class="font-bold text-xl mb-1">${item.name || 'University'}</h3>
              <p class="text-white/90 text-sm">Ready to connect you with admission experts</p>
            </div>
          </div>

          <!-- Progress Indicator -->
          <div class="flex items-center justify-center mb-6">
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-[#0B6F78] text-white flex items-center justify-center text-sm font-bold">1</div>
              <div class="w-16 h-1 bg-[#0B6F78] mx-2"></div>
              <div class="w-8 h-8 rounded-full bg-[#0B6F78] text-white flex items-center justify-center text-sm font-bold">2</div>
              <div class="w-16 h-1 bg-gray-300 mx-2"></div>
              <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">3</div>
            </div>
          </div>

          <!-- Form Section -->
          <div class="space-y-4">
            <!-- Name Field -->
            <div class="group">
              <label class="flex items-center text-sm font-medium text-gray-700 mb-2">
                <svg class="w-4 h-4 mr-2 text-[#0B6F78]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                </svg>
                Full Name
              </label>
              <div class="relative">
                <input 
                  id="swal-name" 
                  type="text" 
                  class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all duration-200 group-hover:border-[#0B6F78]/50"
                  placeholder="Enter your full name"
                  required
                >
                <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                  <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                  </svg>
                </div>
              </div>
            </div>

            <!-- Email Field -->
            <div class="group">
              <label class="flex items-center text-sm font-medium text-gray-700 mb-2">
                <svg class="w-4 h-4 mr-2 text-[#0B6F78]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
                Email Address
              </label>
              <div class="relative">
                <input 
                  id="swal-email" 
                  type="email" 
                  class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all duration-200 group-hover:border-[#0B6F78]/50"
                  placeholder="your.email@example.com"
                  required
                >
                <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                  <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                  </svg>
                </div>
              </div>
            </div>

            <!-- Phone Field -->
            <div class="group">
              <label class="flex items-center text-sm font-medium text-gray-700 mb-2">
                <svg class="w-4 h-4 mr-2 text-[#0B6F78]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/>
                </svg>
                Phone Number
              </label>
              <div class="relative">
                <input 
                  id="swal-phone" 
                  type="tel" 
                  class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all duration-200 group-hover:border-[#0B6F78]/50"
                  placeholder="+1 (555) 123-4567"
                  required
                >
                <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                  <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/>
                  </svg>
                </div>
              </div>
            </div>
          </div>

          <!-- Helper Text -->
          <div class="mt-4 p-3 bg-blue-50 rounded-lg">
            <p class="text-xs text-blue-700 text-center">
              <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
              Your information will be shared only with the university's admission team
            </p>
          </div>
        </div>
      `,
      width: '500px',
      focusConfirm: false,
      showCancelButton: true,
      confirmButtonText: 'Continue to Review',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#0B6F78',
      cancelButtonColor: '#6b7280',
      background: 'linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%)',
      customClass: {
        popup: 'rounded-3xl shadow-2xl border border-gray-100',
        title: 'text-2xl font-bold text-gray-900 mb-2',
        confirmButton: 'px-6 py-3 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-200',
        cancelButton: 'px-6 py-3 rounded-xl font-semibold hover:bg-gray-100 transition-all duration-200'
      },
      preConfirm: () => {
        const name = document.getElementById('swal-name')?.value.trim();
        const email = document.getElementById('swal-email')?.value.trim();
        const phone = document.getElementById('swal-phone')?.value.trim();

        if (!name) {
          Swal.showValidationMessage('Please enter your full name to continue');
          return false;
        }
        if (!email) {
          Swal.showValidationMessage('Please enter your email address');
          return false;
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
          Swal.showValidationMessage('Please enter a valid email address');
          return false;
        }
        if (!phone) {
          Swal.showValidationMessage('Please enter your phone number');
          return false;
        }

        return { name, email, phone };
      }
    });

    if (!formValues) return;

    const userInfo = formValues;
    const universityName = item.name || item.university_name || 'University';
    const universityEmail = item.alternate_email || item.email;

    const result = await Swal.fire({
      title: 'Review Your Request',
      html: `
        <div class="text-center">
          <!-- University Card -->
          <div class="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-2xl p-6 text-white mb-6 relative overflow-hidden">
            <div class="absolute top-0 right-0 w-20 h-20 bg-white/10 rounded-full -mr-10 -mt-10"></div>
            <svg class="w-12 h-12 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>
            </svg>
            <h3 class="font-bold text-lg mb-1">${universityName}</h3>
            <p class="text-white/90 text-sm">Admission Information Request</p>
          </div>

          <!-- Progress Indicator -->
          <div class="flex items-center justify-center mb-6">
            <div class="flex items-center">
              <div class="w-8 h-8 rounded-full bg-[#0B6F78] text-white flex items-center justify-center text-sm font-bold">1</div>
              <div class="w-16 h-1 bg-[#0B6F78] mx-2"></div>
              <div class="w-8 h-8 rounded-full bg-[#0B6F78] text-white flex items-center justify-center text-sm font-bold">2</div>
              <div class="w-16 h-1 bg-[#0B6F78] mx-2"></div>
              <div class="w-8 h-8 rounded-full bg-[#0B6F78] text-white flex items-center justify-center text-sm font-bold">3</div>
            </div>
          </div>

          <!-- User Information Card -->
          <div class="bg-white rounded-2xl p-6 border border-gray-200 text-left mb-4 shadow-sm">
            <h4 class="font-bold text-gray-800 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-[#0B6F78]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
              </svg>
              Your Information
            </h4>
            <div class="space-y-3">
              <div class="flex items-center justify-between py-2 border-b border-gray-100">
                <span class="text-gray-600 font-medium">Name:</span>
                <span class="text-gray-800 font-semibold">${userInfo.name}</span>
              </div>
              <div class="flex items-center justify-between py-2 border-b border-gray-100">
                <span class="text-gray-600 font-medium">Email:</span>
                <span class="text-gray-800 font-semibold">${userInfo.email}</span>
              </div>
              <div class="flex items-center justify-between py-2">
                <span class="text-gray-600 font-medium">Phone:</span>
                <span class="text-gray-800 font-semibold">${userInfo.phone}</span>
              </div>
            </div>
          </div>

          <p class="text-gray-600 text-sm">Ready to connect you with ${universityName}'s admission team</p>
        </div>
      `,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Send Request Now',
      cancelButtonText: 'Edit Information',
      confirmButtonColor: '#0B6F78',
      cancelButtonColor: '#6b7280',
      background: 'linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%)',
      customClass: {
        popup: 'rounded-3xl shadow-2xl border border-gray-100',
        title: 'text-2xl font-bold text-gray-900',
        confirmButton: 'px-6 py-3 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-200',
        cancelButton: 'px-6 py-3 rounded-xl font-semibold hover:bg-gray-100 transition-all duration-200'
      }
    });

    if (result.dismiss === Swal.DismissReason.cancel) {
      return handleAdmissionRequest(item);
    }

    if (result.isConfirmed) {
      Swal.fire({
        title: 'Sending Your Request...',
        html: `
          <div class="text-center py-4">
            <div class="relative">
              <div class="animate-spin rounded-full h-16 w-16 border-4 border-[#0B6F78] border-t-transparent mx-auto mb-4"></div>
              <div class="absolute inset-0 flex items-center justify-center">
                <svg class="w-8 h-8 text-[#0B6F78] animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                </svg>
              </div>
            </div>
            <h3 class="text-lg font-semibold text-white mb-2">Connecting to ${universityName}</h3>
            <p class="text-white/90 text-sm">We're sending your information securely</p>
            <div class="mt-4 w-full bg-white/20 rounded-full h-1">
              <div class="bg-white h-1 rounded-full animate-pulse"></div>
            </div>
          </div>
        `,
        allowOutsideClick: false,
        showConfirmButton: false,
        background: 'linear-gradient(135deg, #0B6F78, #0a306b)',
        color: 'white',
        customClass: {
          popup: 'rounded-3xl'
        }
      });

      try {
        const res = await fetch('/api/frontend/request-info', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            item: {
              ...item,
              university_email: universityEmail,
              university_name: universityName
            }, 
            userInfo 
          }),
        });

        const data = await res.json();

        if (res.status === 401) {
          Swal.fire({
            title: 'Session Expired',
            html: `
              <div class="text-center">
                <p class="text-gray-700">Your session has expired. Please login again.</p>
              </div>
            `,
            icon: 'warning',
            confirmButtonColor: '#0B6F78',
            confirmButtonText: 'Login Again'
          }).then(() => {
            window.location.href = '/student-login';
          });
          return;
        }

        if (data.success) {
          Swal.fire({
            title: 'Request Sent Successfully! 🎉',
            html: `
              <div class="text-center">
                <div class="bg-gradient-to-r from-green-400 to-green-600 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4 shadow-lg">
                  <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                  </svg>
                </div>
                <h3 class="text-xl font-bold text-gray-900 mb-2">Congratulations!</h3>
                <p class="text-gray-600 mb-4">
                  Your request has been sent to <strong class="text-[#0B6F78]">${universityName}</strong>
                </p>
                <div class="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-2xl p-4 text-white">
                  <p class="text-sm">
                    <strong>Expected Response:</strong> 24-48 hours<br>
                  </p>
                </div>
              </div>
            `,
            icon: 'success',
            confirmButtonColor: '#0B6F78',
            confirmButtonText: 'Great! Thank You',
            background: 'linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%)',
            customClass: {
              popup: 'rounded-3xl shadow-2xl border border-green-200'
            }
          });
        } else {
          Swal.fire({
            title: 'Error',
            html: `
              <div class="text-center">
                <div class="bg-gradient-to-r from-red-400 to-red-600 rounded-full w-16 h-16 flex items-center justify-center mx-auto mb-4">
                  <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                  </svg>
                </div>
                <p class="text-gray-700">${data.error || 'Failed to send request. Please try again.'}</p>
              </div>
            `,
            icon: 'error',
            confirmButtonColor: '#0B6F78',
            background: 'linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%)'
          });
        }
      } catch (err) {
        Swal.fire({
          title: 'Connection Error',
          html: `
            <div class="text-center">
              <p class="text-gray-700">Something went wrong while sending the request. Please check your connection and try again.</p>
            </div>
          `,
          icon: 'error',
          confirmButtonColor: '#0B6F78',
        });
      }
    }
  };

  useEffect(() => {
    try {
      setLoading(true);

      if(!uniData.success){
        throw new Error(uniData.message);
      }

      if(uniData.success){
        setUniversity(uniData?.data);
        setRelatedUniversities(uniData?.realtedUniversities || []);
        setCourses(uniData?.courses || []);
      } else {
        setError(uniData.message);
        router.push('/404');
      }

    } catch (error){
      setError(error.message);
      setLoading(false)
    } finally{
      setLoading(false);
    }
  }, [uniData]);

  // Tabs with improved UI
  const tabs = [
    { id: 'overview', label: 'University Overview', icon: <IoMdCheckmarkCircleOutline className="w-5 h-5" /> },
    { id: 'photos', label: 'Campus Photos', icon: <FaCamera className="w-5 h-5" /> },
    { id: 'reviews', label: 'Student Reviews', icon: <FaStar className="w-5 h-5" /> }
  ];

  const renderContent = () => {
    if (!university) return null;

    switch (activeTab) {
      case 'overview':
        return <UniversityOverview university={university} courses={courses} subjectsData={subjectsData} relatedUniversities={relatedUniversities} />;
      case 'photos':
        return <UniversityPhotos university={university} />;
      case 'reviews':
        return <UniversityReviews university={university} />;
      default:
        return <UniversityOverview university={university} relatedUniversities={relatedUniversities} />;
    }
  };

  const formatCurrency = (amount, currency, type) => {
    if (amount === null || amount === undefined) return 'N/A';
    if (type === '$') {
      return `$${parseFloat(amount).toLocaleString()}`;
    } else if(type === 'PKR'){
      return `PKR ${parseFloat(amount).toLocaleString()}`;
    } else {
      return `${currency || 'PKR'} ${parseFloat(amount).toLocaleString()}`;
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-[#0B6F78] mx-auto mb-4"></div>
          <p className="text-gray-600">Loading university details...</p>
        </div>
      </div>
    );
  }

  if (error || !university) {
    return (
      <Container>
        <div className="min-h-screen flex flex-col items-center justify-center py-20">
          <div className="text-6xl mb-4">🏫</div>
          <h1 className="text-2xl font-bold mb-4 text-gray-800">University not found</h1>
          <p className="text-gray-600 mb-6 text-center max-w-md">{error}</p>
          <Link href="/">
            <button 
              className="px-6 py-3 bg-[#0B6F78] text-white rounded-xl font-semibold hover:bg-[#0a5d65] transition-colors"
            >
              Go Back Home
            </button>
          </Link>
        </div>
      </Container>
    );
  }

  // University stats
  const universityStats = [
    { icon: UsersIcon, label: 'Students', value: university.total_students ? `${parseInt(university.total_students).toLocaleString()}+` : '10,000+', color: 'teal' },
    { icon: BookOpenIcon, label: 'Programs', value: university.courses_count || courses.length || '0', color: 'blue' },
    { icon: AwardIcon, label: 'Ranking', value: university.ranking ? `#${university.ranking}` : 'Top 100', color: 'amber' },
    { icon: CalendarIcon, label: 'Founded', value: university.founded_in || '1950', color: 'emerald' }
  ];

  return (
    <>

      <div className="relative min-h-screen bg-gradient-to-b from-gray-50 to-white">
        {/* Hero Section */}
        <div className="relative bg-gradient-to-r from-teal-50/50 to-blue-50/50">
          {/* Animated Background Elements - Fixed with pointer-events-none */}
          <div className="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none">
            {[...Array(20)].map((_, i) => (
              <div
                key={i}
                className="absolute rounded-full bg-gradient-to-r from-teal-200/20 to-blue-200/20 animate-float pointer-events-none"
                style={{
                  width: Math.random() * 100 + 50,
                  height: Math.random() * 100 + 50,
                  top: `${Math.random() * 100}%`,
                  left: `${Math.random() * 100}%`,
                  animationDelay: `${Math.random() * 5}s`,
                  animationDuration: `${Math.random() * 10 + 10}s`
                }}
              />
            ))}
          </div>
          
          <Container>
            <div className="py-16 md:py-20 relative z-10">
              {/* University Logo */}
              <div className="flex justify-center mb-10">
                <div className="relative">
                  <div className="absolute inset-0 bg-gradient-to-r from-teal-600 to-blue-500 rounded-3xl transform rotate-3 opacity-10"></div>
                  <div className="relative bg-white p-6 rounded-3xl shadow-xl border border-gray-100">
                    <div className="w-28 h-28 md:w-32 md:h-32 relative">
                      <Image
                        src={
                          university.logo
                            ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${university.logo.replace(/^\/+/, "")}`
                            : "/assets/default-university.webp"
                        }
                        alt={`${university.name} logo`}
                        fill
                        className="object-contain"
                      />
                    </div>
                  </div>
                </div>
              </div>

              {/* University Title with Gradient */}
              <div className="text-center mb-8 relative z-10">
                <h1 className="text-4xl md:text-5xl font-bold mb-4 bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  {university.name}
                </h1>
                
                <div className="flex items-center justify-center gap-2 text-gray-600 mb-8">
                  <MapPin className="w-5 h-5 text-teal-600" />
                  <span className="text-lg">
                    {[university.city, university.country].filter(Boolean).join(', ')}
                  </span>
                </div>
              </div>

              {/* University Stats */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-12 max-w-2xl mx-auto relative z-10">
                {universityStats.map((stat, index) => (
                  <StatCard
                    key={index}
                    icon={stat.icon}
                    number={stat.value}
                    label={stat.label}
                    color={stat.color}
                  />
                ))}
              </div>

              {/* Hero Section Buttons - Fixed with relative positioning */}
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center max-w-md mx-auto relative z-20">
                <button 
                  onClick={() => handleAdmissionRequest(university)}
                  className="group w-full sm:w-auto px-8 py-4 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-xl transition-all duration-300 transform hover:scale-105 flex items-center justify-center gap-3 shadow-lg relative z-10 cursor-pointer active:scale-95"
                >
                  <Mail className="w-5 h-5" />
                  <span>Request Information</span>
                  <ChevronRight className="w-5 h-5 transition-transform group-hover:translate-x-2" />
                </button>
                
                <button 
                  onClick={() => openConsultationModal(university)}
                  className="w-full sm:w-auto px-8 py-4 border-2 border-gray-300 text-gray-700 font-semibold rounded-xl hover:border-teal-600 hover:text-teal-600 hover:bg-teal-50 transition-all duration-300 transform hover:scale-105 flex items-center justify-center gap-3 relative z-10 cursor-pointer active:scale-95"
                >
                  <Phone className="w-5 h-5" />
                  <span>Free Consultation</span>
                </button>
              </div>
            </div>
          </Container>
        </div>

        {/* Improved Tabs Section */}
        <div className="sticky top-14 bg-white/95 backdrop-blur-lg border-b border-gray-200 shadow-sm z-10">
          <Container>
            <div className="flex overflow-x-auto">
              {tabs.map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex-1 min-w-[140px] py-5 px-4 flex flex-col items-center justify-center transition-all duration-300 relative group ${
                    activeTab === tab.id
                      ? 'text-teal-600'
                      : 'text-gray-600 hover:text-teal-600'
                  }`}
                >
                  {/* Active Indicator */}
                  {activeTab === tab.id && (
                    <div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-teal-600 to-blue-500 rounded-t-full"></div>
                  )}
                  
                  <div className={`mb-2 ${activeTab === tab.id ? 'text-teal-600' : 'text-gray-400 group-hover:text-teal-400'}`}>
                    {tab.icon}
                  </div>
                  
                  <span className="text-sm font-semibold whitespace-nowrap">{tab.label}</span>
                </button>
              ))}
            </div>
          </Container>
        </div>

        {/* Main Content */}
        <div className="py-12">
          <Container>
            <div className="max-w-7xl mx-auto">
              {renderContent()}
            </div>
          </Container>
        </div>

        {/* Quick Contact Bar */}
        <div className="py-8 bg-white border-t border-gray-200">
          <Container>
            <div className="bg-gradient-to-r from-teal-50/50 to-blue-50/50 rounded-2xl p-8">
              <div className="flex flex-col md:flex-row justify-between items-center gap-6">
                <div>
                  <h3 className="text-xl font-bold text-gray-900 mb-2">
                    Interested in {university.name}?
                  </h3>
                  <p className="text-gray-600">Get personalized guidance from our education consultants</p>
                </div>
                <div className="flex gap-3">
                  <button 
                    onClick={() => handleAdmissionRequest(university)}
                    className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-xl font-semibold hover:shadow-xl transition-all duration-300 transform hover:scale-105 flex items-center gap-2 shadow-lg"
                  >
                    <Mail className="w-4 h-4" />
                    Request Info
                  </button>
                  <button 
                    onClick={() => openConsultationModal(university)}
                    className="px-6 py-3 border border-teal-600 text-teal-600 rounded-xl font-semibold hover:bg-teal-600 hover:text-white transition-all duration-300 transform hover:scale-105 flex items-center gap-2"
                  >
                    <Phone className="w-4 h-4" />
                    Free Consultation
                  </button>
                </div>
              </div>
            </div>
          </Container>
        </div>

        {/* Sticky Apply Now Section */}
        <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-20">
          <Container>
            <div className="py-4">
              <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-gradient-to-r from-teal-600 to-blue-500 rounded-lg flex items-center justify-center shadow-lg">
                    <GraduationCap className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">{university.name}</p>
                    <p className="text-sm text-gray-600 flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      {[university.city, university.country].filter(Boolean).join(', ')}
                    </p>
                  </div>
                </div>
                
                <div className="flex gap-3 w-full sm:w-auto">
                  <button 
                    onClick={() => openConsultationModal(university)}
                    className="flex-1 sm:flex-none px-6 py-3 border border-teal-600 text-teal-600 rounded-xl hover:bg-teal-600 hover:text-white transition-colors font-semibold text-sm"
                  >
                    Consultation
                  </button>
                  <button 
                    onClick={() => openApplyNowModal(university)}
                    className="flex-1 sm:flex-none px-8 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-xl hover:shadow-xl transition-all font-semibold text-sm flex items-center justify-center gap-2 shadow-lg"
                  >
                    Apply Now
                  </button>
                </div>
              </div>
            </div>
          </Container>
        </div>

        {/* Consultation Modal */}
        <FreeConsultationModal
          isOpen={isConsultationModalOpen}
          onClose={closeConsultationModal}
          title="University Consultation"
          description={`Get expert guidance about ${selectedItem?.name} - completely free!`}
        />

        {/* Apply Now Modal */}
        <ApplyNowModal />
      </div>

      <style jsx global>{`
        @keyframes float {
          0%, 100% {
            transform: translateY(0) rotate(0deg);
          }
          50% {
            transform: translateY(-20px) rotate(180deg);
          }
        }
        
        .animate-float {
          animation: float 20s infinite linear;
        }
      `}</style>
    </>
  );
};

export default UniversityDetails;