'use client';

import React, { useState, useEffect, Suspense, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import Image from 'next/image';
import Swal from 'sweetalert2';
import { 
  GraduationCap, 
  MapPin, 
  Users, 
  DollarSign, 
  Award, 
  Star, 
  ExternalLink, 
  Clock, 
  Globe, 
  TrendingUp,
  BookOpen,
  CheckCircle,
  XCircle,
  BarChart3,
  Sparkles,
  Trophy,
  Target,
  ClipboardList,
  Brain,
  ThumbsUp,
  Zap,
  User,
  Mail,
  Phone,
  Loader2,
  Save,
  Calendar,
  Building2,
  CalendarDays,
  Languages,
  Home,
  Send,
  Search,
  X,
  Plus,
  MessageSquare,
  HelpCircle,
  RefreshCw,
  ChevronRight,
  Shield
} from 'lucide-react';
import { searchApi } from '../../services/searchApi'

import TextDisplay from '../../components/clientcomponents/TextDisplay';
import FAQSection from '../../components/FAQSection';

// API Configuration
const API_BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:8000';
const COMPARISON_API_URL = `${process.env.NEXT_PUBLIC_PYTHON_APP_URL}/compare`;
const COMPARISON_STORE_API_URL = `${API_BASE_URL}/api/frontend/comparison/submit`;

console.log("Comparison API URL", COMPARISON_API_URL);
console.log("Comparison Store API URL", COMPARISON_STORE_API_URL);

// LocalStorage Keys
const LOCAL_STORAGE_KEYS = {
  USER_DATA: 'comparisonUserData',
  COMPARISON_TYPE: 'comparisonType',
  SELECTED_UNIVERSITIES: 'selectedUniversities',
  SELECTED_COURSES: 'selectedCourses',
  BOOKMARKED_COMPARISONS: 'bookmarkedComparisons'
};

// University and Course fields
const UNIVERSITY_FIELDS = [
  { 
    key: 'founded', 
    label: 'Founded In',
    icon: Calendar,
    color: 'text-teal-600'
  },
  { 
    key: 'type', 
    label: 'Institution Type',
    icon: Building2,
    color: 'text-teal-600',
    format: (val) => {
      if (!val) return '-';
      return val.split(' ').map(word => 
        word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
      ).join(' ');
    }
  },
  { 
    key: 'course_count', 
    label: 'Programs Offered',
    icon: BookOpen,
    color: 'text-teal-600',
    format: (val) => val ? `${val} Programs` : 'No Programs'
  },
  { 
    key: 'intake', 
    label: 'Intake',
    icon: CalendarDays,
    color: 'text-teal-600'
  },
  { 
    key: 'language', 
    label: 'Languages',
    icon: Languages,
    color: 'text-teal-600'
  },
  { 
    key: 'accommodation', 
    label: 'Accommodation',
    icon: Home,
    color: 'text-teal-600',
    format: (val) => {
      if (!val) return 'Not Available';
      if (val.toLowerCase() === 'yes') return 'Available';
      if (val.toLowerCase() === 'no') return 'Not Available';
      return val;
    }
  },
  { 
    key: 'address', 
    label: 'Address',
    icon: MapPin,
    color: 'text-teal-600'
  },
  { 
    key: 'total_students', 
    label: 'Student Body', 
    icon: Users,
    color: 'text-teal-600',
    format: (val) => val ? `${parseInt(val).toLocaleString()}+` : '-',
  },
  { 
    key: 'international_student', 
    label: 'International Students', 
    icon: Globe,
    color: 'text-blue-600',
    format: (val) => val ? `${val}+` : '-',
  },
  { 
    key: 'ranking', 
    label: 'Global Ranking', 
    icon: Trophy,
    color: 'text-amber-500',
    format: (val) => val || 'Not Ranked'
  },
  { 
    key: 'scholarship', 
    label: 'Scholarship',
    icon: Award,
    color: 'text-emerald-500',
    format: (val) => {
      return Number(val) === 1 ? 'Available' : 'Not Available';
    }
  },
  { 
    key: 'website', 
    label: 'Official Website', 
    icon: ExternalLink,
    color: 'text-teal-600',
    format: (val) => val ? (
      <a 
        href={val.startsWith('http') ? val : `https://${val}`} 
        target="_blank" 
        rel="noopener noreferrer" 
        className="inline-flex items-center gap-2 text-teal-600 hover:text-teal-700 transition-colors"
      >
        Visit Website <ExternalLink className="w-4 h-4" />
      </a>
    ) : '-' 
  }
];

const COURSE_FIELDS = [
  { 
    key: 'university', 
    label: 'Institution',
    icon: GraduationCap,
    color: 'text-teal-600'
  },
  { 
    key: 'qualification', 
    label: 'Degree Level',
    icon: Award,
    color: 'text-amber-500'
  },
  { 
    key: 'duration', 
    label: 'Course Duration', 
    icon: Clock,
    color: 'text-teal-600',
    format: (val) => {
      if (!val) return '-';
      const num = parseInt(val);
      if (isNaN(num)) return val;
      if (num >= 1 && num <= 9) {
        return `${num} year${num > 1 ? 's' : ''}`;
      }
      return `${num} month${num > 1 ? 's' : ''}`;
    }
  },
  { 
    key: 'fee_with_symbol', 
    label: 'Annual Fee', 
    icon: DollarSign,
    color: 'text-teal-600'
  },
  { 
    key: 'application_fee_with_symbol', 
    label: 'Application Fee', 
    icon: DollarSign,
    color: 'text-teal-600',
    format: (val) => val ? `${val}` : 'Free'
  },
  { 
    key: 'language', 
    label: 'Language of Instruction',
    icon: Globe,
    color: 'text-teal-600'
  },
  { 
    key: 'scholarship', 
    label: 'Scholarship',
    icon: Award,
    color: 'text-emerald-500',
    format: (val) => {
      return Number(val) === 1 ? 'Available' : 'Not Available';
    }
  }
];

// Modern User Data Modal Component matching the design
function UserDataModal({ isOpen, onClose, onSubmit, initialData = {}, isLoading = false }) {
  const [formData, setFormData] = useState({
    name: initialData.name || '',
    email: initialData.email || '',
    phone: initialData.phone || ''
  });

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

  if (!isOpen) return null;

  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 comparison 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="block 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={formData.name}
              onChange={(e) => setFormData({...formData, 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="block 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={formData.email}
              onChange={(e) => setFormData({...formData, 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="block 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={formData.phone}
              onChange={(e) => setFormData({...formData, 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>
  );
}

// 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 }) => {
  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',
    gray: 'bg-gray-100 text-gray-700 border-gray-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]}`}>
      {Icon && <Icon className="w-3.5 h-3.5" />}
      {children}
    </span>
  );
};

// Stats Card Component
const StatCard = ({ icon: Icon, number, label, color = 'teal' }) => {
  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'
  };

  return (
    <div className="text-center">
      <div className={`inline-flex items-center justify-center w-12 h-12 ${colorClasses[color]} text-white rounded-2xl mb-3`}>
        {Icon}
      </div>
      <div className="text-2xl font-bold text-gray-900 mb-1">{number}</div>
      <div className="text-gray-600 text-sm">{label}</div>
    </div>
  );
};

// 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">
      <ChevronRight className="text-gray-400" />
    </div>
  </div>
);

function ComparisonTool({pageData, faqs}) {
  const searchParams = useSearchParams();
  
  // State Management
  const [loading, setLoading] = useState(true);
  const [comparisonType, setComparisonType] = useState('university');
  const [aiLoading, setAiLoading] = useState(false);
  const [aiResults, setAiResults] = useState(null);
  const [animateStats, setAnimateStats] = useState(false);
  const [bookmarkedComparisons, setBookmarkedComparisons] = useState([]);
  
  // Email State
  const [isSendingEmail, setIsSendingEmail] = useState(false);
  const [emailStatus, setEmailStatus] = useState(null);
  
  // Search State
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [isSearchLoading, setIsSearchLoading] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  
  // Selected Items State
  const [selectedUniversities, setSelectedUniversities] = useState([]);
  const [selectedCourses, setSelectedCourses] = useState([]);
  
  // User Data State
  const [userData, setUserData] = useState(null);
  const [showUserModal, setShowUserModal] = useState(false);
  const [isStoringData, setIsStoringData] = useState(false);

  // Refs for click outside detection
  const searchContainerRef = useRef(null);
  const dropdownRef = useRef(null);

  // Load data from localStorage on component mount
  useEffect(() => {
    const loadFromLocalStorage = () => {
      try {
        const userDataStr = localStorage.getItem(LOCAL_STORAGE_KEYS.USER_DATA);
        if (userDataStr) setUserData(JSON.parse(userDataStr));
        
        const comparisonTypeStr = localStorage.getItem(LOCAL_STORAGE_KEYS.COMPARISON_TYPE);
        if (comparisonTypeStr) setComparisonType(JSON.parse(comparisonTypeStr));
        
        const universitiesStr = localStorage.getItem(LOCAL_STORAGE_KEYS.SELECTED_UNIVERSITIES);
        if (universitiesStr) {
          const data = JSON.parse(universitiesStr);
          setSelectedUniversities(Array.isArray(data) ? data.filter(item => item && typeof item === 'object') : []);
        }
        
        const coursesStr = localStorage.getItem(LOCAL_STORAGE_KEYS.SELECTED_COURSES);
        if (coursesStr) {
          const data = JSON.parse(coursesStr);
          setSelectedCourses(Array.isArray(data) ? data.filter(item => item && typeof item === 'object') : []);
        }
        
        const bookmarksStr = localStorage.getItem(LOCAL_STORAGE_KEYS.BOOKMARKED_COMPARISONS);
        if (bookmarksStr) setBookmarkedComparisons(JSON.parse(bookmarksStr));
      } catch (error) {
        console.error('Error loading from localStorage:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadFromLocalStorage();
  }, []);

  // Save data to localStorage whenever it changes
  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem(LOCAL_STORAGE_KEYS.COMPARISON_TYPE, JSON.stringify(comparisonType));
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  }, [comparisonType]);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem(LOCAL_STORAGE_KEYS.SELECTED_UNIVERSITIES, JSON.stringify(selectedUniversities));
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  }, [selectedUniversities]);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem(LOCAL_STORAGE_KEYS.SELECTED_COURSES, JSON.stringify(selectedCourses));
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  }, [selectedCourses]);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem(LOCAL_STORAGE_KEYS.BOOKMARKED_COMPARISONS, JSON.stringify(bookmarkedComparisons));
    } catch (error) {
      console.error('Error saving bookmarks:', error);
    }
  }, [bookmarkedComparisons]);

  // Save user data to localStorage
  const saveUserData = (data) => {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem(LOCAL_STORAGE_KEYS.USER_DATA, JSON.stringify(data));
      setUserData(data);
    } catch (error) {
      console.error('Error saving user data:', error);
    }
  };

  // Load user data from localStorage helper
  const loadUserDataFromLocalStorage = () => {
    if (typeof window === 'undefined') return null;
    try {
      const data = localStorage.getItem(LOCAL_STORAGE_KEYS.USER_DATA);
      return data ? JSON.parse(data) : null;
    } catch (error) {
      console.error('Error loading user data:', error);
      return null;
    }
  };

  // Store comparison data to backend
  const storeComparisonData = async (userData) => {
    setIsStoringData(true);
    try {
      const currentSelectedItems = getCurrentSelectedItems();
      const nonEmptyItems = currentSelectedItems.filter(item => item.id && item.id !== '');
      const comparedItemIds = nonEmptyItems.map(item => item.id);
      
      if (comparedItemIds.length < 2) {
        throw new Error('At least 2 items required for comparison');
      }
      
      const payload = {
        name: userData.name,
        email: userData.email,
        phone: userData.phone,
        comparison_type: comparisonType,
        compared_items: comparedItemIds
      };
      
      console.log('Sending comparison data to store:', payload);
      
      const response = await fetch(COMPARISON_STORE_API_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload)
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }
      
      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.message || 'Failed to store comparison data');
      }
      
      console.log('Comparison data stored successfully:', result);
      return result;
      
    } catch (error) {
      console.error('Error storing comparison data:', error);
      throw error;
    } finally {
      setIsStoringData(false);
    }
  };

  // Handle user data submission
  const handleUserDataSubmit = async (formData) => {
    try {
      saveUserData(formData);
      const result = await storeComparisonData(formData);
      return result;
    } catch (error) {
      console.error('Error in user data submission:', error);
      throw error;
    }
  };

  // Main function to handle AI comparison button click
  const handleGetAIComparison = async () => {
    const currentSelectedItems = getCurrentSelectedItems();
    const nonEmptyItems = currentSelectedItems.filter(item => item.id && item.id !== '');
    
    if (nonEmptyItems.length < 2) {
      Swal.fire({
        icon: 'warning',
        title: 'Need More Items',
        text: 'Please select at least 2 items for AI comparison',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    const storedUserData = loadUserDataFromLocalStorage();
    
    if (!storedUserData || !storedUserData.name || !storedUserData.email || !storedUserData.phone) {
      setShowUserModal(true);
      return;
    }
    
    await proceedWithAIComparison(storedUserData);
  };

  // Proceed with AI comparison after user data is handled
  const proceedWithAIComparison = async (userDataToStore = null) => {
    setAiLoading(true);
    try {
      if (userDataToStore) {
        try {
          await handleUserDataSubmit(userDataToStore);
        } catch (storageError) {
          console.error('Storage failed, stopping AI comparison:', storageError);
          Swal.fire({
            icon: 'error',
            title: 'Storage Failed',
            text: 'Could not save your data. Please try again.',
            confirmButtonColor: '#0B6D76'
          });
          setAiLoading(false);
          setShowUserModal(false);
          return;
        }
      }
      
      const currentSelectedItems = getCurrentSelectedItems();
      const nonEmptyItems = currentSelectedItems.filter(item => item.id && item.id !== '');
      
      console.log('Calling AI comparison with items:', nonEmptyItems.map(item => item.id));
      
      const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/comparison`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          item_ids: nonEmptyItems.map(item => item.id),
          comparison_type: comparisonType,
          user_context: {
            timestamp: new Date().toISOString()
          }
        })
      });

      console.log('AI Response status:', response.status);

      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status} - ${response.statusText}`);
      }

      const data = await response.json();
      console.log('AI API Response:', data);
      
      const isSuccessful = data.metadata?.api_success !== false && 
                          data.metadata?.fallback_used !== true;
      
      if (isSuccessful) {
        setAiResults(data);
        Swal.fire({
          icon: 'success',
          title: 'AI Analysis Complete!',
          text: 'Our AI has analyzed and compared your selections',
          timer: 2000,
          showConfirmButton: false,
          background: '#ffffff',
          color: '#1f2937'
        });
      } else {
        setAiResults(data);
        Swal.fire({
          icon: 'info',
          title: 'Basic Analysis',
          text: 'Using basic comparison analysis (AI service limited)',
          timer: 3000,
          showConfirmButton: false,
          background: '#ffffff',
          color: '#1f2937'
        });
      }
    } catch (error) {
      console.error('AI Comparison Error:', error);
      
      const currentSelectedItems = getCurrentSelectedItems();
      const nonEmptyItems = currentSelectedItems.filter(item => item.id && item.id !== '');
      
      const fallbackResponse = {
        comparison_id: `fallback_${Date.now()}`,
        timestamp: new Date().toISOString(),
        comparison_type: comparisonType,
        items_compared: nonEmptyItems.length,
        ai_analysis: {
          overview: "Basic comparison analysis overview",
          detailed_comparison: {
            sections: [{
              title: "Basic Comparison",
              content: "Due to technical limitations, we're showing a basic comparison. For detailed AI insights, please try again later.",
              key_points: []
            }]
          },
          top_recommendation: {
            name: "Unable to determine",
            reason: "Basic analysis mode",
            best_for: [],
            strengths: [],
            considerations: []
          },
          comparative_analysis: {
            ranking_order: [],
            key_differences: [],
            value_analysis: ""
          },
          final_advice: "Try the AI comparison again or check your connection."
        },
        metadata: {
          ai_model: "fallback",
          api_success: false,
          fallback_used: true,
          error: error.message
        }
      };
      
      setAiResults(fallbackResponse);
      
      Swal.fire({
        icon: 'error',
        title: 'Connection Issue',
        text: 'Using basic comparison. ' + error.message,
        confirmButtonColor: '#0B6D76',
        timer: 4000,
        background: '#ffffff',
        color: '#1f2937'
      });
    } finally {
      setAiLoading(false);
      setShowUserModal(false);
    }
  };

  // Handle modal submission
  const handleModalSubmit = async (formData) => {
    await proceedWithAIComparison(formData);
  };

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

    const currentSelectedItems = getCurrentSelectedItems();
    const nonEmptyItems = currentSelectedItems.filter(item => item.id && item.id !== '');
    
    if (nonEmptyItems.length < 2) {
      Swal.fire({
        icon: 'warning',
        title: 'Insufficient Data',
        text: 'Please select at least 2 items for email report',
        confirmButtonColor: '#0B6D76',
        background: '#ffffff',
        color: '#1f2937'
      });
      return;
    }

    const storedUserData = loadUserDataFromLocalStorage();
    if (!storedUserData || !storedUserData.email) {
      Swal.fire({
        icon: 'warning',
        title: 'Email Required',
        text: 'Please provide your email to send the comparison report',
        confirmButtonColor: '#0B6D76',
        showCancelButton: true,
        confirmButtonText: 'Enter Email',
        cancelButtonText: 'Cancel',
        background: '#ffffff',
        color: '#1f2937'
      }).then((result) => {
        if (result.isConfirmed) {
          setShowUserModal(true);
        }
      });
      return;
    }

    setIsSendingEmail(true);
    setEmailStatus(null);

    try {
      const response = await fetch('/api/frontend/comparison/send-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          comparisonType,
          selectedItems: nonEmptyItems,
          aiResults,
          userData: storedUserData,
        }),
      });

      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>Comparison report has been sent to:</p>
              <p class="font-semibold text-teal-600 mt-2">${storedUserData.email}</p>
              <p class="text-sm text-gray-600 mt-4">Check your inbox and spam folder</p>
            </div>
          `,
          confirmButtonColor: '#0B6D76',
          timer: 5000,
          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 {
      setIsSendingEmail(false);
    }
  };

  // Debounce function
  const useDebounce = (value, delay) => {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);

      return () => {
        clearTimeout(handler);
      };
    }, [value, delay]);

    return debouncedValue;
  };

  const debouncedSearchQuery = useDebounce(searchQuery, 300);

  // Click outside dropdown handler
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target) &&
          searchContainerRef.current && !searchContainerRef.current.contains(event.target)) {
        setShowDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Search effect - FIXED VERSION
  useEffect(() => {
    let isActive = true;
    
    const performSearch = async () => {
      if (!debouncedSearchQuery.trim()) {
        if (isActive) {
          setSearchResults([]);
          setShowDropdown(false);
        }
        return;
      }

      if (isActive) {
        setIsSearchLoading(true);
        setShowDropdown(true);
      }

      try {
        let results;
        if (comparisonType === 'university') {
          results = await searchApi.searchUniversities(debouncedSearchQuery);
        } else {
          results = await searchApi.searchCourses(debouncedSearchQuery);
        }
        
        if (isActive) {
          console.log('Search results received:', results.data);
          setSearchResults(results.data || []);
          setIsSearchLoading(false);
        }
      } catch (error) { 
        if (isActive) {
          console.error('Search error:', error);
          setSearchResults([]);
          setIsSearchLoading(false);
        }
      }
    };

    performSearch();

    return () => {
      isActive = false;
    };
  }, [debouncedSearchQuery, comparisonType]);

  // Clear AI results when selection changes
  useEffect(() => {
    setAiResults(null);
    setEmailStatus(null);
  }, [selectedUniversities, selectedCourses, comparisonType]);

  // Get current selected items
  const getCurrentSelectedItems = () => {
    return comparisonType === 'university' ? selectedUniversities : selectedCourses;
  };

  // Update selected items
  const updateSelectedItems = (items) => {
    if (comparisonType === 'university') {
      setSelectedUniversities(items);
    } else {
      setSelectedCourses(items);
    }
  };

  // Clear all comparison data
  const clearAllComparisonData = () => {
    Swal.fire({
      title: 'Clear All Data?',
      text: 'This will remove all selected items and comparisons.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#0B6D76',
      cancelButtonColor: '#6b7280',
      confirmButtonText: 'Yes, clear all',
      cancelButtonText: 'Cancel',
      background: '#ffffff',
      color: '#1f2937'
    }).then((result) => {
      if (result.isConfirmed) {
        setSelectedUniversities([]);
        setSelectedCourses([]);
        setBookmarkedComparisons([]);
        setComparisonType('university');
        setAiResults(null);
        setUserData(null);
        setEmailStatus(null);
        
        localStorage.removeItem(LOCAL_STORAGE_KEYS.SELECTED_UNIVERSITIES);
        localStorage.removeItem(LOCAL_STORAGE_KEYS.SELECTED_COURSES);
        localStorage.removeItem(LOCAL_STORAGE_KEYS.BOOKMARKED_COMPARISONS);
        localStorage.removeItem(LOCAL_STORAGE_KEYS.COMPARISON_TYPE);
        localStorage.removeItem(LOCAL_STORAGE_KEYS.USER_DATA);
        
        Swal.fire({
          title: 'Cleared!',
          text: 'All comparison data has been cleared.',
          icon: 'success',
          timer: 1500,
          showConfirmButton: false,
          background: '#ffffff',
          color: '#1f2937'
        });
      }
    });
  };

  // Handle add to compare
  const handleAddToCompare = (item) => {
    const currentSelected = getCurrentSelectedItems();
    
    if (currentSelected.some(selected => selected.id === item.id)) {
      return;
    }
    
    const emptySlotIndex = currentSelected.findIndex(selected => !selected.id || selected.id === '');
    
    if (emptySlotIndex !== -1) {
      const updatedSelected = [...currentSelected];
      updatedSelected[emptySlotIndex] = { ...item };
      updateSelectedItems(updatedSelected);
    } else if (currentSelected.length < 3) {
      const updatedSelected = [...currentSelected, { ...item }];
      updateSelectedItems(updatedSelected);
    } else {
      Swal.fire({
        icon: 'info',
        title: 'Maximum Reached',
        text: `You can compare up to 3 ${comparisonType === 'university' ? 'universities' : 'courses'} maximum`,
        timer: 2000,
        showConfirmButton: false,
        background: '#ffffff',
        color: '#1f2937'
      });
    }
    
    setShowDropdown(false);
    setSearchQuery('');
  };

  // Clear search when switching types
  useEffect(() => {
    setSearchQuery('');
    setSearchResults([]);
    setShowDropdown(false);
    setAiResults(null);
    setEmailStatus(null);
  }, [comparisonType]);

  // Handle remove from compare
  const handleRemoveFromCompare = (itemId) => {
    const currentSelected = getCurrentSelectedItems();
    const nonEmptyItems = currentSelected.filter(item => item.id && item.id !== '');
    
    if (nonEmptyItems.length <= 2) {
      const updatedSelected = currentSelected.map(item => 
        item.id === itemId ? { id: '' } : item
      );
      updateSelectedItems(updatedSelected);
    } else {
      const updatedSelected = currentSelected.filter(item => item.id !== itemId);
      updateSelectedItems(updatedSelected);
    }
    
    setAiResults(null);
    setEmailStatus(null);
  };

  const toggleBookmark = () => {
    if (!aiResults) return;
    
    const comparisonKey = aiResults.comparison_id || `cmp_${Date.now()}`;
    if (bookmarkedComparisons.includes(comparisonKey)) {
      setBookmarkedComparisons(bookmarkedComparisons.filter(k => k !== comparisonKey));
      Swal.fire({
        title: 'Removed!',
        text: 'Comparison removed from bookmarks',
        icon: 'success',
        timer: 1500,
        showConfirmButton: false,
        background: '#ffffff',
        color: '#1f2937'
      });
    } else {
      setBookmarkedComparisons([...bookmarkedComparisons, comparisonKey]);
      Swal.fire({
        title: 'Bookmarked!',
        text: 'Comparison saved for later',
        icon: 'success',
        timer: 1500,
        showConfirmButton: false,
        background: '#ffffff',
        color: '#1f2937'
      });
    }
  };

  const isBookmarked = () => {
    if (!aiResults) return false;
    const comparisonKey = aiResults.comparison_id || `cmp_${Date.now()}`;
    return bookmarkedComparisons.includes(comparisonKey);
  };

  // Render progress bar
  const renderProgressBar = (value, max, color = 'teal') => {
    const percentage = Math.min(100, Math.max(0, (value / max) * 100));
    
    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'
    };
    
    return (
      <div className="w-full bg-gray-100 rounded-full h-2 overflow-hidden">
        <div 
          className={`h-2 rounded-full ${colorClasses[color] || 'bg-linear-to-r from-teal-500 to-blue-500'}`}
          style={{ width: `${percentage}%` }}
        ></div>
      </div>
    );
  };

  // Render field value
  const renderFieldValue = (field, item) => {
    if (!item) {
      return <span className="text-gray-400">-</span>;
    }
    
    const value = item[field.key];
    
    if (value === null || value === undefined || value === '') {
      return <span className="text-gray-400">-</span>;
    }
    
    const formattedValue = field.format ? field.format(value, item) : (value || '-');
    
    if (field.visual && value && !isNaN(value)) {
      const numValue = parseInt(value);
      let maxValue = 100;
      
      if (field.key === 'total_students') {
        maxValue = 50000;
      } else if (field.key === 'yearly_fee') {
        maxValue = 100000;
      } else if (field.key === 'duration') {
        maxValue = 60;
      }
      
      return (
        <div className="group relative">
          <div className="font-semibold text-gray-900 mb-2">{formattedValue}</div>
          {renderProgressBar(numValue, maxValue, field.color?.includes('teal') ? 'teal' : 'blue')}
        </div>
      );
    }
    
    if (field.key === 'duration' && value) {
      return (
        <div className="font-semibold text-gray-900">
          {formattedValue}
        </div>
      );
    }
    
    return (
      <div className="font-medium text-gray-900">
        {formattedValue}
      </div>
    );
  };

  // Email Status Indicator
  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" />
          ) : (
            <XCircle 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>
    );
  };

  // Render AI Analysis Results - UPDATED for new response format
  const renderAIAnalysis = () => {
    if (!aiResults) return null;

    const { 
      ai_analysis, 
      metadata 
    } = aiResults;

    const isFallback = metadata?.fallback_used === true || metadata?.api_success === false;

    return (
      <div className="space-y-8 mb-12">
        {/* AI Analysis Header */}
        <ModernCard className="overflow-hidden">
          <div className={`p-8 ${isFallback ? 'bg-linear-to-r from-amber-500 to-orange-500' : 'bg-linear-to-r from-teal-600 to-blue-500'}`}>
            <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-14 h-14 rounded-xl flex items-center justify-center ${isFallback ? 'bg-white/20' : 'bg-white/20'}`}>
                  <Brain className="w-8 h-8 text-white" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-white">
                    {isFallback ? '📊 Basic Analysis' : '🤖 AI-Powered Analysis'}
                  </h2>
                  <p className="text-white/90 mt-1">
                    {comparisonType === 'university' ? 'University' : 'Course'} Comparison
                    {isFallback && ' (Basic Mode)'}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className={`px-4 py-2 ${isFallback ? 'bg-amber-100 border-amber-200' : 'bg-emerald-100 border-emerald-200'} rounded-full text-gray-900 text-sm font-medium border`}>
                  {isFallback ? 'Basic Analysis' : 'High Confidence'}
                </div>
                <button
                  onClick={handleSendEmail}
                  disabled={isSendingEmail}
                  className="px-6 py-3 bg-white text-gray-900 rounded-xl font-semibold hover:bg-gray-50 transition-all disabled:opacity-50 flex items-center gap-2 shadow-lg hover:shadow-xl"
                >
                  {isSendingEmail ? (
                    <>
                      <Loader2 className="w-5 h-5 animate-spin" />
                      Sending...
                    </>
                  ) : (
                    <>
                      <Send className="w-5 h-5" />
                      Email Report
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </ModernCard>

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

        {/* AI Overview */}
        <ModernCard className="p-8">
          <div className="flex items-center gap-3 mb-6">
            <div className="p-2 rounded-lg bg-teal-50 border border-teal-100">
              <Sparkles className="w-6 h-6 text-teal-600" />
            </div>
            <div>
              <h3 className="text-xl font-bold text-gray-900">
                {isFallback ? 'Basic Summary' : 'Executive Overview'}
              </h3>
              <p className="text-gray-600 text-sm">Key insights from our analysis</p>
            </div>
          </div>
          <div className="prose prose-lg max-w-none">
            <div className="text-gray-700 text-lg leading-relaxed bg-gray-50 p-6 rounded-xl border border-gray-100 whitespace-pre-line">
              {ai_analysis?.overview || "No overview available."}
            </div>
          </div>
        </ModernCard>

        {/* Top Recommendation */}
        {ai_analysis?.top_recommendation && (
          <ModernCard className="p-8 border-2 border-teal-100">
            <div className="flex items-center justify-between mb-8">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-lg bg-emerald-50 border border-emerald-100">
                  <Trophy className="w-6 h-6 text-emerald-600" />
                </div>
                <div>
                  <h3 className="text-xl font-bold text-gray-900">
                    {isFallback ? '⭐ Top Selection' : '🏆 Top Recommendation'}
                  </h3>
                  <p className="text-gray-600 text-sm">Our expert recommendation</p>
                </div>
              </div>
            </div>
            
            <div className="bg-linear-to-r from-teal-50 to-blue-50 rounded-2xl p-6 border border-teal-100">
              <div className="flex items-start gap-4">
                <div className="p-3 rounded-xl bg-white border border-teal-100">
                  <ThumbsUp className="w-8 h-8 text-amber-500" />
                </div>
                <div className="flex-1">
                  <h4 className="text-2xl font-bold text-gray-900 mb-2">
                    {ai_analysis.top_recommendation.name}
                  </h4>
                  <p className="text-gray-600 mb-4">
                    {ai_analysis.top_recommendation.reason}
                  </p>
                  
                  {/* Best For */}
                  {ai_analysis.top_recommendation.best_for && ai_analysis.top_recommendation.best_for.length > 0 && (
                    <div className="mb-4">
                      <h5 className="font-semibold text-gray-900 mb-2 flex items-center gap-2">
                        <Target className="w-4 h-4 text-teal-600" />
                        Best For:
                      </h5>
                      <div className="flex flex-wrap gap-2">
                        {ai_analysis.top_recommendation.best_for.map((type, index) => (
                          <Badge key={index} color="teal">
                            {type}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                  
                  {/* Strengths */}
                  {ai_analysis.top_recommendation.strengths && ai_analysis.top_recommendation.strengths.length > 0 && (
                    <div className="mb-4">
                      <h5 className="font-semibold text-gray-900 mb-2 flex items-center gap-2">
                        <Zap className="w-4 h-4 text-amber-600" />
                        Key Strengths:
                      </h5>
                      <ul className="space-y-2">
                        {ai_analysis.top_recommendation.strengths.map((strength, index) => (
                          <li key={index} className="flex items-start gap-2">
                            <CheckCircle className="w-4 h-4 text-emerald-500 mt-0.5 shrink-0" />
                            <span className="text-gray-700">{strength}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                  
                  {/* Considerations */}
                  {ai_analysis.top_recommendation.considerations && ai_analysis.top_recommendation.considerations.length > 0 && (
                    <div>
                      <h5 className="font-semibold text-gray-900 mb-2 flex items-center gap-2">
                        <HelpCircle className="w-4 h-4 text-blue-600" />
                        Important Considerations:
                      </h5>
                      <ul className="space-y-2">
                        {ai_analysis.top_recommendation.considerations.map((consideration, index) => (
                          <li key={index} className="flex items-start gap-2">
                            <div className="w-4 h-4 rounded-full bg-blue-100 flex items-center justify-center shrink-0 mt-0.5">
                              <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
                            </div>
                            <span className="text-gray-700">{consideration}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </ModernCard>
        )}

        {/* Detailed Comparison Sections */}
        {ai_analysis?.detailed_comparison?.sections && ai_analysis.detailed_comparison.sections.length > 0 && (
          <ModernCard className="p-8">
            <div className="flex items-center gap-3 mb-6">
              <div className="p-2 rounded-lg bg-blue-50 border border-blue-100">
                <ClipboardList className="w-6 h-6 text-blue-600" />
              </div>
              <div>
                <h3 className="text-xl font-bold text-gray-900">
                  {isFallback ? 'Basic Analysis Details' : 'Detailed Comparison'}
                </h3>
                <p className="text-gray-600 text-sm">In-depth analysis of key factors</p>
              </div>
            </div>
            <div className="space-y-6">
              {ai_analysis.detailed_comparison.sections.map((section, index) => (
                <div key={index} className="border border-gray-200 rounded-xl p-6 hover:border-teal-200 transition-colors">
                  <h4 className="text-lg font-bold text-gray-900 mb-3 flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-teal-500"></div>
                    {section.title}
                  </h4>
                  <p className="text-gray-700 mb-4 leading-relaxed">
                    {section.content}
                  </p>
                  {section.key_points && section.key_points.length > 0 && (
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h5 className="font-semibold text-gray-900 mb-2">Key Points:</h5>
                      <ul className="space-y-2">
                        {section.key_points.map((point, pointIndex) => (
                          <li key={pointIndex} className="flex items-start gap-2">
                            <div className="w-1.5 h-1.5 rounded-full bg-teal-500 mt-2 shrink-0"></div>
                            <span className="text-gray-700">{point}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </ModernCard>
        )}

        {/* Comparative Analysis */}
        {ai_analysis?.comparative_analysis && (
          <ModernCard className="p-8">
            <div className="flex items-center gap-3 mb-6">
              <div className="p-2 rounded-lg bg-amber-50 border border-amber-100">
                <BarChart3 className="w-6 h-6 text-amber-600" />
              </div>
              <div>
                <h3 className="text-xl font-bold text-gray-900">
                  Comparative Analysis
                </h3>
                <p className="text-gray-600 text-sm">Ranking and value comparison</p>
              </div>
            </div>
            
            {/* Ranking Order */}
            {ai_analysis.comparative_analysis.ranking_order && ai_analysis.comparative_analysis.ranking_order.length > 0 && (
              <div className="mb-6">
                <h4 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                  <TrendingUp className="w-4 h-4 text-teal-600" />
                  Ranking Order:
                </h4>
                <div className="space-y-3">
                  {ai_analysis.comparative_analysis.ranking_order.map((rank, index) => (
                    <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                      <div className="w-8 h-8 rounded-lg bg-linear-to-r from-teal-500 to-blue-500 flex items-center justify-center text-white font-bold">
                        {index + 1}
                      </div>
                      <span className="font-medium text-gray-900">{rank}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
            
            {/* Key Differences */}
            {ai_analysis.comparative_analysis.key_differences && ai_analysis.comparative_analysis.key_differences.length > 0 && (
              <div className="mb-6">
                <h4 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                  <Target className="w-4 h-4 text-blue-600" />
                  Key Differences:
                </h4>
                <div className="space-y-2">
                  {ai_analysis.comparative_analysis.key_differences.map((difference, index) => (
                    <div key={index} className="flex items-start gap-2">
                      <div className="w-1.5 h-1.5 rounded-full bg-blue-500 mt-2 shrink-0"></div>
                      <span className="text-gray-700">{difference}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
            
            {/* Value Analysis */}
            {ai_analysis.comparative_analysis.value_analysis && (
              <div>
                <h4 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                  <DollarSign className="w-4 h-4 text-emerald-600" />
                  Value Analysis:
                </h4>
                <div className="bg-emerald-50 border border-emerald-100 rounded-xl p-4">
                  <p className="text-gray-700">{ai_analysis.comparative_analysis.value_analysis}</p>
                </div>
              </div>
            )}
          </ModernCard>
        )}

        {/* Final Advice */}
        {ai_analysis?.final_advice && (
          <ModernCard className="p-8">
            <div className="flex items-center gap-3 mb-6">
              <div className="p-2 rounded-lg bg-emerald-50 border border-emerald-100">
                <MessageSquare className="w-6 h-6 text-emerald-600" />
              </div>
              <div>
                <h3 className="text-xl font-bold text-gray-900">
                  Final Advice & Next Steps
                </h3>
                <p className="text-gray-600 text-sm">Practical guidance for your decision</p>
              </div>
            </div>
            <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">
                {ai_analysis.final_advice}
              </div>
            </div>
          </ModernCard>
        )}
      </div>
    );
  };

  // Render comparison table (manual view)
  const renderComparisonTable = () => {
    const currentSelectedItems = getCurrentSelectedItems();
    const nonEmptyItems = currentSelectedItems.filter(item => item.id && item.id !== '');
    const items = nonEmptyItems.map(item => ({
      ...item,
      details: item
    }));
    
    const fields = comparisonType === 'university' ? UNIVERSITY_FIELDS : COURSE_FIELDS;
    const hasData = items.length >= 1;

    if (!hasData) {
      return (
        <ModernCard className="p-12 text-center">
          <div className="max-w-2xl 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">
              {comparisonType === 'university' ? 
                <GraduationCap className="w-12 h-12 text-teal-600" /> :
                <BookOpen className="w-12 h-12 text-teal-600" />
              }
            </div>
            <h3 className="text-3xl font-bold text-gray-900 mb-4">
              Start Comparing
            </h3>
            <p className="text-lg text-gray-600 mb-8">
              Select at least 2 {comparisonType === 'university' ? 'universities' : 'courses'} to see a detailed side-by-side comparison
            </p>
            
            <div className="grid md:grid-cols-2 gap-6 max-w-2xl mx-auto">
              <div className="p-6 bg-teal-50 rounded-2xl border border-teal-100">
                <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                  <Target className="w-5 h-5 text-teal-600" />
                  What to Compare
                </h4>
                <ul className="space-y-3 text-gray-700">
                  {comparisonType === 'university' ? (
                    <>
                      <li className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-emerald-500" />
                        Location & Campus
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-emerald-500" />
                        Rankings & Reputation
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-emerald-500" />
                        Scholarship Options
                      </li>
                    </>
                  ) : (
                    <>
                      <li className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-emerald-500" />
                        Course Fees & Duration
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-emerald-500" />
                        Entry Requirements
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-emerald-500" />
                        Accreditation Status
                      </li>
                    </>
                  )}
                </ul>
              </div>
              
              <div className="p-6 bg-blue-50 rounded-2xl border border-blue-100">
                <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                  <Sparkles className="w-5 h-5 text-blue-600" />
                  Pro Tips
                </h4>
                <ul className="space-y-3 text-gray-700">
                  <li className="flex items-center gap-2">
                    <TrendingUp className="w-4 h-4 text-teal-500" />
                    Compare 2-3 options
                  </li>
                  <li className="flex items-center gap-2">
                    <DollarSign className="w-4 h-4 text-emerald-500" />
                    Include living costs
                  </li>
                  <li className="flex items-center gap-2">
                    <Award className="w-4 h-4 text-amber-500" />
                    Check accreditation
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </ModernCard>
      );
    }

    return (
      <div className="space-y-8">
        {/* Selected Items Cards */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {currentSelectedItems.map((item, index) => (
            item.id && item.id !== '' ? (
              <ModernCard key={index} className="overflow-hidden hover:shadow-lg transition-all duration-300">
                <div className="relative h-48 bg-linear-to-br from-teal-600 to-blue-500">
                  <button
                    onClick={() => handleRemoveFromCompare(item.id)}
                    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"
                    aria-label="Remove comparison"
                  >
                    <X className="w-5 h-5" />
                  </button>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="w-28 h-28 bg-white rounded-2xl p-4 shadow-2xl transform rotate-3">
                      <Image
                        src={
                          item.image && item.image.startsWith('/')
                          ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com${item.image}`
                          : `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${item.image}` || "/default-image.jpg"
                        }
                        alt={item.name || item.title}
                        width={112}
                        height={112}
                        className="w-full h-full object-cover rounded-lg"
                      />
                    </div>
                  </div>
                </div>
                <div className="p-6">
                  <h3 className="text-xl font-bold text-gray-900 mb-2 line-clamp-2">
                    {item.name || item.title}
                  </h3>
                  {item.country && (
                    <p className="text-gray-600 flex items-center gap-2 mb-4">
                      <MapPin className="w-4 h-4 text-gray-400" />
                      {item.city}, {item.country}
                    </p>
                  )}
                  <div className="flex flex-wrap gap-2">
                    <Badge color="teal">
                      {item.type}
                    </Badge>
                    {item.ranking && (
                      <Badge color="amber" icon={Trophy}>
                        #{item.ranking}
                      </Badge>
                    )}
                    {item.scholarship && Number(item.scholarship) === 1 && (
                      <Badge color="emerald" icon={Award}>
                        Scholarship
                      </Badge>
                    )}
                  </div>
                </div>
              </ModernCard>
            ) : (
              <div key={index} className="bg-linear-to-br from-gray-50 to-gray-100 border-2 border-dashed border-gray-300 rounded-3xl p-8 flex flex-col items-center justify-center hover:border-teal-400 hover:bg-teal-50 transition-all duration-300 group cursor-pointer" onClick={() => setShowDropdown(true)}>
                <div className="text-center">
                  <div className="w-16 h-16 bg-linear-to-br from-teal-100 to-blue-100 rounded-2xl flex items-center justify-center mb-6 group-hover:from-teal-200 group-hover:to-blue-200 transition-colors mx-auto">
                    <Plus className="w-8 h-8 text-teal-600" />
                  </div>
                  <span className="text-gray-700 group-hover:text-teal-600 font-semibold text-lg">
                    Add {comparisonType === 'university' ? 'University' : 'Course'}
                  </span>
                  <p className="text-sm text-gray-500 mt-2">
                    Slot {index + 1}
                  </p>
                </div>
              </div>
            )
          ))}
        </div>

        {/* Comparison Table */}
        <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-4">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center">
                  <BarChart3 className="w-7 h-7 text-white" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-white">
                    Detailed Comparison
                  </h2>
                  <p className="text-white/90 mt-1">
                    Side-by-side analysis of {items.length} {comparisonType === 'university' ? 'universities' : 'courses'}
                  </p>
                </div>
              </div>
            </div>
          </div>
          
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr>
                  <th className="text-left p-6 bg-gray-50 font-semibold text-gray-900 min-w-[220px] border-r border-gray-200">
                    <div className="flex items-center gap-2">
                      <span>Criteria</span>
                      <HelpCircle className="w-4 h-4 text-gray-400" />
                    </div>
                  </th>
                  {currentSelectedItems.map((item, index) => (
                    <th key={index} className="p-6 text-center bg-gray-50 border-r border-gray-200 min-w-[220px] last:border-r-0">
                      {item.id && item.id !== '' ? (
                        <div className="space-y-2">
                          <div className="font-semibold text-gray-900 text-sm">
                            {item.name || item.title}
                          </div>
                          {(item.city || item.country) && (
                            <div className="text-xs text-gray-500">
                              {item.city ? `${item.city}, ` : ''}{item.country || ''}
                            </div>
                          )}
                        </div>
                      ) : (
                        <div className="text-gray-400 italic">
                          Empty Slot {index + 1}
                        </div>
                      )}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {fields.map((field, i) => {
                  const Icon = field.icon;
                  return (
                    <tr key={i} className={`hover:bg-gray-50 transition-colors ${i % 2 === 0 ? 'bg-white' : 'bg-gray-50/50'}`}>
                      <td className="p-6 border-r border-gray-200">
                        <div className="flex items-center gap-3">
                          <div className={`p-2 rounded-lg ${field.color.includes('teal') ? 'bg-teal-50 border border-teal-100' : field.color.includes('amber') ? 'bg-amber-50 border border-amber-100' : 'bg-gray-50 border border-gray-100'}`}>
                            <Icon className={`w-5 h-5 ${field.color}`} />
                          </div>
                          <span className="font-medium text-gray-900">
                            {field.label}
                          </span>
                        </div>
                      </td>
                      {currentSelectedItems.map((item, j) => (
                        <td key={j} className="p-6 text-center border-r border-gray-200 last:border-r-0">
                          <div className="min-h-[48px] flex items-center justify-center">
                            {item.id && item.id !== '' ? (
                              renderFieldValue(field, item)
                            ) : (
                              <span className="text-gray-300">—</span>
                            )}
                          </div>
                        </td>
                      ))}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </ModernCard>
      </div>
    );
  };

  // Features array
  const features = [
    {
      icon: Shield,
      title: "AI-Powered Analysis",
      description: "Get intelligent insights using advanced machine learning algorithms",
      color: "from-teal-500 to-blue-500"
    },
    {
      icon: Brain,
      title: "Smart Recommendations",
      description: "Receive personalized recommendations based on your preferences",
      color: "from-blue-500 to-cyan-400"
    },
    {
      icon: BarChart3,
      title: "Detailed Comparison",
      description: "Side-by-side analysis of all key factors and metrics",
      color: "from-emerald-500 to-teal-400"
    },
    {
      icon: Send,
      title: "Email Reports",
      description: "Get comprehensive reports delivered to your inbox",
      color: "from-amber-500 to-orange-400"
    }
  ];

  // Steps array
  const steps = [
    {
      number: "01",
      title: "Select Items",
      description: "Choose 2-3 universities or courses to compare",
      icon: <Plus className="w-5 h-5" />
    },
    {
      number: "02",
      title: "AI Analysis",
      description: "Our AI analyzes all factors and provides insights",
      icon: <Brain className="w-5 h-5" />
    },
    {
      number: "03",
      title: "Review Results",
      description: "Get detailed comparison tables and recommendations",
      icon: <BarChart3 className="w-5 h-5" />
    },
    {
      number: "04",
      title: "Make Decision",
      description: "Use insights to make informed educational choices",
      icon: <CheckCircle className="w-5 h-5" />
    }
  ];

  // Main render
  return (
    <>
      <UserDataModal
        isOpen={showUserModal}
        onClose={() => setShowUserModal(false)}
        onSubmit={handleModalSubmit}
        initialData={userData || {}}
        isLoading={isStoringData || aiLoading}
      />
      
      <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
        {/* Hero Section */}
        <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 Comparison Tool
              </div>

              {/* Main Heading */}
              <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-6 leading-tight">
                Compare{' '}
                <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  {comparisonType === 'university' ? 'Universities' : 'Courses'}
                </span>{' '}
                <br />
                with UniversitiesPage AI
              </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>

              {/* Comparison Type Tabs - MOVED ABOVE SEARCH */}
              <div className="max-w-md mx-auto mb-8">
                <div className="bg-white border-2 border-gray-200 rounded-2xl p-1 shadow-sm">
                  <div className="flex">
                    <button
                      onClick={() => setComparisonType('university')}
                      className={`flex-1 py-3 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
                        comparisonType === 'university' 
                          ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                          : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                      }`}
                    >
                      <GraduationCap className="w-5 h-5" />
                      Universities
                    </button>
                    <button
                      onClick={() => setComparisonType('course')}
                      className={`flex-1 py-3 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
                        comparisonType === 'course' 
                          ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                          : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                      }`}
                    >
                      <BookOpen className="w-5 h-5" />
                      Courses
                    </button>
                  </div>
                </div>
              </div>

              {/* Search Bar */}
              <div className="max-w-2xl mx-auto mb-8">
                <div className="relative" ref={searchContainerRef}>
                  <div className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400">
                    <Search className="w-5 h-5" />
                  </div>
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onFocus={() => {
                      if (searchQuery) {
                        setShowDropdown(true);
                      }
                    }}
                    placeholder={
                      comparisonType === 'university'
                        ? "Search universities by name, location, or ranking..."
                        : "Search courses by name, institution, or field..."
                    }
                    className="w-full pl-12 pr-24 py-4 bg-white border-2 border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent text-lg shadow-lg hover:shadow-xl transition-shadow duration-300"
                  />
                  <button
                    onClick={() => setShowDropdown(true)}
                    className="absolute right-2 top-1/2 transform -translate-y-1/2 bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-2 rounded-xl font-semibold hover:shadow-lg hover:scale-105 transition-all duration-300"
                  >
                    Search
                  </button>
                </div>

                {/* Search Results Dropdown - POSITIONED RELATIVE TO SEARCH CONTAINER */}
                {showDropdown && (
                  <div 
                    ref={dropdownRef}
                    className="absolute left-1/2 transform -translate-x-1/2 w-full max-w-2xl mt-2 bg-white rounded-2xl shadow-2xl border border-gray-200 max-h-96 overflow-y-auto z-50"
                  >
                    {isSearchLoading ? (
                      <div className="p-4 text-center text-gray-600">
                        <Loader2 className="w-6 h-6 animate-spin mx-auto mb-2 text-teal-600" />
                        Searching...
                      </div>
                    ) : searchResults.filter(item => !getCurrentSelectedItems().some(selected => selected.id === item.id)).length === 0 ? (
                      <div className="p-4 text-center text-gray-600">
                        {searchResults.length === 0 && searchQuery
                          ? `No ${comparisonType === 'university' ? 'universities' : 'courses'} found for "${searchQuery}"`
                          : 'All results are already selected'
                        }
                      </div>
                    ) : (
                      <div className="py-2">
                        <div className="px-4 py-2 border-b border-gray-200 bg-gray-50">
                          <div className="text-sm font-semibold text-gray-700">
                            Found {searchResults.filter(item => !getCurrentSelectedItems().some(selected => selected.id === item.id)).length} results
                          </div>
                        </div>
                        {searchResults
                          .filter(item => !getCurrentSelectedItems().some(selected => selected.id === item.id))
                          .map((item) => (
                            <div
                              key={item.id}
                              className="dropdown-item flex items-center justify-between p-4 hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-b-0 cursor-pointer"
                              onClick={() => handleAddToCompare(item)}
                            >
                              <div className="flex-1 text-left mr-4">
                                <div className="font-semibold text-gray-900">{item.name || item.title}</div>
                                {item.location && (
                                  <div className="text-sm text-gray-600 mt-1">{item.location}</div>
                                )}
                                {item.duration && (
                                  <div className="text-sm text-gray-600 mt-1">Duration: {item.duration}</div>
                                )}
                                {item.country && (
                                  <div className="text-sm text-gray-600 mt-1">📍 {item.country}</div>
                                )}
                              </div>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleAddToCompare(item);
                                }}
                                className="px-4 py-2 rounded-xl font-medium transition-all bg-linear-to-r from-teal-600 to-blue-500 text-white hover:opacity-90 shadow-sm"
                              >
                                Add
                              </button>
                            </div>
                          ))
                        }
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* AI Compare Button */}
              <div className="text-center mt-12">
                <button
                  onClick={handleGetAIComparison}
                  disabled={aiLoading || getCurrentSelectedItems().filter(item => item.id).length < 2}
                  className={`px-12 py-4 rounded-2xl font-semibold text-lg transition-all duration-300 flex items-center gap-3 mx-auto shadow-lg hover:shadow-xl ${
                    getCurrentSelectedItems().filter(item => item.id).length >= 2
                      ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white cursor-pointer hover:opacity-90'
                      : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                  }`}
                >
                  {aiLoading ? (
                    <>
                      <Loader2 className="w-6 h-6 animate-spin" />
                      Analyzing with AI...
                    </>
                  ) : (
                    <>
                      <Brain className="w-6 h-6" />
                      Get AI-Powered Comparison
                    </>
                  )}
                </button>
                <p className="text-gray-600 text-sm mt-3">
                  {getCurrentSelectedItems().filter(item => item.id).length >= 2 
                    ? `Ready to compare ${getCurrentSelectedItems().filter(item => item.id).length} items with AI`
                    : 'Select at least 2 items for AI comparison'
                  }
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20">
          {/* Clear All Button */}
          <div className="flex justify-end mb-6">
            <button
              onClick={clearAllComparisonData}
              className="px-6 py-3 bg-linear-to-r from-red-500 to-red-600 text-white rounded-xl font-semibold hover:shadow-lg hover:scale-105 transition-all duration-300 flex items-center gap-2"
            >
              <RefreshCw className="w-5 h-5" />
              Clear All
            </button>
          </div>

          {/* AI Results */}
          {aiResults && renderAIAnalysis()}

          {/* Cards and Comparison Table */}
          {renderComparisonTable()}

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

          {/* 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 Comparison Tool?
                  </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
                </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>

          {/* How It Works 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" />
              How It Works
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
              {steps.map((step, index) => (
                <div key={index} className="flex flex-col items-center text-center">
                  <div className="w-16 h-16 bg-linear-to-r from-teal-500 to-blue-500 text-white rounded-2xl flex items-center justify-center font-bold text-xl mb-4">
                    {step.number}
                  </div>
                  <h4 className="text-lg font-bold text-gray-900 mb-2">{step.title}</h4>
                  <p className="text-gray-600 text-sm">{step.description}</p>
                </div>
              ))}
            </div>
          </div>

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

          {/* Tips Section */}
          <div className="mt-16">
            <div className="text-center mb-8">
              <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100 mb-4">
                <Sparkles className="w-4 h-4 text-teal-600" />
                <span className="text-sm font-medium text-teal-700">Expert Tips</span>
              </div>
              <h3 className="text-3xl font-bold text-gray-900 mb-4">
                Make Informed Decisions
              </h3>
              <p className="text-gray-600 max-w-2xl mx-auto">
                Follow these expert recommendations to choose the best option for your educational journey
              </p>
            </div>
            
            <div className="grid md:grid-cols-2 gap-8">
              <ModernCard className="p-8">
                <div className="flex items-center gap-3 mb-6">
                  <div className="p-2 rounded-lg bg-teal-50 border border-teal-100">
                    <Target className="w-6 h-6 text-teal-600" />
                  </div>
                  <h4 className="text-xl font-bold text-gray-900">
                    {comparisonType === 'university' ? 'University Selection' : 'Course Selection'}
                  </h4>
                </div>
                <ul className="space-y-4">
                  {comparisonType === 'university' ? (
                    <>
                      <li className="flex items-start gap-3">
                        <div className="w-6 h-6 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <CheckCircle className="w-4 h-4 text-emerald-600" />
                        </div>
                        <span className="text-gray-700">Higher rankings often indicate better resources and global recognition</span>
                      </li>
                      <li className="flex items-start gap-3">
                        <div className="w-6 h-6 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <Award className="w-4 h-4 text-emerald-600" />
                        </div>
                        <span className="text-gray-700">Explore scholarship options to significantly reduce education costs</span>
                      </li>
                      <li className="flex items-start gap-3">
                        <div className="w-6 h-6 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <Users className="w-4 h-4 text-emerald-600" />
                        </div>
                        <span className="text-gray-700">Higher international student ratios often mean better cultural diversity</span>
                      </li>
                    </>
                  ) : (
                    <>
                      <li className="flex items-start gap-3">
                        <div className="w-6 h-6 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <Clock className="w-4 h-4 text-emerald-600" />
                        </div>
                        <span className="text-gray-700">Compare course durations against yearly fees for total cost analysis</span>
                      </li>
                      <li className="flex items-start gap-3">
                        <div className="w-6 h-6 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <Star className="w-4 h-4 text-emerald-600" />
                        </div>
                        <span className="text-gray-700">Student reviews provide authentic insights into course quality and teaching</span>
                      </li>
                      <li className="flex items-start gap-3">
                        <div className="w-6 h-6 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <Target className="w-4 h-4 text-emerald-600" />
                        </div>
                        <span className="text-gray-700">Verify entry requirements match your academic background and qualifications</span>
                      </li>
                    </>
                  )}
                </ul>
              </ModernCard>
              
              <ModernCard className="p-8">
                <div className="flex items-center gap-3 mb-6">
                  <div className="p-2 rounded-lg bg-blue-50 border border-blue-100">
                    <Trophy className="w-6 h-6 text-blue-600" />
                  </div>
                  <h4 className="text-xl font-bold text-gray-900">
                    Best Practices
                  </h4>
                </div>
                <ul className="space-y-4">
                  <li className="flex items-start gap-3">
                    <div className="w-6 h-6 rounded-full bg-teal-100 flex items-center justify-center shrink-0 mt-0.5">
                      <ExternalLink className="w-4 h-4 text-teal-600" />
                    </div>
                    <span className="text-gray-700">Always verify information directly with official institution websites</span>
                  </li>
                  <li className="flex items-start gap-3">
                    <div className="w-6 h-6 rounded-full bg-teal-100 flex items-center justify-center shrink-0 mt-0.5">
                      <DollarSign className="w-4 h-4 text-teal-600" />
                    </div>
                    <span className="text-gray-700">Factor in living costs, accommodation, and other expenses beyond tuition</span>
                  </li>
                  <li className="flex items-start gap-3">
                    <div className="w-6 h-6 rounded-full bg-teal-100 flex items-center justify-center shrink-0 mt-0.5">
                      <Award className="w-4 h-4 text-teal-600" />
                    </div>
                    <span className="text-gray-700">Verify program accreditation and global recognition for career prospects</span>
                  </li>
                  <li className="flex items-start gap-3">
                    <div className="w-6 h-6 rounded-full bg-teal-100 flex items-center justify-center shrink-0 mt-0.5">
                      <TrendingUp className="w-4 h-4 text-teal-600" />
                    </div>
                    <span className="text-gray-700">Research graduate employment rates and alumni success stories</span>
                  </li>
                </ul>
              </ModernCard>
            </div>
          </div>

          <FAQSection faqs = {faqs} />

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

          {/* 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 Make an Informed Decision?
              </h2>
              <p className="text-xl text-teal-100 mb-10 max-w-2xl mx-auto">
                Let our AI help you compare and choose the best educational option for your future
              </p>
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                <button
                  onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
                  className="group bg-white 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 Comparison
                  <ChevronRight className="transition-transform duration-300 group-hover:translate-x-2" />
                </button>
                
                <button
                  onClick={handleGetAIComparison}
                  disabled={getCurrentSelectedItems().filter(item => item.id).length < 2}
                  className="px-10 py-5 border-2 border-white/30 text-white rounded-2xl font-semibold hover:bg-white/10 transition-all duration-300 flex items-center gap-2 disabled:opacity-50"
                >
                  <BarChart3 className="w-5 h-5" />
                  Get AI Analysis
                </button>
              </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">AI-Powered Analysis • Data-Driven Insights</span>
              </div>
            </div>
          </div>
        </main>
      </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 function ComparisonPage({pageData, faqs}) {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-linear-to-b from-gray-50 to-white flex items-center justify-center">
        <div className="text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-linear-to-r from-teal-600 to-blue-500 mb-6">
            <Brain className="w-8 h-8 text-white animate-pulse" />
          </div>
          <h2 className="text-2xl font-semibold text-gray-800 mb-2">Loading AI Comparison Tool</h2>
          <p className="text-gray-600">Preparing your intelligent comparison experience...</p>
        </div>
      </div>
    }>
      <ComparisonTool 
      pageData={pageData}
      faqs={faqs}
      />
    </Suspense>
  );
}