// app/components/eligibility/AIEligibilityCalculator.jsx
'use client';
import "../../components/componentscss/texteditor.css"

import React, { useState, useEffect, useMemo } from 'react';
import { 
  GraduationCap, 
  MapPin, 
  DollarSign, 
  Award, 
  Clock,
  Globe,
  BookOpen,
  ArrowRight,
  Sparkles,
  CheckCircle,
  User,
  Target,
  School,
  Flag,
  ChevronLeft,
  ChevronRight,
  Lightbulb,
  X,
  Brain,
  ChevronDown,
  ChevronUp,
  PieChart,
  AlertCircle,
  Loader2,
  Send,
  Zap,
  Trophy,
  Shield,
  RefreshCw,
  Mail,
  Phone,
  Save
} from 'lucide-react';
import Link from 'next/link';
import { useWishlist } from '../../context/WishlistContext';
import { FaHeart, FaRegHeart } from 'react-icons/fa';
import { eligibilityStorage } from '../../../lib/eligibilityStorage';
import Swal from 'sweetalert2';
import FAQSection from "../../components/FAQSection";
import TextDisplay from "../../components/clientcomponents/TextDisplay";

const faqs = [
  // ... (your existing FAQ array remains the same)
];

// Modern Card Component
const ModernCard = ({ children, className = '', hover = true }) => (
  <div className={`bg-white rounded-3xl border border-gray-100 shadow-sm hover:shadow-lg transition-all duration-300 ${hover ? 'hover:border-teal-200' : ''} ${className}`}>
    {children}
  </div>
);

