// app/students/components/ForeignStudentsListing.jsx
'use client';

import React, { useState, useEffect, useCallback } from 'react';
import StudentCard from './StudentCard';
import StudentModal from './StudentModal';
import BookingModal from '../../components/organisms/BookingModal';
import Pagination from './Pagination';
import SearchFilters from './SearchFilters';
import { 
  Users, 
  Globe, 
  Filter,
  DollarSign,
  Sparkles,
  Award,
  Target,
  RefreshCw,
  ChevronRight,
  Star,
  Shield,
  Clock,
  CheckCircle,
  GraduationCap,
  Globe as GlobeIcon,
  MapPin,
  Calendar,
  MessageSquare,
  Phone,
  Mail,
  BookOpen,
  Languages,
  Zap
} from 'lucide-react';
import Swal from 'sweetalert2';

const API_BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
const STUDENTS_PER_PAGE = 9;

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

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

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

  return debouncedValue;
}

export default function ForeignStudentsListing() {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalStudents, setTotalStudents] = useState(0);
  const [selectedStudent, setSelectedStudent] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false);
  const [bookingStudent, setBookingStudent] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filters, setFilters] = useState({
    country: '',
    education: '',
    gender: '',
    minRate: '',
    maxRate: ''
  });
  const [countries, setCountries] = useState([]);
  const [lastUpdated, setLastUpdated] = useState(null);
  const [searchInput, setSearchInput] = useState('');
  const [isHovered, setIsHovered] = useState(false);

  // Debounced search query
  const debouncedSearchQuery = useDebounce(searchInput, 500);

  // Fetch students with pagination and filters
  const fetchStudents = useCallback(async (page = 1) => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: page.toString(),
        limit: STUDENTS_PER_PAGE.toString(),
        ...(debouncedSearchQuery && { search: debouncedSearchQuery }),
        ...(filters.country && { country: filters.country }),
        ...(filters.education && { education: filters.education }),
        ...(filters.gender && { gender: filters.gender }),
        ...(filters.minRate && { minRate: filters.minRate }),
        ...(filters.maxRate && { maxRate: filters.maxRate }),
        ...(filters.is_verified && { is_verified: filters.is_verified })
      });

      const response = await fetch(`${API_BASE_URL}/api/frontend/foreign-students?${queryParams}`);
      const data = await response.json();
      
      if (data.success) {
        setStudents(data.students || []);
        setTotalPages(data.pagination?.totalPages || 1);
        setTotalStudents(data.pagination?.totalCount || 0);
        setCurrentPage(data.pagination?.currentPage || 1);
        setCountries(data.countries || []);
        setLastUpdated(new Date());
      } else {
        console.error('API Error:', data.error);
        setStudents(getMockStudents());
        setTotalPages(3);
        setTotalStudents(27);
        setCountries(getMockCountries());
      }
    } catch (error) {
      console.error('Error fetching students:', error);
      setStudents(getMockStudents());
      setTotalPages(3);
      setTotalStudents(27);
      setCountries(getMockCountries());
    } finally {
      setLoading(false);
    }
  }, [debouncedSearchQuery, filters]);

  // Auto-fetch when debounced search or filters change
  useEffect(() => {
    fetchStudents(currentPage);
  }, [fetchStudents, currentPage]);

  // Reset to page 1 when filters or search changes
  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearchQuery, filters]);

  const handlePageChange = (page) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleViewDetails = (student) => {
    setSelectedStudent(student);
    setIsModalOpen(true);
  };

  const handleBookAppointment = async (student) => {
    try {
      const response = await fetch(
        `${API_BASE_URL}/api/frontend/userdashboard/foreign-student-availability/${student.id}`,
        {
          method: 'GET',
          credentials: 'include'
        }
      );

      if (!response.ok) {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to check availability.',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }

      const data = await response.json();
      
      if (!data.success || !data.schedule) {
        Swal.fire({
          icon: 'error',
          title: 'Not Available',
          text: 'This student has not set their availability yet.',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }

      setBookingStudent(student);
      setIsBookingModalOpen(true);
    } catch (error) {
      console.error('Error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load availability. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleBookingSuccess = () => {
    Swal.fire({
      icon: 'success',
      title: 'Success!',
      text: 'Appointment booked successfully.',
      confirmButtonColor: '#0B6D76'
    });
  };

  const handleSearch = (query) => {
    setSearchInput(query);
    setSearchQuery(query);
  };

  const handleFilterChange = (newFilters) => {
    setFilters(newFilters);
  };

  const clearAll = () => {
    setSearchInput('');
    setSearchQuery('');
    setFilters({
      country: '',
      education: '',
      gender: '',
      minRate: '',
      maxRate: '',
    });
    setCurrentPage(1);
  };

  const refreshData = () => {
    fetchStudents(currentPage);
  };

  const getMockStudents = () => {
    return Array.from({ length: STUDENTS_PER_PAGE }, (_, i) => ({
      id: i + 1,
      name: `Student ${i + 1}`,
      email: `student${i + 1}@example.com`,
      phone: `+1 (555) 123-${4567 + i}`,
      country_id: (i % 5) + 1,
      timezone: 'UTC',
      about_me: 'Passionate international student with experience in cross-cultural communication.',
      profile_picture: `https://randomuser.me/api/portraits/${i % 2 === 0 ? 'men' : 'women'}/${i + 1}.jpg`,
      hour_rate: (20 + Math.random() * 30).toFixed(2),
      gender: ['male', 'female', 'other'][i % 3],
      experience: '2 years of tutoring experience',
      last_education: ['bachelors', 'masters', 'phd'][i % 3],
      email_verified: i % 2 === 0,
      is_active: true,
      country_name: ['USA', 'Canada', 'UK', 'Australia', 'Germany'][i % 5],
      city: ['New York', 'Toronto', 'London', 'Sydney', 'Berlin'][i % 5]
    }));
  };

  const getMockCountries = () => {
    return [
      { id: 1, name: 'USA', student_count: 10 },
      { id: 2, name: 'Canada', student_count: 8 },
      { id: 3, name: 'UK', student_count: 6 },
      { id: 4, name: 'Australia', student_count: 4 },
      { id: 5, name: 'Germany', student_count: 3 }
    ];
  };

  const features = [
    {
      icon: <Shield className="w-6 h-6" />,
      title: "Verified Profiles",
      description: "All students are thoroughly verified for authenticity and credibility",
      color: "from-blue-500 to-cyan-400"
    },
    {
      icon: <GraduationCap className="w-6 h-6" />,
      title: "Expert Guidance",
      description: "Get insights from students who have successfully studied abroad",
      color: "from-purple-500 to-pink-400"
    },
    {
      icon: <GlobeIcon className="w-6 h-6" />,
      title: "Global Network",
      description: "Connect with students from top universities worldwide",
      color: "from-green-500 to-emerald-400"
    },
    {
      icon: <MessageSquare className="w-6 h-6" />,
      title: "Direct Communication",
      description: "One-on-one conversations with experienced international students",
      color: "from-orange-500 to-yellow-400"
    }
  ];

  const steps = [
    {
      number: "01",
      title: "Browse Students",
      description: "Find the perfect mentor based on your study abroad goals",
      icon: <Search className="w-5 h-5" />
    },
    {
      number: "02",
      title: "Check Availability",
      description: "View their schedule and book a convenient time slot",
      icon: <Calendar className="w-5 h-5" />
    },
    {
      number: "03",
      title: "Connect & Learn",
      description: "Get personalized guidance from experienced students",
      icon: <MessageSquare className="w-5 h-5" />
    },
    {
      number: "04",
      title: "Achieve Your Dream",
      description: "Get step-by-step support for your study abroad journey",
      icon: <Award className="w-5 h-5" />
    }
  ];

  const testimonials = [
    {
      name: "Ali Raza",
      role: "Accepted to University of Toronto",
      content: "The guidance I received from a Canadian student helped me secure my admission and scholarship!",
      avatar: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face"
    },
    {
      name: "Fatima Khan",
      role: "Studying in UK",
      content: "Connected with a mentor who helped me navigate the entire visa process smoothly.",
      avatar: "https://images.unsplash.com/photo-1494790108755-2616b612b786?w=150&h=150&fit=crop&crop=face"
    },
    {
      name: "Ahmed Malik",
      role: "Germany Scholarship Winner",
      content: "The insights from German students were invaluable for my scholarship application.",
      avatar: "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=150&h=150&fit=crop&crop=face"
    }
  ];

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative overflow-hidden">
        {/* Background Gradient */}
        <div className="absolute inset-0 bg-gradient-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-gradient-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-gradient-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" />
              Verified International Students
            </div>

            {/* Main Heading */}
            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-6 leading-tight">
              Connect with{' '}
              <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Experienced
              </span>{' '}
              <br />
              International Students
            </h1>

            {/* Subheading */}
            <p className="text-xl md:text-2xl text-gray-600 mb-10 max-w-3xl mx-auto leading-relaxed">
              Get first-hand guidance from students who have successfully navigated the study abroad journey. 
              Real insights, honest advice, and practical support for your dream education.
            </p>

            {/* Stats */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-8 max-w-3xl mx-auto mb-12">
              {[
                { number: `${totalStudents}+`, label: "Active Students", icon: <Users className="w-5 h-5" /> },
                { number: `${countries.length}+`, label: "Countries", icon: <Globe className="w-5 h-5" /> },
                { number: "24/7", label: "Availability", icon: <Clock className="w-5 h-5" /> },
                { number: "100%", label: "Verified", icon: <CheckCircle className="w-5 h-5" /> }
              ].map((stat, index) => (
                <div key={index} className="text-center">
                  <div className="inline-flex items-center justify-center w-12 h-12 bg-gradient-to-r from-teal-500 to-blue-500 text-white rounded-2xl mb-3">
                    {stat.icon}
                  </div>
                  <div className="text-2xl font-bold text-gray-900 mb-1">{stat.number}</div>
                  <div className="text-gray-600 text-sm">{stat.label}</div>
                </div>
              ))}
            </div>

            {/* Search Bar */}
            <div className="max-w-2xl mx-auto mb-8">
              <div className="relative">
                <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={searchInput}
                  onChange={(e) => handleSearch(e.target.value)}
                  placeholder="Search by country, university, or expertise..."
                  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={() => fetchStudents(1)}
                  className="absolute right-2 top-1/2 transform -translate-y-1/2 bg-gradient-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>
            </div>
          </div>
        </div>
      </div>

      {/* Features Section */}
      <div className="py-20 bg-white">
        <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 Connect with{' '}
              <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Our Students?
              </span>
            </h2>
            <p className="text-gray-600 text-lg max-w-3xl mx-auto">
              Get authentic insights and practical guidance from students who have walked the path
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            {features.map((feature, index) => (
              <div
                key={index}
                className="group relative p-8 bg-gradient-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-gradient-to-r ${feature.color} opacity-0 group-hover:opacity-5 rounded-3xl transition-opacity duration-300`}></div>
                <div className={`inline-flex p-4 rounded-2xl bg-gradient-to-r ${feature.color} text-white mb-6`}>
                  {feature.icon}
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-3">{feature.title}</h3>
                <p className="text-gray-600">{feature.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>
            ))}
          </div>
        </div>
      </div>

      {/* Main Content with Sidebar */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Left Sidebar - Filters */}
          <div className="lg:w-1/4">
            <div className="sticky top-6">
              <div className="bg-white rounded-3xl shadow-xl border border-gray-100 p-8 hover:shadow-2xl transition-all duration-300">
                <div className="flex items-center gap-3 mb-8 pb-6 border-b border-gray-200">
                  <Filter className="w-6 h-6 text-teal-600" />
                  <h2 className="text-xl font-bold text-gray-900">Filters & Search</h2>
                </div>
                <SearchFilters
                  searchQuery={searchInput}
                  onSearch={handleSearch}
                  filters={filters}
                  onFilterChange={handleFilterChange}
                  countries={countries}
                />
                
                {/* Quick Stats */}
                <div className="mt-8 pt-6 border-t border-gray-200">
                  <div className="flex items-center justify-between text-sm text-gray-600">
                    <span>Active Filters:</span>
                    <span className="font-semibold text-teal-600">
                      {Object.values(filters).filter(val => val !== '').length}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm text-gray-600 mt-2">
                    <span>Search Results:</span>
                    <span className="font-semibold text-teal-600">{totalStudents}</span>
                  </div>
                </div>

                {/* Clear All Button */}
                {(debouncedSearchQuery || Object.values(filters).some(val => val !== '')) && (
                  <button
                    onClick={clearAll}
                    className="w-full mt-6 px-4 py-3 bg-gradient-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 justify-center gap-2"
                  >
                    <RefreshCw className="w-4 h-4" />
                    Clear All Filters
                  </button>
                )}
              </div>

              {/* How It Works */}
              <div className="mt-8 bg-gradient-to-br from-teal-50 to-blue-50 rounded-3xl border border-teal-100 p-8">
                <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                  <Zap className="w-6 h-6 text-teal-600" />
                  How It Works
                </h3>
                <div className="space-y-6">
                  {steps.map((step, index) => (
                    <div key={index} className="flex items-start gap-4">
                      <div className="flex-shrink-0 w-10 h-10 bg-gradient-to-r from-teal-500 to-blue-500 text-white rounded-xl flex items-center justify-center font-bold text-sm">
                        {step.number}
                      </div>
                      <div>
                        <h4 className="font-semibold text-gray-900 mb-1">{step.title}</h4>
                        <p className="text-sm text-gray-600">{step.description}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Right Content - Students Grid */}
          <div className="lg:w-3/4">
            {/* Students Grid Header */}
            <div className="bg-gradient-to-r from-teal-500/10 to-blue-500/10 rounded-2xl p-6 mb-8 border border-teal-100">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between">
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Available Students</h2>
                  <p className="text-gray-600 mt-1">
                    Showing <span className="font-bold text-teal-600">{(currentPage - 1) * STUDENTS_PER_PAGE + 1}</span> -{' '}
                    <span className="font-bold text-teal-600">{Math.min(currentPage * STUDENTS_PER_PAGE, totalStudents)}</span> of{' '}
                    <span className="font-bold text-teal-600">{totalStudents}</span> students
                    {debouncedSearchQuery && (
                      <span className="text-teal-600 font-medium ml-2">
                        • Searching: "{debouncedSearchQuery}"
                      </span>
                    )}
                  </p>
                </div>
                <div className="mt-2 sm:mt-0 flex items-center gap-3">
                  <div className="text-sm text-gray-500">
                    Page <span className="font-bold">{currentPage}</span> of <span className="font-bold">{totalPages}</span>
                  </div>
                  <button
                    onClick={refreshData}
                    className="px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-xl font-medium hover:bg-gray-50 hover:border-gray-400 transition-all duration-200 flex items-center gap-2"
                  >
                    <RefreshCw className="w-4 h-4" />
                    Refresh
                  </button>
                </div>
              </div>
            </div>

            {/* Loading Indicator */}
            {loading && (
              <div className="mb-6 p-4 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-2xl border border-blue-100">
                <div className="flex items-center justify-center gap-3">
                  <div className="animate-spin rounded-full h-6 w-6 border-2 border-teal-600 border-t-transparent"></div>
                  <span className="text-teal-700 font-medium">Loading students...</span>
                </div>
              </div>
            )}

            {/* Students Grid */}
            <div className="mb-12">
              {loading ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {Array.from({ length: STUDENTS_PER_PAGE }).map((_, i) => (
                    <div key={i} className="bg-white rounded-3xl shadow-lg border border-gray-100 p-6 animate-pulse">
                      <div className="flex items-center space-x-4">
                        <div className="w-20 h-20 bg-gray-200 rounded-full"></div>
                        <div className="flex-1 space-y-2">
                          <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                          <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : students.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {students.map((student) => (
                    <StudentCard
                      key={student.id}
                      student={student}
                      onViewDetails={() => handleViewDetails(student)}
                      onBookAppointment={() => handleBookAppointment(student)}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-16 bg-gradient-to-br from-white to-gray-50 rounded-3xl shadow-xl border border-gray-100">
                  <div className="w-24 h-24 mx-auto mb-8 bg-gradient-to-r from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
                    <Users className="w-12 h-12 text-gray-400" />
                  </div>
                  <h3 className="text-3xl font-bold text-gray-700 mb-4">No students found</h3>
                  <p className="text-gray-500 text-lg mb-8 max-w-md mx-auto">
                    {debouncedSearchQuery 
                      ? `No results found for "${debouncedSearchQuery}"`
                      : 'Try adjusting your search criteria or filters to find more students'}
                  </p>
                  <button
                    onClick={clearAll}
                    className="px-8 py-4 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-2xl font-semibold hover:shadow-2xl hover:scale-105 transition-all duration-300"
                  >
                    Clear All Filters
                  </button>
                </div>
              )}
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="mb-12">
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={handlePageChange}
                  totalItems={totalStudents}
                  itemsPerPage={STUDENTS_PER_PAGE}
                />
              </div>
            )}

            {/* Tips Section */}
            <div className="bg-gradient-to-r from-teal-50 to-blue-50 rounded-3xl p-8 border border-teal-100 shadow-lg">
              <h3 className="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                <Sparkles className="w-7 h-7 text-teal-600" />
                Tips for Successful Connections
              </h3>
              <div className="grid md:grid-cols-2 gap-6">
                <div className="bg-white rounded-2xl p-6 shadow-sm hover:shadow-md transition-shadow duration-300">
                  <h4 className="font-bold text-gray-900 mb-3 flex items-center gap-2">
                    <Target className="w-5 h-5 text-teal-600" />
                    Be Prepared
                  </h4>
                  <p className="text-gray-600">
                    Have your questions ready before booking a session. This helps students provide the most relevant guidance.
                  </p>
                </div>
                <div className="bg-white rounded-2xl p-6 shadow-sm hover:shadow-md transition-shadow duration-300">
                  <h4 className="font-bold text-gray-900 mb-3 flex items-center gap-2">
                    <DollarSign className="w-5 h-5 text-amber-600" />
                    Respect Their Time
                  </h4>
                  <p className="text-gray-600">
                    Arrive on time for appointments and be mindful of different time zones when scheduling.
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Testimonials Section */}
      <div className="py-20 bg-white">
        <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">
              Success{' '}
              <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Stories
              </span>
            </h2>
            <p className="text-gray-600 text-lg max-w-3xl mx-auto">
              Hear from students who achieved their study abroad dreams through our platform
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {testimonials.map((testimonial, index) => (
              <div
                key={index}
                className="bg-gradient-to-br from-gray-50 to-white p-8 rounded-3xl border border-gray-100 shadow-lg hover:shadow-2xl transition-all duration-300 group"
              >
                <div className="flex items-center mb-6">
                  <img
                    src={testimonial.avatar}
                    alt={testimonial.name}
                    className="w-14 h-14 rounded-full object-cover border-4 border-white shadow-lg group-hover:scale-110 transition-transform duration-300"
                  />
                  <div className="ml-4">
                    <h4 className="font-bold text-gray-900 text-lg">{testimonial.name}</h4>
                    <p className="text-sm text-teal-600 font-semibold">{testimonial.role}</p>
                  </div>
                </div>
                <p className="text-gray-700 italic mb-6 leading-relaxed">"{testimonial.content}"</p>
                <div className="flex text-yellow-400">
                  {[...Array(5)].map((_, i) => (
                    <Star key={i} className="w-5 h-5 fill-current" />
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Final CTA */}
      <div className="py-20 bg-gradient-to-r from-teal-600 to-blue-500">
        <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 Start Your Study Abroad Journey?
          </h2>
          <p className="text-xl text-teal-100 mb-10 max-w-2xl mx-auto">
            Connect with experienced international students who can guide you every step of the way
          </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"
            >
              <Users className="animate-bounce" />
              Browse All Students
              <ChevronRight className="transition-transform duration-300 group-hover:translate-x-2" />
            </button>
            
            <button
              onClick={() => {
                const searchSection = document.querySelector('input[type="text"]');
                searchSection?.focus();
              }}
              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"
            >
              <Search className="w-5 h-5" />
              Search Specific Expertise
            </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">100% Verified Students • Secure Platform</span>
          </div>
        </div>
      </div>

      {/* Student Details Modal */}
      {selectedStudent && (
        <StudentModal
          student={selectedStudent}
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          onBookAppointment={() => {
            setIsModalOpen(false);
            handleBookAppointment(selectedStudent);
          }}
        />
      )}

      {/* Booking Modal */}
      <BookingModal
        student={bookingStudent}
        isOpen={isBookingModalOpen}
        onClose={() => {
          setIsBookingModalOpen(false);
          setBookingStudent(null);
        }}
        onBookingSuccess={handleBookingSuccess}
      />

      {/* Add missing Search icon component */}
      <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>
    </div>
  );
}

// Add missing Search icon component
const Search = ({ className = "w-6 h-6" }) => (
  <svg 
    className={className} 
    fill="none" 
    stroke="currentColor" 
    viewBox="0 0 24 24"
  >
    <path 
      strokeLinecap="round" 
      strokeLinejoin="round" 
      strokeWidth={2} 
      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" 
    />
  </svg>
);