// Badge Component
const Badge = ({ children, color = 'teal', icon: Icon, className = '' }) => {
  const colorClasses = {
    teal: 'bg-teal-100 text-teal-700 border-teal-200',
    blue: 'bg-blue-100 text-blue-700 border-blue-200',
    emerald: 'bg-emerald-100 text-emerald-700 border-emerald-200',
    amber: 'bg-amber-100 text-amber-700 border-amber-200',
    purple: 'bg-purple-100 text-purple-700 border-purple-200',
    gray: 'bg-gray-100 text-gray-700 border-gray-200',
    red: 'bg-red-100 text-red-700 border-red-200'
  };

  return (
    <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium border ${colorClasses[color]} ${className}`}>
      {Icon && <Icon className="w-3.5 h-3.5" />}
      {children}
    </span>
  );
};

// Feature Card Component
const FeatureCard = ({ icon: Icon, title, description, color = 'from-teal-500 to-blue-500' }) => (
  <div className="group relative p-8 bg-linear-to-br from-gray-50 to-white rounded-3xl border border-gray-100 shadow-sm hover:shadow-2xl hover:scale-105 transition-all duration-300 hover:border-teal-200">
    <div className={`absolute inset-0 bg-linear-to-r ${color} opacity-0 group-hover:opacity-5 rounded-3xl transition-opacity duration-300`}></div>
    <div className={`inline-flex p-4 rounded-2xl bg-linear-to-r ${color} text-white mb-6`}>
      <Icon className="w-6 h-6" />
    </div>
    <h3 className="text-xl font-bold text-gray-900 mb-3">{title}</h3>
    <p className="text-gray-600">{description}</p>
    <div className="absolute bottom-8 right-8 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
      <ArrowRight className="text-gray-400" />
    </div>
  </div>
);

// Progress Bar Component
const ProgressBar = ({ percentage, color = 'teal', className = '' }) => {
  const colorClasses = {
    teal: 'bg-linear-to-r from-teal-500 to-blue-500',
    blue: 'bg-linear-to-r from-blue-500 to-cyan-500',
    emerald: 'bg-linear-to-r from-emerald-500 to-teal-500',
    amber: 'bg-linear-to-r from-amber-500 to-orange-500',
    purple: 'bg-linear-to-r from-purple-500 to-pink-500'
  };

  return (
    <div className="w-full bg-gray-100 rounded-full h-2 overflow-hidden">
      <div 
        className={`h-2 rounded-full ${colorClasses[color]} transition-all duration-500 ${className}`}
        style={{ width: `${percentage}%` }}
      ></div>
    </div>
  );
};

// Form Input Component
const FormInput = React.memo(({ 
  label, 
  icon: Icon, 
  type = 'text', 
  value, 
  onChange, 
  placeholder, 
  options = [],
  step,
  min,
  max,
  className = '',
  ...props 
}) => {
  return (
    <div className={className}>
      <label className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-2">
        <div className="w-8 h-8 rounded-lg bg-teal-50 border border-teal-100 flex items-center justify-center">
          <Icon className="w-4 h-4 text-teal-600" />
        </div>
        {label}
      </label>
      {type === 'select' ? (
        <div className="relative">
          <select
            value={value}
            onChange={onChange}
            className="w-full p-4 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white transition-all duration-200 hover:border-gray-300 appearance-none cursor-pointer"
            {...props}
          >
            {options.map(option => (
              <option key={option.value || option.id} value={option.value || option.id}>
                {option.label || option.title || option.name}
              </option>
            ))}
          </select>
          <ChevronDown className="absolute right-4 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
        </div>
      ) : (
        <input
          type={type}
          value={value}
          onChange={onChange}
          placeholder={placeholder}
          step={step}
          min={min}
          max={max}
          className="w-full p-4 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all duration-200 hover:border-gray-300"
          {...props}
        />
      )}
    </div>
  );
});

FormInput.displayName = 'FormInput';

// User Info Modal Component
const UserInfoModal = React.memo(({ 
  showUserModal, 
  userInfo, 
  onClose, 
  onSubmit, 
  onUserInfoChange,
  isLoading = false 
}) => {
  if (!showUserModal) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit();
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
      <div className="bg-white rounded-3xl w-full max-w-lg shadow-2xl animate-in fade-in zoom-in duration-300 border border-gray-100">
        <div className="p-8 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-linear-to-r from-teal-500 to-blue-500 flex items-center justify-center shadow-lg">
                <User className="w-6 h-6 text-white" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900">Complete Your Profile</h2>
                <p className="text-gray-600 text-sm mt-1">
                  We'll save your analysis for future reference
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors hover:bg-gray-100 rounded-lg p-2"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>
        
        <form onSubmit={handleSubmit} className="p-8 space-y-6">
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
              <User className="w-4 h-4 text-gray-400" />
              Full Name *
            </label>
            <input
              type="text"
              required
              value={userInfo.name}
              onChange={(e) => onUserInfoChange('name', e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
              placeholder="John Smith"
              disabled={isLoading}
            />
          </div>
          
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
              <Mail className="w-4 h-4 text-gray-400" />
              Email Address *
            </label>
            <input
              type="email"
              required
              value={userInfo.email}
              onChange={(e) => onUserInfoChange('email', e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
              placeholder="john@example.com"
              disabled={isLoading}
            />
          </div>
          
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
              <Phone className="w-4 h-4 text-gray-400" />
              Phone Number *
            </label>
            <input
              type="tel"
              required
              value={userInfo.phone}
              onChange={(e) => onUserInfoChange('phone', e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
              placeholder="+1234567890"
              disabled={isLoading}
            />
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors font-medium"
              disabled={isLoading}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isLoading}
              className="flex-1 px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 font-medium flex items-center justify-center gap-2 disabled:opacity-50 shadow-lg"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Processing...
                </>
              ) : (
                <>
                  <Save className="w-5 h-5" />
                  Continue
                </>
              )}
            </button>
          </div>
          
          <p className="text-xs text-gray-500 text-center pt-2">
            Your data is securely stored and only used for personalized recommendations.
          </p>
        </form>
      </div>
    </div>
  );
});

UserInfoModal.displayName = 'UserInfoModal';

// Email Modal Component
const EmailModal = React.memo(({ 
  isOpen, 
  onClose, 
  userInfo, 
  onUserInfoChange, 
  onSubmit, 
  isLoading = false 
}) => {
  if (!isOpen) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit();
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
      <div className="bg-white rounded-3xl w-full max-w-lg shadow-2xl animate-in fade-in zoom-in duration-300 border border-gray-100">
        <div className="p-8 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-linear-to-r from-teal-500 to-blue-500 flex items-center justify-center shadow-lg">
                <Mail className="w-6 h-6 text-white" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900">Get Your AI Analysis Report</h2>
                <p className="text-gray-600 text-sm mt-1">
                  We'll send a detailed analysis report to your email
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors hover:bg-gray-100 rounded-lg p-2"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>
        
        <form onSubmit={handleSubmit} className="p-8 space-y-6">
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
              <User className="w-4 h-4 text-gray-400" />
              Full Name *
            </label>
            <input
              type="text"
              required
              value={userInfo.name}
              onChange={(e) => onUserInfoChange('name', e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
              placeholder="John Smith"
              disabled={isLoading}
            />
          </div>
          
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
              <Mail className="w-4 h-4 text-gray-400" />
              Email Address *
            </label>
            <input
              type="email"
              required
              value={userInfo.email}
              onChange={(e) => onUserInfoChange('email', e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
              placeholder="john@example.com"
              disabled={isLoading}
            />
          </div>
          
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
              <Phone className="w-4 h-4 text-gray-400" />
              Phone Number *
            </label>
            <input
              type="tel"
              required
              value={userInfo.phone}
              onChange={(e) => onUserInfoChange('phone', e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
              placeholder="+1234567890"
              disabled={isLoading}
            />
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors font-medium"
              disabled={isLoading}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isLoading}
              className="flex-1 px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 font-medium flex items-center justify-center gap-2 disabled:opacity-50 shadow-lg"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Sending...
                </>
              ) : (
                <>
                  <Send className="w-5 h-5" />
                  Send Report
                </>
              )}
            </button>
          </div>
          
          <p className="text-xs text-gray-500 text-center pt-2">
            Your report will include detailed AI analysis, course recommendations, and improvement suggestions.
          </p>
        </form>
      </div>
    </div>
  );
});

EmailModal.displayName = 'EmailModal';

// Score Breakdown Modal
const ScoreBreakdown = ({ course, onClose }) => {
  if (!course) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
      <ModernCard className="max-w-lg w-full max-h-[90vh] overflow-y-auto">
        <div className="p-8">
          <div className="flex justify-between items-center mb-8">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-linear-to-r from-teal-500 to-blue-500 flex items-center justify-center">
                <PieChart className="w-6 h-6 text-white" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900">AI Score Breakdown</h2>
                <p className="text-gray-600 text-sm mt-1">{course.name}</p>
              </div>
            </div>
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg p-2 transition-colors">
              <X className="w-5 h-5" />
            </button>
          </div>
          
          {/* Overall Score */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-4">
              <span className="text-lg font-bold text-gray-900">Overall AI Score</span>
              <div className="flex items-center gap-2">
                <div className="text-3xl font-bold text-teal-600">
                  {course.ai_analysis?.eligibility_score || Math.round(course.similarity_score * 100)}%
                </div>
                <div className={`px-3 py-1 rounded-full text-xs font-bold ${
                  (course.ai_analysis?.eligibility_score || course.similarity_score * 100) >= 80 ? 'bg-emerald-100 text-emerald-800 border-emerald-200' :
                  (course.ai_analysis?.eligibility_score || course.similarity_score * 100) >= 60 ? 'bg-amber-100 text-amber-800 border-amber-200' :
                  'bg-red-100 text-red-800 border-red-200'
                } border`}>
                  {(course.ai_analysis?.eligibility_score || course.similarity_score * 100) >= 80 ? 'Excellent' :
                   (course.ai_analysis?.eligibility_score || course.similarity_score * 100) >= 60 ? 'Good' : 'Fair'}
                </div>
              </div>
            </div>
            
            {course.ai_analysis?.score_breakdown && (
              <div className="space-y-6">
                {/* Academic Fit */}
                <div>
                  <div className="flex justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <GraduationCap className="w-4 h-4 text-blue-600" />
                      <span className="font-medium text-gray-900">Academic Fit</span>
                    </div>
                    <span className="font-bold text-blue-600">{course.ai_analysis.score_breakdown.academic_fit}%</span>
                  </div>
                  <ProgressBar percentage={course.ai_analysis.score_breakdown.academic_fit} color="blue" />
                </div>
                
                {/* Financial Fit */}
                <div>
                  <div className="flex justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <DollarSign className="w-4 h-4 text-emerald-600" />
                      <span className="font-medium text-gray-900">Financial Fit</span>
                    </div>
                    <span className="font-bold text-emerald-600">{course.ai_analysis.score_breakdown.financial_fit}%</span>
                  </div>
                  <ProgressBar percentage={course.ai_analysis.score_breakdown.financial_fit} color="emerald" />
                </div>
                
                {/* Country/University Fit */}
                <div>
                  <div className="flex justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <MapPin className="w-4 h-4 text-teal-600" />
                      <span className="font-medium text-gray-900">Location Fit</span>
                    </div>
                    <span className="font-bold text-teal-600">{course.ai_analysis.score_breakdown.country_university_fit}%</span>
                  </div>
                  <ProgressBar percentage={course.ai_analysis.score_breakdown.country_university_fit} color="teal" />
                </div>
                
                {/* Requirements Match */}
                <div>
                  <div className="flex justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <CheckCircle className="w-4 h-4 text-amber-600" />
                      <span className="font-medium text-gray-900">Requirements</span>
                    </div>
                    <span className="font-bold text-amber-600">{course.ai_analysis.score_breakdown.requirements_match}%</span>
                  </div>
                  <ProgressBar percentage={course.ai_analysis.score_breakdown.requirements_match} color="amber" />
                </div>
                
                {/* Major Alignment */}
                <div>
                  <div className="flex justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <Target className="w-4 h-4 text-purple-600" />
                      <span className="font-medium text-gray-900">Major Alignment</span>
                    </div>
                    <span className="font-bold text-purple-600">{course.ai_analysis.score_breakdown.major_alignment}%</span>
                  </div>
                  <ProgressBar percentage={course.ai_analysis.score_breakdown.major_alignment} color="purple" />
                </div>
              </div>
            )}
          </div>
          
          {/* Strengths & Concerns */}
          <div className="grid grid-cols-2 gap-6">
            <div>
              <h4 className="font-bold text-gray-900 mb-3 flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-emerald-600" />
                Key Strengths
              </h4>
              <div className="space-y-2">
                {course.ai_analysis?.key_strengths?.map((strength, idx) => (
                  <div key={idx} className="flex items-start gap-2">
                    <div className="w-2 h-2 rounded-full bg-emerald-500 mt-2 shrink-0"></div>
                    <span className="text-sm text-gray-700">{strength}</span>
                  </div>
                )) || (
                  <p className="text-sm text-gray-500">No strengths identified</p>
                )}
              </div>
            </div>
            
            <div>
              <h4 className="font-bold text-gray-900 mb-3 flex items-center gap-2">
                <AlertCircle className="w-4 h-4 text-amber-600" />
                Key Concerns
              </h4>
              <div className="space-y-2">
                {course.ai_analysis?.key_concerns?.map((concern, idx) => (
                  <div key={idx} className="flex items-start gap-2">
                    <div className="w-2 h-2 rounded-full bg-amber-500 mt-2 shrink-0"></div>
                    <span className="text-sm text-gray-700">{concern}</span>
                  </div>
                )) || (
                  <p className="text-sm text-gray-500">No major concerns</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </ModernCard>
    </div>
  );
};

const AIEligibilityCalculator = ({ countries = [], levels = [], subjects = [], pageData = [], faqs }) => {
  // Form state
  const [formData, setFormData] = useState({
    country: '',
    gpa: '',
    englishTestType: '',
    englishTestScore: '',
    budget: '',
    major: '',
    qualification: ''
  });

  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    phone: ''
  });

  const [showUserModal, setShowUserModal] = useState(false);
  const [showEmailModal, setShowEmailModal] = useState(false);
  const [currencyInfo, setCurrencyInfo] = useState({
    currency: 'USD',
    currency_symbol: '$'
  });

  // AI Results state - UPDATED: Now stores all 32 courses
  const [aiResults, setAiResults] = useState(null);
  const [loading, setLoading] = useState(false);
  const [emailLoading, setEmailLoading] = useState(false);
  const [emailStatus, setEmailStatus] = useState(null);
  const [currentPage, setCurrentPage] = useState(1); // Client-side pagination
  const [showScoreBreakdown, setShowScoreBreakdown] = useState(null);
  const [error, setError] = useState('');
  const { wishlist, toggleWishlist, isWishlisted } = useWishlist();
  const [expandedCourse, setExpandedCourse] = useState(null);

  // Test options
  const englishTests = [
    { value: 'ielts', label: 'IELTS', maxScore: 9, step: 0.5, placeholder: 'e.g., 6.5' },
    { value: 'pte', label: 'PTE', maxScore: 90, step: 1, placeholder: 'e.g., 58' },
    { value: 'toefl', label: 'TOEFL', maxScore: 120, step: 1, placeholder: 'e.g., 80' },
    { value: 'duolingo', label: 'Duolingo', maxScore: 160, step: 5, placeholder: 'e.g., 105' },
    { value: 'none', label: 'No English Test', maxScore: 0, step: 0, placeholder: '' }
  ];

  const qualifications = levels.map(level => ({
    id: level.id,
    title: level.title
  }));

  // Features array
  const features = [
    {
      icon: Brain,
      title: "AI-Powered Analysis",
      description: "Intelligent matching using advanced machine learning algorithms",
      color: "from-teal-500 to-blue-500"
    },
    {
      icon: Target,
      title: "Personalized Scores",
      description: "Get custom eligibility scores based on your profile",
      color: "from-blue-500 to-cyan-400"
    },
    {
      icon: DollarSign,
      title: "Budget Optimization",
      description: "Find programs that match your financial capabilities",
      color: "from-emerald-500 to-teal-400"
    },
    {
      icon: Zap,
      title: "Fast Results",
      description: "Get instant analysis of thousands of programs",
      color: "from-amber-500 to-orange-400"
    }
  ];

  // Check for stored user data on component mount
  useEffect(() => {
    const storedUserData = eligibilityStorage.getUserData();
    if (storedUserData) {
      setUserInfo({
        name: storedUserData.name,
        email: storedUserData.email,
        phone: storedUserData.phone
      });
    }
  }, []);

  // Update currency when country changes
  useEffect(() => {
    if (formData.country) {
      const selectedCountry = countries.find(c => c.country === formData.country);
      if (selectedCountry) {
        setCurrencyInfo({
          currency: selectedCountry.currency || 'USD',
          currency_symbol: selectedCountry.currency_symbol || '$'
        });
      }
    } else {
      setCurrencyInfo({
        currency: 'USD',
        currency_symbol: '$'
      });
    }
  }, [formData.country, countries]);

  const handleInputChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setError('');
    
    if (field === 'englishTestType' && value === 'none') {
      setFormData(prev => ({ ...prev, englishTestScore: '' }));
    }
  };

  const handleUserInfoChange = (field, value) => {
    setUserInfo(prev => ({ ...prev, [field]: value }));
  };

  const hasMinimumData = () => {
    return Object.values(formData).some(value => value && value !== '');
  };

  const calculateEligibility = async () => {
    if (!hasMinimumData()) {
      setError('Please fill at least one field to get AI-powered recommendations');
      return;
    }

    // Check if we have user info
    if (!userInfo.name || !userInfo.email || !userInfo.phone) {
      setShowUserModal(true);
      return;
    }

    await performAIAnalysis();
  };

  const performAIAnalysis = async () => {
    setLoading(true);
    setCurrentPage(1); // Reset to first page
    setError('');
    
    try {
      // First, submit user data
      const submitResponse = await fetch('/api/frontend/eligibility-calculator/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...userInfo,
          ...formData,
          budget: formData.budget ? parseFloat(formData.budget) : null,
          gpa: formData.gpa ? parseFloat(formData.gpa) : null,
          englishTestScore: formData.englishTestScore ? parseFloat(formData.englishTestScore) : null,
        })
      });

      if (!submitResponse.ok) {
        throw new Error('Failed to submit user data');
      }

      // Store user info in localStorage
      eligibilityStorage.setUserData(userInfo);

      // Call AI Eligibility Calculator API with limit=32
      const response = await fetch('/api/frontend/eligibility-calculator', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          country: formData.country,
          qualification: formData.qualification,
          max_fee: formData.budget ? parseFloat(formData.budget) : 0,
          gpa: formData.gpa ? parseFloat(formData.gpa) : 0,
          english_test_type: formData.englishTestType,
          english_test_score: formData.englishTestScore ? parseFloat(formData.englishTestScore) : 0,
          major: formData.major,
          limit: 32, // UPDATED: Get 32 courses upfront
          page: 1
        })
      });

      if (!response.ok) {
        throw new Error('AI analysis failed');
      }

      const data = await response.json();
      
      if (!data.success || !data.courses || data.courses.length === 0) {
        setError('No programs found matching your criteria. Try adjusting your preferences.');
        setAiResults(null);
        return;
      }

      setAiResults(data);

    } catch (error) {
      console.error('AI Analysis error:', error);
      setError('Failed to analyze your profile. Please check your connection and try again.');
      setAiResults(null);
    } finally {
      setLoading(false);
    }
  };

  const handleModalSubmit = () => {
    // Basic validation
    if (!userInfo.name.trim() || !userInfo.email.trim() || !userInfo.phone.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'Missing Information',
        text: 'Please fill all required fields',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(userInfo.email)) {
      Swal.fire({
        icon: 'warning',
        title: 'Invalid Email',
        text: 'Please enter a valid email address',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    setShowUserModal(false);
    performAIAnalysis();
  };

  // Email Functionality
  const handleSendEmail = async () => {
    if (!aiResults) {
      Swal.fire({
        icon: 'warning',
        title: 'No Analysis Available',
        text: 'Please run AI analysis first before sending email',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    const storedUserData = eligibilityStorage.getUserData();
    if (!storedUserData || !storedUserData.email) {
      // Show modal to collect email
      setShowEmailModal(true);
      return;
    }

    await sendEmailReport(storedUserData);
  };

  const handleEmailModalSubmit = () => {
    // Basic validation
    if (!userInfo.name.trim() || !userInfo.email.trim() || !userInfo.phone.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'Missing Information',
        text: 'Please fill all required fields',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(userInfo.email)) {
      Swal.fire({
        icon: 'warning',
        title: 'Invalid Email',
        text: 'Please enter a valid email address',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    eligibilityStorage.setUserData(userInfo);
    setShowEmailModal(false);
    sendEmailReport(userInfo);
  };

  const sendEmailReport = async (userDataToSend) => {
    setEmailLoading(true);
    setEmailStatus(null);

    try {
      const response = await fetch('/api/frontend/eligibility-calculator/send-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          eligibilityResults: aiResults,
          userData: userDataToSend,
          calculationInputs: formData,
          symbol: currencyInfo.currency_symbol
        })
      });

      const result = await response.json();

      if (result.success) {
        setEmailStatus({ type: 'success', message: 'Email sent successfully!' });
        Swal.fire({
          icon: 'success',
          title: 'Email Sent!',
          html: `
            <div class="text-center">
              <div class="text-4xl mb-4">📧</div>
              <p>Your AI analysis report has been sent to:</p>
              <p class="font-semibold text-teal-600 mt-2">${userDataToSend.email}</p>
              <p class="text-sm text-gray-600 mt-4">Check your inbox and spam folder</p>
            </div>
          `,
          confirmButtonColor: '#0B6D76',
          timer: 5000,
          showConfirmButton: false,
          background: '#ffffff',
          color: '#1f2937'
        });
      } else {
        setEmailStatus({ type: 'error', message: result.message });
        Swal.fire({
          icon: 'error',
          title: 'Failed to Send',
          text: result.message || 'Unable to send email. Please try again.',
          confirmButtonColor: '#0B6D76',
          background: '#ffffff',
          color: '#1f2937'
        });
      }
    } catch (error) {
      console.error('Error sending email:', error);
      setEmailStatus({ type: 'error', message: 'Network error. Please try again.' });
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Unable to connect to email service. Please check your connection.',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
    } finally {
      setEmailLoading(false);
    }
  };

  const renderEmailStatus = () => {
    if (!emailStatus) return null;
    
    return (
      <div className={`rounded-xl p-4 mb-6 animate-in slide-in-from-top duration-300 ${
        emailStatus.type === 'success' 
          ? 'bg-emerald-50 border border-emerald-200 text-emerald-800' 
          : 'bg-red-50 border border-red-200 text-red-800'
      }`}>
        <div className="flex items-center gap-3">
          {emailStatus.type === 'success' ? (
            <CheckCircle className="w-6 h-6 text-emerald-600" />
          ) : (
            <X className="w-6 h-6 text-red-600" />
          )}
          <span className="font-medium">{emailStatus.message}</span>
          <button
            onClick={() => setEmailStatus(null)}
            className="ml-auto text-gray-400 hover:text-gray-600"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
      </div>
    );
  };

  const resetCalculator = () => {
    setFormData({
      country: '', 
      gpa: '', 
      englishTestType: '', 
      englishTestScore: '', 
      budget: '', 
      major: '', 
      qualification: '' 
    });
    setAiResults(null);
    setCurrentPage(1);
    setShowScoreBreakdown(null);
    setError('');
    setExpandedCourse(null);
    setEmailStatus(null);
  };

  // Client-side pagination logic
  const itemsPerPage = 8;
  const totalCourses = aiResults?.courses?.length || 0;
  const totalPages = Math.ceil(totalCourses / itemsPerPage);
  
  // Get current page courses
  const getCurrentPageCourses = () => {
    if (!aiResults?.courses) return [];
    
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return aiResults.courses.slice(startIndex, endIndex);
  };

  const handlePageChange = (newPage) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setCurrentPage(newPage);
      // Scroll to results section
      const resultsSection = document.getElementById('ai-results-section');
      if (resultsSection) {
        resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }
  };

  // Generate pagination numbers
  const getPaginationNumbers = () => {
    const pages = [];
    const maxVisible = 5;
    
    if (totalPages <= maxVisible) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        for (let i = 1; i <= 4; i++) pages.push(i);
        pages.push('...');
        pages.push(totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1);
        pages.push('...');
        for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
      } else {
        pages.push(1);
        pages.push('...');
        pages.push(currentPage - 1);
        pages.push(currentPage);
        pages.push(currentPage + 1);
        pages.push('...');
        pages.push(totalPages);
      }
    }
    
    return pages;
  };

  const handleWishlistToggle = (course) => {
    const courseWithType = {
      ...course,
      type: 'course',
      label: 'course'
    };
    toggleWishlist(courseWithType);
  };

  const isCourseWishlisted = (course) => {
    const courseWithType = {
      ...course,
      type: 'course',
      label: 'course'
    };
    return isWishlisted(courseWithType);
  };

  const getCurrentEnglishTest = () => {
    return englishTests.find(test => test.value === formData.englishTestType);
  };

  // Render functions
  const renderAIInsights = () => {
    if (!aiResults?.ai_insights?.overall_summary) return null;

    return (
      <ModernCard className="overflow-hidden">
        <div className="bg-linear-to-r from-teal-600 to-blue-500 p-8">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center">
              <Brain className="w-7 h-7 text-white" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-white">AI Profile Analysis</h2>
              <p className="text-white/90 mt-1">Powered by UniversitiesPage AI</p>
            </div>
          </div>
        </div>
        <div className="p-8">
          <div className="prose prose-lg max-w-none">
            <div className="text-gray-700 leading-relaxed bg-gray-50 p-6 rounded-xl border border-gray-100 whitespace-pre-line">
              {aiResults.ai_insights.overall_summary}
            </div>
          </div>
          <div className="flex flex-wrap gap-2 mt-6">
            <Badge color="teal" icon={Brain}>
              AI-Powered Analysis
            </Badge>
            <Badge color="blue">
              {aiResults.meta?.response_format === 'ai_enhanced' ? 'Enhanced Analysis' : 'Basic Analysis'}
            </Badge>
            <Badge color="emerald" icon={Sparkles}>
              {aiResults.courses?.length || 0} Courses Analyzed
            </Badge>
            <Badge color="amber" icon={Zap}>
              Instant Client-side Pagination
            </Badge>
          </div>
        </div>
      </ModernCard>
    );
  };

  const renderCourseCard = (course) => {
    const aiAnalysis = course.ai_analysis;
    const isExpanded = expandedCourse === course.id;

    return (
      <ModernCard key={course.id} className="overflow-hidden hover:shadow-xl transition-all duration-300 group">
        {/* Card Header */}
        <div className="relative h-48 bg-linear-to-br from-teal-600 to-blue-500">
          {/* Wishlist Button */}
          <button
            className="absolute top-4 right-4 w-10 h-10 bg-white/20 hover:bg-white/30 backdrop-blur-sm rounded-full flex items-center justify-center text-white transition-colors cursor-pointer z-10"
            onClick={() => handleWishlistToggle(course)}
            title={isCourseWishlisted(course) ? 'Remove from wishlist' : 'Add to wishlist'}
          >
            {isCourseWishlisted(course) ? (
              <FaHeart className="text-red-400 text-base" />
            ) : (
              <FaRegHeart className="text-white text-base" />
            )}
          </button>
          
          {/* Score Badge */}
          <div className="absolute bottom-4 right-4">
            <div className={`px-4 py-2 rounded-xl font-bold shadow-lg ${
              (aiAnalysis?.eligibility_score || course.similarity_score * 100) >= 80 ? 'bg-linear-to-r from-emerald-500 to-teal-500' :
              (aiAnalysis?.eligibility_score || course.similarity_score * 100) >= 60 ? 'bg-linear-to-r from-amber-500 to-orange-500' :
              'bg-linear-to-r from-red-500 to-pink-500'
            } text-white`}>
              AI Score: {aiAnalysis?.eligibility_score || Math.round(course.similarity_score * 100)}%
            </div>
          </div>

          <div className="absolute inset-0 flex items-center justify-center">
            <div className="text-center px-4">
              <h3 className="text-2xl font-bold text-white mb-2 line-clamp-2">{course.name}</h3>
              <p className="text-white/90 text-sm">{course.university_name}</p>
            </div>
          </div>
        </div>

        {/* Card Body */}
        <div className="p-6">
          {/* Basic Info */}
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="text-center">
              <MapPin className="w-5 h-5 text-gray-400 mx-auto mb-2" />
              <div className="text-sm font-medium text-gray-900">{course.country_name}</div>
            </div>
            <div className="text-center">
              <Clock className="w-5 h-5 text-gray-400 mx-auto mb-2" />
              <div className="text-sm font-medium text-gray-900">{course.duration} months</div>
            </div>
            <div className="text-center">
              <DollarSign className="w-5 h-5 text-gray-400 mx-auto mb-2" />
              <div className="text-sm font-medium text-gray-900">
                {course.currency_symbol || currencyInfo.currency_symbol}{parseInt(course.yearly_fee).toLocaleString()}
              </div>
            </div>
          </div>

          {/* AI Analysis Summary */}
          {aiAnalysis && (
            <div className="mb-6">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <Brain className="w-4 h-4 text-teal-600" />
                  <span className="font-medium text-gray-900">AI Analysis</span>
                </div>
                <Badge color={
                  aiAnalysis.recommendation === 'strong_recommend' ? 'emerald' :
                  aiAnalysis.recommendation === 'recommend_with_conditions' ? 'amber' : 'red'
                }>
                  {aiAnalysis.recommendation === 'strong_recommend' ? 'Strong Match' :
                   aiAnalysis.recommendation === 'recommend_with_conditions' ? 'Good Match' : 'Fair Match'}
                </Badge>
              </div>
              <p className="text-sm text-gray-600 line-clamp-3">{aiAnalysis.analysis_summary}</p>
            </div>
          )}

          {/* Expandable Detailed Analysis */}
          {aiAnalysis && (
            <div className="mb-6">
              <button
                onClick={() => setExpandedCourse(isExpanded ? null : course.id)}
                className="w-full text-left text-sm font-medium text-teal-600 hover:text-teal-700 flex items-center justify-between"
              >
                <span>View AI Analysis Details</span>
                {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </button>
              
              {isExpanded && (
                <div className="mt-4 space-y-4 animate-in slide-in-from-top">
                  {/* Strengths & Concerns */}
                  <div className="grid grid-cols-2 gap-4">
                    <div className="bg-emerald-50 border border-emerald-100 rounded-xl p-4">
                      <h4 className="font-semibold text-emerald-800 text-sm mb-2 flex items-center gap-2">
                        <CheckCircle className="w-4 h-4" />
                        Strengths
                      </h4>
                      <ul className="space-y-2">
                        {aiAnalysis.key_strengths?.slice(0, 3).map((strength, idx) => (
                          <li key={idx} className="text-sm text-emerald-700 flex items-start gap-2">
                            <div className="w-2 h-2 rounded-full bg-emerald-500 mt-1.5 shrink-0"></div>
                            {strength}
                          </li>
                        ))}
                      </ul>
                    </div>
                    
                    <div className="bg-amber-50 border border-amber-100 rounded-xl p-4">
                      <h4 className="font-semibold text-amber-800 text-sm mb-2 flex items-center gap-2">
                        <AlertCircle className="w-4 h-4" />
                        Concerns
                      </h4>
                      <ul className="space-y-2">
                        {aiAnalysis.key_concerns?.slice(0, 3).map((concern, idx) => (
                          <li key={idx} className="text-sm text-amber-700 flex items-start gap-2">
                            <div className="w-2 h-2 rounded-full bg-amber-500 mt-1.5 shrink-0"></div>
                            {concern}
                          </li>
                        ))}
                      </ul>
                    </div>
                  </div>

                  {/* Specific Advice */}
                  {aiAnalysis.specific_advice && (
                    <div className="bg-blue-50 border border-blue-100 rounded-xl p-4">
                      <h4 className="font-semibold text-blue-800 text-sm mb-2 flex items-center gap-2">
                        <Lightbulb className="w-4 h-4" />
                        AI Recommendations
                      </h4>
                      <p className="text-sm text-blue-700">{aiAnalysis.specific_advice}</p>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Score Breakdown Button */}
          <button
            onClick={() => setShowScoreBreakdown(course)}
            className="w-full mb-4 text-sm font-medium text-gray-600 hover:text-teal-600 flex items-center justify-center gap-2"
          >
            <PieChart className="w-4 h-4" />
            View Detailed Score Breakdown
          </button>

          {/* Action Buttons */}
          <div className="flex gap-3">
            <Link 
              href={`/courses/${course.id}`}
              className="flex-1 bg-linear-to-r from-teal-600 to-blue-500 text-white px-4 py-3 rounded-xl font-semibold hover:shadow-lg hover:scale-105 transition-all duration-300 text-sm flex items-center justify-center gap-2 shadow-lg"
            >
              <span>View Details</span>
              <ArrowRight className="w-4 h-4" />
            </Link>
            <button
              onClick={() => setShowScoreBreakdown(course)}
              className="px-4 py-3 border-2 border-gray-200 text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition-all duration-300 flex items-center justify-center"
              title="View AI Analysis"
            >
              <Brain className="w-4 h-4" />
            </button>
          </div>
        </div>
      </ModernCard>
    );
  };

  // Client-side Pagination Component
  const Pagination = () => {
    if (!aiResults?.courses || totalPages <= 1) return null;

    const paginationNumbers = getPaginationNumbers();

    return (
      <div className="flex flex-col md:flex-row items-center justify-between gap-4 mt-8 pt-6 border-t border-gray-200">
        <div className="text-sm text-gray-600">
          Page {currentPage} of {totalPages} • Showing {getCurrentPageCourses().length} of {totalCourses} analyzed courses
        </div>
        
        <div className="flex items-center gap-2">
          <button
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
            className={`flex items-center gap-2 px-4 py-2 rounded-xl font-semibold transition-all duration-200 ${
              currentPage > 1
                ? 'bg-white text-gray-700 hover:bg-gray-50 border-2 border-gray-200'
                : 'bg-gray-100 text-gray-400 cursor-not-allowed border-2 border-gray-200'
            }`}
          >
            <ChevronLeft className="w-4 h-4" />
            Previous
          </button>

          <div className="flex items-center gap-1">
            {paginationNumbers.map((pageNum, index) => (
              pageNum === '...' ? (
                <span key={`ellipsis-${index}`} className="px-3 py-2 text-gray-400">
                  ...
                </span>
              ) : (
                <button
                  key={pageNum}
                  onClick={() => handlePageChange(pageNum)}
                  className={`px-3 py-2 rounded-lg font-semibold transition-all duration-200 ${
                    currentPage === pageNum
                      ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-md'
                      : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-200'
                  }`}
                >
                  {pageNum}
                </button>
              )
            ))}
          </div>

          <button
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
            className={`flex items-center gap-2 px-4 py-2 rounded-xl font-semibold transition-all duration-200 ${
              currentPage < totalPages
                ? 'bg-white text-gray-700 hover:bg-gray-50 border-2 border-gray-200'
                : 'bg-gray-100 text-gray-400 cursor-not-allowed border-2 border-gray-200'
            }`}
          >
            Next
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      </div>
    );
  };

  return (
    <>
      <UserInfoModal 
        showUserModal={showUserModal}
        userInfo={userInfo}
        onClose={() => setShowUserModal(false)}
        onSubmit={handleModalSubmit}
        onUserInfoChange={handleUserInfoChange}
        isLoading={loading}
      />

      <EmailModal 
        isOpen={showEmailModal}
        userInfo={userInfo}
        onClose={() => setShowEmailModal(false)}
        onUserInfoChange={handleUserInfoChange}
        onSubmit={handleEmailModalSubmit}
        isLoading={emailLoading}
      />
      
      <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
        {/* Hero Section - Matching comparison tool */}
        <div className="relative">
          {/* Background linear */}
          <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
          
          {/* Animated Background Elements */}
          <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
            {[...Array(20)].map((_, i) => (
              <div
                key={i}
                className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
                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>

          <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-24">
            <div className="text-center">
              {/* Badge */}
              <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-4 py-2 rounded-full text-sm font-semibold mb-6 animate-pulse">
                <Shield className="w-4 h-4" />
                AI-Powered Eligibility Calculator
              </div>

              {/* Main Heading */}
              <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-6 leading-tight">
                {pageData?.simple_title}{' '}
                <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  {pageData?.color_title}
                </span>
              </h1>

              {/* Subheading */}
              <p className="text-xl md:text-2xl text-gray-600 mb-10 max-w-3xl mx-auto leading-relaxed">
                {pageData?.short_description}
              </p>

              {/* Stats Preview */}
              <div className="bg-white/80 backdrop-blur-sm rounded-3xl p-6 max-w-4xl mx-auto border border-gray-100 shadow-lg mb-12">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                  <div className="text-center">
                    <div className="text-2xl md:text-3xl font-bold text-teal-600 mb-1">🤖</div>
                    <div className="font-semibold text-gray-900">AI-Powered</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl md:text-3xl font-bold text-blue-600 mb-1">⚡</div>
                    <div className="font-semibold text-gray-900">Instant Results</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl md:text-3xl font-bold text-emerald-600 mb-1">🎯</div>
                    <div className="font-semibold text-gray-900">Personalized</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl md:text-3xl font-bold text-amber-600 mb-1">📊</div>
                    <div className="font-semibold text-gray-900">Detailed Analysis</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20 -mt-8">
          {/* Error Message */}
          {error && (
            <div className="mb-6 bg-linear-to-r from-red-50 to-red-100 border border-red-200 rounded-2xl p-6">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 rounded-xl bg-linear-to-r from-red-500 to-red-600 flex items-center justify-center shrink-0">
                  <AlertCircle className="w-6 h-6 text-white" />
                </div>
                <div className="flex-1">
                  <h3 className="font-semibold text-red-800 text-lg mb-1">Attention Required</h3>
                  <p className="text-red-700">{error}</p>
                </div>
              </div>
            </div>
          )}

          {/* Email Status */}
          {renderEmailStatus()}

          {/* Form Section */}
          <ModernCard className="mb-8 mt-10">
            <div className="p-8 border-b border-gray-200">
              <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                  <h2 className="text-2xl md:text-3xl font-bold text-gray-900 mb-2">
                    Your Profile Details
                  </h2>
                  <p className="text-gray-600">Fill in your academic and preference details for AI analysis</p>
                </div>
                {aiResults && (
                  <div className="flex gap-3">
                    <button
                      onClick={handleSendEmail}
                      disabled={emailLoading || !aiResults}
                      className="px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl font-semibold hover:shadow-lg hover:scale-105 transition-all duration-300 shadow-lg flex items-center gap-2 disabled:opacity-50"
                    >
                      {emailLoading ? (
                        <Loader2 className="w-5 h-5 animate-spin" />
                      ) : (
                        <Send className="w-5 h-5" />
                      )}
                      Email Report
                    </button>
                    <button
                      onClick={resetCalculator}
                      className="px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition-all duration-300 flex items-center gap-2"
                    >
                      <RefreshCw className="w-5 h-5" />
                      New Analysis
                    </button>
                  </div>
                )}
              </div>
            </div>

            {/* Form Grid */}
            <div className="p-8">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-8">
                <FormInput
                  label="What study level are you applying for?*"
                  icon={School}
                  type="select"
                  value={formData.qualification}
                  onChange={(e) => handleInputChange('qualification', e.target.value)}
                  options={[{ value: '', label: 'Select your desired level' }, ...qualifications]}
                />

                <FormInput
                  label="What do you want to study?*"
                  icon={BookOpen}
                  type="select"
                  value={formData.major}
                  onChange={(e) => handleInputChange('major', e.target.value)}
                  options={[{ value: '', label: 'Choose your field' }, ...subjects]}
                />

                <FormInput
                  label="Which country do you prefer?*"
                  icon={Flag}
                  type="select"
                  value={formData.country}
                  onChange={(e) => handleInputChange('country', e.target.value)}
                  options={[{ value: '', label: 'Choose destination country' }, ...countries.map(country => ({
                    value: country.country,
                    label: `${country.country} (${country.currency_symbol || '$'})`
                  }))]}
                />

                <FormInput
                  label="Your current CGPA or percentage*"
                  icon={User}
                  type="select"
                  value={formData.gpa}
                  onChange={(e) => handleInputChange('gpa', e.target.value)}
                  options={[
                    { value: '', label: 'Select your CGPA or percentage' },
                    ...Array.from({ length: 41 }, (_, i) => {
                      const gpaValue = (i * 0.1).toFixed(1);
                      const percentage = Math.round(gpaValue * 25);
                      return {
                        value: gpaValue,
                        label: `CGPA: ${gpaValue} (${percentage}%)`
                      };
                    })
                  ]}
                />

                <FormInput
                  label="English language test"
                  icon={Globe}
                  type="select"
                  value={formData.englishTestType}
                  onChange={(e) => handleInputChange('englishTestType', e.target.value)}
                  options={[{ value: '', label: 'Select test (IELTS, TOEFL, PTE)' }, ...englishTests]}
                />

                <div>
                  <label className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-2">
                    <div className="w-8 h-8 rounded-lg bg-teal-50 border border-teal-100 flex items-center justify-center">
                      <Award className="w-4 h-4 text-teal-600" />
                    </div>
                    Your score
                  </label>
                  {formData.englishTestType && formData.englishTestType !== 'none' ? (
                    <input
                      type="number"
                      step={getCurrentEnglishTest()?.step || 0.5}
                      min="0"
                      max={getCurrentEnglishTest()?.maxScore || 9}
                      value={formData.englishTestScore}
                      onChange={(e) => handleInputChange('englishTestScore', e.target.value)}
                      placeholder={getCurrentEnglishTest()?.placeholder + '' || 'e.g., 6.5 / 90 / 58'}
                      className="w-full p-4 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all duration-200 hover:border-gray-300"
                    />
                  ) : (
                    <div className="w-full p-4 border-2 border-gray-200 rounded-xl bg-gray-50 text-gray-500">
                      No test selected
                    </div>
                  )}
                </div>

                <div className="md:col-span-2 lg:col-span-1">
                  <label className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-2">
                    <div className="w-8 h-8 rounded-lg bg-teal-50 border border-teal-100 flex items-center justify-center">
                      <DollarSign className="w-4 h-4 text-teal-600" />
                    </div>
                    Budget for tuition & living ({currencyInfo.currency})
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                      <span className="text-gray-500 font-medium">{currencyInfo.currency_symbol}</span>
                    </div>
                    <input
                      type="number"
                      value={formData.budget}
                      onChange={(e) => handleInputChange('budget', e.target.value)}
                      placeholder="e.g., 30000"
                      className="w-full p-4 pl-12 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all duration-200 hover:border-gray-300"
                    />
                  </div>
                </div>
              </div>

              {/* Calculate Button */}
              <button
                onClick={calculateEligibility}
                disabled={loading}
                className={`w-full bg-linear-to-r from-teal-600 to-blue-500 text-white py-4 px-8 rounded-xl font-semibold hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02] shadow-lg flex items-center justify-center gap-3 ${
                  loading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
                }`}
              >
                {loading ? (
                  <>
                    <Loader2 className="w-6 h-6 animate-spin" />
                    <span>AI is analyzing courses...</span>
                  </>
                ) : (
                  <>
                    <Brain className="w-6 h-6" />
                    <span>Get AI-Powered Analysis</span>
                    <ArrowRight className="w-6 h-6" />
                  </>
                )}
              </button>
            </div>
          </ModernCard>

          {/* Results Section */}
          {aiResults && (
            <div id="ai-results-section" className="space-y-8 animate-in fade-in">
              {/* AI Insights */}
              {renderAIInsights()}

              {/* User Profile Summary */}
              <ModernCard>
                <div className="p-8 border-b border-gray-200">
                  <h3 className="text-xl font-bold text-gray-900">Your Profile Summary</h3>
                </div>
                <div className="p-8">
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
                    {aiResults.user_profile.country && (
                      <div className="text-center">
                        <div className="w-12 h-12 rounded-xl bg-linear-to-r from-teal-500 to-blue-500 flex items-center justify-center mx-auto mb-3">
                          <Flag className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-sm text-gray-600 mb-1">Country</div>
                        <div className="font-semibold text-gray-900">{aiResults.user_profile.country}</div>
                      </div>
                    )}
                    {aiResults.user_profile.qualification && (
                      <div className="text-center">
                        <div className="w-12 h-12 rounded-xl bg-linear-to-r from-blue-500 to-cyan-500 flex items-center justify-center mx-auto mb-3">
                          <GraduationCap className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-sm text-gray-600 mb-1">Level</div>
                        <div className="font-semibold text-gray-900">{aiResults.user_profile.qualification}</div>
                      </div>
                    )}
                    {aiResults.user_profile.gpa && parseFloat(aiResults.user_profile.gpa) > 0 && (
                      <div className="text-center">
                        <div className="w-12 h-12 rounded-xl bg-linear-to-r from-emerald-500 to-teal-500 flex items-center justify-center mx-auto mb-3">
                          <Trophy className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-sm text-gray-600 mb-1">GPA</div>
                        <div className="font-semibold text-gray-900">{aiResults.user_profile.gpa}</div>
                      </div>
                    )}
                    {aiResults.user_profile.english_test_type && aiResults.user_profile.english_test_type !== 'none' && (
                      <div className="text-center">
                        <div className="w-12 h-12 rounded-xl bg-linear-to-r from-amber-500 to-orange-500 flex items-center justify-center mx-auto mb-3">
                          <Globe className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-sm text-gray-600 mb-1">English Test</div>
                        <div className="font-semibold text-gray-900">
                          {aiResults.user_profile.english_test_type.toUpperCase()}: {aiResults.user_profile.english_test_score}
                        </div>
                      </div>
                    )}
                    {aiResults.user_profile.budget && parseFloat(aiResults.user_profile.budget) > 0 && (
                      <div className="text-center">
                        <div className="w-12 h-12 rounded-xl bg-linear-to-r from-purple-500 to-pink-500 flex items-center justify-center mx-auto mb-3">
                          <DollarSign className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-sm text-gray-600 mb-1">Budget</div>
                        <div className="font-semibold text-gray-900">
                          {currencyInfo.currency_symbol}{parseFloat(aiResults.user_profile.budget).toLocaleString()}
                        </div>
                      </div>
                    )}
                    {aiResults.user_profile.major && (
                      <div className="text-center">
                        <div className="w-12 h-12 rounded-xl bg-linear-to-r from-pink-500 to-rose-500 flex items-center justify-center mx-auto mb-3">
                          <BookOpen className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-sm text-gray-600 mb-1">Major</div>
                        <div className="font-semibold text-gray-900">{aiResults.user_profile.major}</div>
                      </div>
                    )}
                  </div>
                </div>
              </ModernCard>

              {/* AI Results Header */}
              <ModernCard className="overflow-hidden">
                <div className="bg-linear-to-r from-teal-600 to-blue-500 p-8">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
                    <div className="flex items-center gap-4">
                      <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center">
                        <Brain className="w-7 h-7 text-white" />
                      </div>
                      <div>
                        <h2 className="text-2xl font-bold text-white">AI-Powered Program Recommendations</h2>
                        <p className="text-white/90 mt-1">
                          Showing {getCurrentPageCourses().length} of {totalCourses} analyzed courses (Page {currentPage} of {totalPages})
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <Badge className="bg-white/20! text-white! border-white/30!">
                        {totalCourses} AI Analyzed
                      </Badge>
                      <Badge className="bg-white/20! text-white! border-white/30!">
                        Client-side Pagination
                      </Badge>
                    </div>
                  </div>
                </div>
              </ModernCard>

              {/* Course Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                {getCurrentPageCourses().map(renderCourseCard)}
              </div>

              {/* Client-side Pagination */}
              <Pagination />
            </div>
          )}

          {/* No Results State */}
          {!loading && !aiResults && hasMinimumData() && (
            <ModernCard className="p-12 text-center">
              <div className="max-w-md mx-auto">
                <div className="w-24 h-24 bg-linear-to-br from-teal-100 to-blue-100 rounded-2xl mx-auto mb-8 flex items-center justify-center">
                  <Brain className="w-12 h-12 text-teal-600" />
                </div>
                <h3 className="text-3xl font-bold text-gray-900 mb-4">Ready for AI Analysis</h3>
                <p className="text-lg text-gray-600 mb-8">
                  Click the button below to get AI-powered eligibility analysis courses.
                  All courses will be loaded upfront for instant client-side pagination.
                </p>
                <button
                  onClick={calculateEligibility}
                  className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-8 py-4 rounded-xl font-semibold hover:shadow-xl hover:scale-105 transition-all duration-300 shadow-lg"
                >
                  Start AI Analysis
                </button>
              </div>
            </ModernCard>
          )}

          <TextDisplay 
            content={pageData?.top_content}
            className="prose prose-lg max-w-none sn-content"
          />

          {/* Score Breakdown Modal */}
          {showScoreBreakdown && (
            <ScoreBreakdown 
              course={showScoreBreakdown} 
              onClose={() => setShowScoreBreakdown(null)} 
            />
          )}

          {/* Features Section */}
          <div className="py-20 bg-white z-10">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
              <div className="text-center mb-16">
                <h2 className="text-4xl font-bold text-gray-900 mb-4">
                  Why Use Our{' '}
                  <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                    AI Eligibility Calculator?
                  </span>
                </h2>
                <p className="text-gray-600 text-lg max-w-3xl mx-auto">
                  Get intelligent insights and make data-driven decisions for your education abroad
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
                {features.map((feature, index) => (
                  <FeatureCard
                    key={index}
                    icon={feature.icon}
                    title={feature.title}
                    description={feature.description}
                    color={feature.color}
                  />
                ))}
              </div>
            </div>
          </div>

          {/* Tips Section */}
          <div className="mt-16 bg-linear-to-br from-teal-50 to-blue-50 rounded-3xl border border-teal-100 p-8">
            <h3 className="text-2xl font-bold text-gray-900 mb-8 flex items-center gap-3">
              <Zap className="w-7 h-7 text-teal-600" />
              Pro Tips for Better Results
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div className="space-y-4">
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-lg bg-linear-to-r from-teal-500 to-blue-500 flex items-center justify-center shrink-0">
                    <CheckCircle className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <h4 className="font-bold text-gray-900 mb-1">Courses Pre-loaded</h4>
                    <p className="text-gray-600 text-sm">We analyze courses upfront for instant client-side pagination and faster navigation.</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-lg bg-linear-to-r from-emerald-500 to-teal-500 flex items-center justify-center shrink-0">
                    <Target className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <h4 className="font-bold text-gray-900 mb-1">Set Realistic Budgets</h4>
                    <p className="text-gray-600 text-sm">Include living expenses and other costs for a complete financial picture.</p>
                  </div>
                </div>
              </div>
              <div className="space-y-4">
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-lg bg-linear-to-r from-blue-500 to-cyan-500 flex items-center justify-center shrink-0">
                    <Award className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <h4 className="font-bold text-gray-900 mb-1">Instant Pagination</h4>
                    <p className="text-gray-600 text-sm">Navigate through all analyzed courses instantly without waiting for API calls.</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-lg bg-linear-to-r from-amber-500 to-orange-500 flex items-center justify-center shrink-0">
                    <Globe className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <h4 className="font-bold text-gray-900 mb-1">Consider Multiple Countries</h4>
                    <p className="text-gray-600 text-sm">Try different country preferences to discover more options.</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <TextDisplay 
            content={pageData?.bottom_content}
            className="prose prose-lg max-w-none sn-content"
          />

          <FAQSection faqs={faqs} />

          {/* Final CTA */}
          <div className="mt-20 py-20 bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl">
            <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
              <h2 className="text-4xl font-bold text-white mb-6">
                Ready to Find Your Perfect Program?
              </h2>
              <p className="text-xl text-teal-100 mb-10 max-w-2xl mx-auto">
                Our AI analyzes courses for instant results with client-side pagination
              </p>
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                <button
                  onClick={resetCalculator}
                  className="group bg-white cursor-pointer text-teal-600 px-12 py-5 rounded-2xl text-lg font-bold shadow-2xl hover:shadow-3xl hover:scale-105 transition-all duration-300 flex items-center gap-3"
                >
                  <Brain className="animate-bounce" />
                  Start New Analysis
                  <ArrowRight className="transition-transform duration-300 group-hover:translate-x-2" />
                </button>
                
                <Link href={"/apply-online"}><button
                  className="group bg-white cursor-pointer text-teal-600 px-12 py-5 rounded-2xl text-lg font-bold shadow-2xl hover:shadow-3xl hover:scale-105 transition-all duration-300 flex items-center gap-3"
                >
                  <Sparkles className="w-5 h-5" />
                  Free Consultation?
                </button></Link>
              </div>

              {/* Guarantee Badge */}
              <div className="mt-12 inline-flex items-center gap-3 bg-white/10 backdrop-blur-sm px-8 py-4 rounded-full">
                <Shield className="text-white w-5 h-5" />
                <span className="text-white font-semibold">Courses Pre-analyzed • Instant Pagination • Personalized Recommendations</span>
              </div>
            </div>
          </div>
        </div>
      </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 AIEligibilityCalculator;