'use client';

import { useState, useEffect, useCallback, useMemo, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';
import debounce from 'lodash/debounce';
import { useWishlist } from '../../context/WishlistContext';
import { FaHeart, FaRegHeart, FaBalanceScaleLeft } from 'react-icons/fa';
import { 
  Sparkles, 
  Search, 
  Filter, 
  Globe, 
  GraduationCap, 
  Award, 
  Clock, 
  Users,
  ChevronRight,
  X
} from 'lucide-react';
import Swal from 'sweetalert2';
import FreeConsultationModal from '../../components/organisms/FreeConsultationModal';
import ApplyNowModal from '../../components/clientcomponents/ApplyNowModal';
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';

const SafeImage = ({ 
  imageKey, 
  alt, 
  width, 
  height, 
  className,
  fallbackSrc = '/assets/default-university.webp'
}) => {
  const [src, setSrc] = useState(
    `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imageKey}`
  );

  const handleError = () => {
    setSrc(fallbackSrc);
  };

  return (
    <Image
      src={src}
      alt={alt}
      width={width}
      height={height}
      className={className}
      onError={handleError}
    />
  );
};

// Add this at the top of your file, after imports
declare global {
  interface Window {
    removeItemFromList?: (index: number) => void;
  }
}

const SearchPageInner = () => {
  const searchParams = useSearchParams();
  
  // State management
  const [results, setResults] = useState([]);
  const { toggleWishlist, isWishlisted } = useWishlist();
  const [loading, setLoading] = useState(true);
  type FilterState = {
    type: string;
    search: string;
    country: string;
    qualification: string;
    scholarship: string;
    subject: string;
    sort: string;
  };

  const [filters, setFilters] = useState<FilterState>({
    type: searchParams.get('type') || 'all',
    search: searchParams.get('q') || '',
    country: searchParams.get('country') || 'Select Country',
    qualification: searchParams.get('qualification') || '',
    scholarship: searchParams.get('scholarship') || '',
    subject: searchParams.get('subject') || '',
    sort: searchParams.get('sort') || 'relevance',
  });

  useEffect(() => {
    setFilters({
      type: searchParams.get('type') || 'all',
      search: searchParams.get('q') || '',
      country: searchParams.get('country') || 'Select Country',
      qualification: searchParams.get('qualification') || '',
      scholarship: searchParams.get('scholarship') || '',
      subject: searchParams.get('subject') || '',
      sort: searchParams.get('sort') || 'relevance',
    });
  }, [searchParams]);

  const [pagination, setPagination] = useState({
    currentPage: 1,
    totalPages: 1,
    totalItems: 0,
    itemsPerPage: 12
  });
  const [filterOptions, setFilterOptions] = useState({
    countries: [],
    qualifications: [],
    subjects: []
  });
  const [activeTab, setActiveTab] = useState('all');
  const [isScrolled, setIsScrolled] = useState(false);

  // Function to open Apply Now modal using the global function
  const openApplyNowModal = (item) => {
    if (!item) return;
    
    // Call the global function that's already set up in your ApplyNowModal
    if (window.openApplyNowModal) {
      window.openApplyNowModal(item);
    } else {
      console.warn('ApplyNowModal not available');
    }
  };

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

  // Function to open consultation modal
  const openConsultationModal = (item) => {
    setSelectedItem(item);
    setIsConsultationModalOpen(true);
  };

  // Function to close consultation modal
  const closeConsultationModal = () => {
    setIsConsultationModalOpen(false);
    setSelectedItem(null);
  };

  // Handle scroll for mobile search
  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 100);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // localStorage utility functions
  const localStorageKeys = {
    COMPARISON_TYPE: 'comparisonType',
    SELECTED_UNIVERSITIES: 'selectedUniversities',
    SELECTED_COURSES: 'selectedCourses',
    BOOKMARKED_COMPARISONS: 'bookmarkedComparisons'
  };

  const saveToLocalStorage = (key, data) => {
    try {
      localStorage.setItem(key, JSON.stringify(data));
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  };

  const loadFromLocalStorage = (key, defaultValue) => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
      console.error('Error loading from localStorage:', error);
      return defaultValue;
    }
  };

  const handleCompareClick = (item) => {
    // Determine the type (university or course)
    const itemType = (item.type || item.label || '').toLowerCase();
    const isUniversity = itemType.includes('university') || itemType.includes('college');
    const type = isUniversity ? 'university' : 'course';

    // Check if there are existing items in localStorage for comparison
    const storageKey = isUniversity ? localStorageKeys.SELECTED_UNIVERSITIES : localStorageKeys.SELECTED_COURSES;
    const existingItems = loadFromLocalStorage(storageKey, []);
    const nonEmptyItems = existingItems.filter(existingItem => existingItem.id && existingItem.id !== '');

    // Check if item is already in comparison
    const isAlreadyAdded = nonEmptyItems.some(existingItem => existingItem.id === item.id);
    
    if (isAlreadyAdded) {
      Swal.fire({
        title: 'Already Added',
        text: 'This item is already in your comparison list.',
        icon: 'info',
        confirmButtonColor: '#0B6F78',
      });
      return;
    }

    if (nonEmptyItems.length >= 3) {
      // Show remove item dialog when maximum limit reached
      showRemoveItemDialog(item, type, existingItems, nonEmptyItems);
    } else if (nonEmptyItems.length > 0) {
      // Show confirmation dialog with existing items
      showComparisonConfirmation(item, type, existingItems, nonEmptyItems);
    } else {
      // No existing items, just add this one and redirect
      addToComparisonAndRedirect(item, type, existingItems);
    }
  };

  const showRemoveItemDialog = (newItem, type, existingItems, nonEmptyItems) => {
    Swal.fire({
      title: 'Maximum Items Reached',
      html: `
        <div class="text-left">
          <p class="mb-3">You can only compare up to 3 items at a time. Please remove one item to add "${newItem.name || newItem.title}":</p>
          <div class="space-y-2 mb-4 max-h-40 overflow-y-auto">
            ${nonEmptyItems.map((existingItem, index) => `
              <div class="flex items-center justify-between p-2 border rounded">
                <span class="text-sm">${existingItem.name || existingItem.title}</span>
                <button 
                  onclick="removeItemFromList(${index})" 
                  class="text-red-500 hover:text-red-700 text-sm px-2 py-1 border border-red-300 rounded hover:bg-red-50"
                >
                  Remove
                </button>
              </div>
            `).join('')}
          </div>
          <p class="text-sm text-gray-600">After removing an item, click "Continue to Comparison"</p>
        </div>
      `,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#0B6F78',
      cancelButtonColor: '#6c757d',
      confirmButtonText: 'Continue to Comparison',
      cancelButtonText: 'Cancel',
      didOpen: () => {
        // Add global function for remove buttons
        window.removeItemFromList = (index) => {
          removeItemFromComparison(index, type, newItem, existingItems);
        };
      },
      willClose: () => {
        // Clean up global function
        delete window.removeItemFromList;
      }
    });
  };

  const removeItemFromComparison = (index, type, newItem, existingItems) => {
    const storageKey = type === 'university' ? localStorageKeys.SELECTED_UNIVERSITIES : localStorageKeys.SELECTED_COURSES;
    
    // Remove the item at the specified index
    const updatedItems = existingItems.filter((_, i) => i !== index);
    
    // Ensure we maintain at least 2 empty slots if needed
    while (updatedItems.length < 2) {
      updatedItems.push({ id: '' });
    }
    
    // Save updated list to localStorage
    saveToLocalStorage(storageKey, updatedItems);
    
    // Show success message
    Swal.fire({
      title: 'Item Removed',
      text: 'The item has been removed from your comparison list.',
      icon: 'success',
      confirmButtonColor: '#0B6F78',
    }).then(() => {
      // Check if we can now add the new item
      const currentItems = loadFromLocalStorage(storageKey, []);
      const currentNonEmpty = currentItems.filter(item => item.id && item.id !== '');
      
      if (currentNonEmpty.length < 3) {
        // Add the new item and redirect
        addToComparisonAndRedirect(newItem, type, currentItems);
      } else {
        // Should not happen, but just in case
        showRemoveItemDialog(newItem, type, currentItems, currentNonEmpty);
      }
    });
  };

  const showComparisonConfirmation = (item, type, existingItems, nonEmptyItems) => {
    Swal.fire({
      title: 'Compare with existing items?',
      html: `
        <div class="text-left">
          <p class="mb-3">You already have ${nonEmptyItems.length} item(s) selected for comparison:</p>
          <ul class="list-disc list-inside mb-4">
            ${nonEmptyItems.map(existingItem => 
              `<li class="text-sm">${existingItem.name || existingItem.title}</li>`
            ).join('')}
          </ul>
          <p>Do you want to add this item and go to comparison page?</p>
        </div>
      `,
      icon: 'question',
      showCancelButton: true,
      confirmButtonColor: '#0B6F78',
      cancelButtonColor: '#6c757d',
      confirmButtonText: 'Yes, compare now!',
      cancelButtonText: 'Cancel',
      showLoaderOnConfirm: true,
      preConfirm: () => {
        return addToComparisonAndRedirect(item, type, existingItems);
      }
    });
  };

  const addToComparisonAndRedirect = (item, type, existingItems) => {
    return new Promise((resolve) => {
      const storageKey = type === 'university' ? localStorageKeys.SELECTED_UNIVERSITIES : localStorageKeys.SELECTED_COURSES;
      
      // Find first empty slot or add new one
      const emptySlotIndex = existingItems.findIndex(existingItem => !existingItem.id || existingItem.id === '');
      
      let updatedItems;
      if (emptySlotIndex !== -1) {
        // Replace empty slot
        updatedItems = [...existingItems];
        updatedItems[emptySlotIndex] = { ...item };
      } else if (existingItems.length < 3) {
        // Add new slot
        updatedItems = [...existingItems, { ...item }];
      } else {
        // This should not happen due to our checks, but just in case
        Swal.fire({
          title: 'Error',
          text: 'Cannot add more than 3 items for comparison.',
          icon: 'error',
          confirmButtonColor: '#0B6F78',
        });
        resolve(void 0);
        return;
      }
      
      // Save to localStorage
      saveToLocalStorage(storageKey, updatedItems);
      
      // Also set the comparison type
      saveToLocalStorage(localStorageKeys.COMPARISON_TYPE, type);
      
      // Redirect to comparison page
      setTimeout(() => {
        window.location.href = '/comparison';
        resolve(void 0);
      }, 500);
    });
  };

  const searchFn = useCallback(
    async (searchFilters, page = 1) => {
      setLoading(true);
      try {
        const params = new URLSearchParams();
        Object.entries(searchFilters).forEach(([key, value]) => {
          if (value && value !== 'Select Country') {
            params.append(key, String(value));
          }
        });

        params.append('page', String(page));
        params.append('limit', String(pagination.itemsPerPage));

        const newUrl = `/search?${params.toString()}`;
        window.history.replaceState({}, '', newUrl);

        const response = await fetch(`/api/frontend/search?${params}`);
        const data = await response.json();

        if (data.success) {
          setResults(data.data);
          setPagination(data.pagination);
          setFilterOptions(data.filters);
        }
      } catch (error) {
        console.error('Search error:', error);
      } finally {
        setLoading(false);
      }
    },
    [pagination.itemsPerPage] 
  );

  const debouncedSearch = useMemo(() => debounce(searchFn, 500), [searchFn]);

  // Initial load and when filters change
  useEffect(() => {
    debouncedSearch(filters, 1);
  }, [filters, debouncedSearch]);

  // Handle filter changes
  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  // Handle page change
  const handlePageChange = (page) => {
    setPagination(prev => ({ ...prev, currentPage: page }));
    debouncedSearch(filters, page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Clear all filters
  const clearFilters = () => {
    setFilters({
      type: 'all',
      search: '',
      country: 'Select Country',
      qualification: '',
      scholarship: '',
      subject: '',
      sort: 'relevance'
    });
    setActiveTab('all');
  };

  // Check if any filters are active
  const hasActiveFilters = useMemo(() => {
    return Object.entries(filters).some(([key, value]) => {
      if (key === 'type') return value !== 'all';
      if (key === 'country') return value !== 'Select Country';
      if (key === 'sort') return false;
      return value !== '';
    });
  }, [filters]);

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <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">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-6 animate-pulse">
              <Sparkles className="w-5 h-5" />
              Discover Your Perfect Education
            </div>

            <h1 className="text-4xl md:text-6xl font-bold text-gray-900 mb-6 leading-tight">
              Find Your{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Dream University
              </span>{' '}
              &<br />
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Course
              </span>
            </h1>

            <p className="text-lg md:text-xl text-gray-600 mb-8 max-w-3xl mx-auto leading-relaxed">
              Search through 50,000+ universities and courses worldwide with expert guidance
            </p>

            {/* Search Bar */}
            <div className="max-w-3xl mx-auto">
              <div className="relative">
                <input
                  type="text"
                  placeholder="Search universities, courses, scholarships..."
                  value={filters.search}
                  onChange={(e) => handleFilterChange('search', e.target.value)}
                  className="w-full px-6 py-4 rounded-2xl bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-4 focus:ring-teal-500/20 shadow-xl border border-gray-200 text-lg"
                />
                <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                  <button className="bg-linear-to-r from-teal-600 to-blue-500 text-white p-3 rounded-xl hover:from-teal-700 hover:to-blue-600 transition-all duration-300 shadow-lg hover:shadow-xl">
                    <Search className="w-5 h-5" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="pb-20">
        <div className="max-w-screen-2xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Filter Section */}
          <ModernCard className="p-6 mb-8">
            <div className="flex items-center gap-4 mb-6">
              <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                <Filter className="w-6 h-6 text-teal-600" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900">Refine Your Search</h2>
                <p className="text-gray-600 mt-1">
                  Use filters to find the perfect match for your education goals
                </p>
              </div>
            </div>

            {/* Type Tabs */}
            <div className="flex flex-wrap gap-2 mb-6">
              {[
                { id: 'all', label: 'All Results', icon: <Globe className="w-4 h-4" /> },
                { id: 'university', label: 'Universities', icon: <GraduationCap className="w-4 h-4" /> },
                { id: 'course', label: 'Courses', icon: <Award className="w-4 h-4" /> }
              ].map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => {
                    handleFilterChange('type', tab.id);
                    setActiveTab(tab.id);
                  }}
                  className={`flex items-center gap-2 px-5 py-3 rounded-xl font-medium transition-all duration-300 ${
                    filters.type === tab.id
                      ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  {tab.icon}
                  <span>{tab.label}</span>
                </button>
              ))}
            </div>

            {/* Filters Row */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Country</label>
                <select
                  value={filters.country}
                  onChange={(e) => handleFilterChange('country', e.target.value)}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white"
                >
                  <option value="Select Country">Select Country</option>
                  {filterOptions.countries.map((country, index) => (
                    <option key={index} value={country}>{country}</option>
                  ))}
                </select>
              </div>

              {(filters.type === 'course' || filters.type === 'all') && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Qualification</label>
                    <select
                      value={filters.qualification}
                      onChange={(e) => handleFilterChange('qualification', e.target.value)}
                      className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white"
                    >
                      <option value="">Select Qualification</option>
                      {filterOptions.qualifications.map((qual) => (
                        <option key={qual.id} value={qual.id}>
                          {qual.title}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Subject</label>
                    <select
                      value={filters.subject}
                      onChange={(e) => handleFilterChange('subject', e.target.value)}
                      className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white"
                    >
                      <option value="">Select Subject</option>
                      {filterOptions.subjects.map((subject) => (
                        <option key={subject.id} value={subject.name}>{subject.name}</option>
                      ))}
                    </select>
                  </div>
                </>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Scholarship</label>
                <select
                  value={filters.scholarship}
                  onChange={(e) => handleFilterChange('scholarship', e.target.value)}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white"
                >
                  <option value="">Scholarship Status</option>
                  <option value="With Scholarship">With Scholarship</option>
                  <option value="Without Scholarship">Without Scholarship</option>
                </select>
              </div>
            </div>

            {/* Actions Row */}
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4">
              <div className="flex items-center gap-4">
                <label className="text-sm font-medium text-gray-700">Sort by:</label>
                <select
                  value={filters.sort}
                  onChange={(e) => handleFilterChange('sort', e.target.value)}
                  className="px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white"
                >
                  <option value="relevance">Relevance</option>
                  <option value="popularity">Most Popular</option>
                  <option value="ranking">Highest Ranked</option>
                  <option value="newest">Newest</option>
                </select>
              </div>

              <div className="flex items-center gap-4">
                {hasActiveFilters && (
                  <button 
                    onClick={clearFilters}
                    className="flex items-center gap-2 px-5 py-3 bg-red-100 text-red-600 rounded-xl hover:bg-red-200 transition font-medium"
                  >
                    <X className="w-4 h-4" />
                    Clear Filters
                  </button>
                )}
              </div>
            </div>
          </ModernCard>

          {/* Results Section */}
          <div>
            {/* Results Header */}
            <div className="mb-8">
              <h2 className="text-3xl font-bold text-gray-900 mb-2">
                {loading ? (
                  <span className="flex items-center">
                    <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-teal-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Finding perfect matches...
                  </span>
                ) : `Found ${pagination.totalItems} Opportunities`}
              </h2>
              <p className="text-gray-600">
                {!loading && results.length > 0 
                  ? 'Browse through our carefully curated selection of universities and courses'
                  : 'No results found. Try adjusting your search criteria.'
                }
              </p>
            </div>

            {/* Loading State */}
            {loading && (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                {[...Array(8)].map((_, index) => (
                  <div key={index} className="bg-white rounded-2xl shadow-lg p-6 animate-pulse">
                    <div className="bg-gray-300 h-48 rounded-xl mb-4"></div>
                    <div className="bg-gray-300 h-4 rounded mb-2"></div>
                    <div className="bg-gray-300 h-4 rounded w-3/4"></div>
                  </div>
                ))}
              </div>
            )}

            {/* Results Grid - 4 items per row */}
            {!loading && results.length > 0 && (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
                  {results.map((item) => (
                    <div 
                      key={`${item.type}-${item.id}`} 
                      className="bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 border border-gray-200 group"
                    >
                      {/* Header Section with Actions */}
                      <div className="bg-gray-50 rounded-t-2xl p-4 border-b border-gray-200 relative">
                        {/* Wishlist and Compare Icons - Top Right */}
                        <div className="absolute top-3 right-3 flex gap-2">
                          {/* Compare Button */}
                          <button
                            onClick={() => handleCompareClick(item)}
                            className="cursor-pointer bg-white rounded-full px-3 py-2 shadow-md hover:bg-blue-50 hover:scale-110 transition-all duration-300 flex items-center gap-1"
                            title="Compare"
                          >
                            <FaBalanceScaleLeft className="text-blue-600 text-sm" />
                            <span className="text-xs font-medium text-blue-600">Compare</span>
                          </button>

                          {/* Wishlist Button */}
                          <button
                            className="cursor-pointer bg-white rounded-full p-2 shadow-md hover:bg-red-50 hover:scale-110 transition-all duration-300"
                            title={isWishlisted({...item, type: (item.type || item.label || '').toLowerCase()}) 
                              ? 'Remove from wishlist' 
                              : 'Add to wishlist'}
                            onClick={() => toggleWishlist({...item, type: (item.type || item.label || '').toLowerCase()})}
                          >
                            {isWishlisted({...item, type: (item.type || item.label || '').toLowerCase()}) ? (
                              <FaHeart className="text-red-500 text-base" />
                            ) : (
                              <FaRegHeart className="text-gray-400 text-base" />
                            )}
                          </button>
                        </div>

                        <div className="flex flex-col items-center text-center pt-2">
                          {/* University Image */}
                          <div className="w-14 h-14 rounded-full overflow-hidden border-2 border-white shadow-md mb-3">
                            <SafeImage
                              imageKey={item.image}
                              alt={item.university || "University"}
                              width={56}
                              height={56}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          
                          {/* University Name */}
                          <h3 className="text-base font-bold text-gray-900 mb-2 line-clamp-2">
                            {item.university || item.name}
                          </h3>
                          
                          {/* Location */}
                          <div className="flex items-center justify-center text-gray-600 text-sm">
                            <svg className="w-4 h-4 mr-1 shrink-0" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                            </svg>
                            <span className="line-clamp-1">{item.location}</span>
                          </div>
                        </div>
                      </div>

                      {/* Course Details */}
                      <div className="p-5">
                        {/* Course Title */}
                        <h4 className="text-lg font-bold text-gray-900 mb-5 leading-tight text-center">
                          {item.type === 'course' ? item.name : item.courseName}
                        </h4>

                        {/* Course Info - 2 Column Grid */}
                        <div className="grid grid-cols-2 gap-4 mb-5">
                          {/* Field */}
                          {item.type === 'course' ?
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-blue-100 rounded-full">
                                <span className="text-blue-600 text-sm">📚</span>
                              </div>
                              <span className="font-medium">{item.field || item.subject}</span>
                            </div>
                          :
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-blue-100 rounded-full">
                                <span className="text-blue-600 text-sm">🏢</span>
                              </div>
                              <span className="font-medium">Founded in {item.founded || item.subject}</span>
                            </div>
                          }

                          {/* Qualification */}
                          {item.type === 'course' ?
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-green-100 rounded-full">
                                <span className="text-green-600 text-sm">🎓</span>
                              </div>
                              <span className="font-medium">{item.qualification}</span>
                            </div>
                          :
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-green-100 rounded-full">
                                <span className="text-green-600 text-sm">🎓</span>
                              </div>
                              <span className="font-medium">Ranking {item.ranking}</span>
                            </div>
                          }

                          {/* Duration */}
                          {item.type === "course" ?
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-purple-100 rounded-full">
                                <span className="text-purple-600 text-sm">⏱️</span>
                              </div>
                              <span className="font-medium">
                                {typeof item.duration === 'number' && !isNaN(item.duration) 
                                  ? `${item.duration} Year${item.duration > 1 ? 's' : ''}`
                                  : item.duration
                                }
                              </span>
                            </div>
                          :
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-purple-100 rounded-full">
                                <span className="text-purple-600 text-sm">⏱️</span>
                              </div>
                              <span className="font-medium">{item.intake}</span>
                            </div>
                          }

                          {/* Study Mode */}
                          {item.type === "course" ?
                            <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-orange-100 rounded-full">
                                <span className="text-orange-600 text-sm">🏛️</span>
                              </div>
                              <span className="font-medium">{item.currency_symbol ? item.currency_symbol : '$'}{item.fee}</span>
                            </div>
                          :
                              <div className="flex items-center gap-2 text-sm text-gray-700">
                              <div className="w-5 h-5 flex items-center justify-center bg-orange-100 rounded-full">
                                <span className="text-orange-600 text-sm">🏛️</span>
                              </div>
                              <span 
                                className="font-medium"
                                dangerouslySetInnerHTML={{ __html: item.accommodation }}
                              />
                            </div>
                          }

                          {/* Language */}
                          <div className="flex items-center gap-2 text-sm text-gray-700">
                            <div className="w-5 h-5 flex items-center justify-center bg-red-100 rounded-full">
                              <span className="text-red-600 text-sm">🌐</span>
                            </div>
                            <span className="font-medium">{item.language || 'English'}</span>
                          </div>

                          {/* Pace */}
                          <div className="flex items-center gap-2 text-sm text-gray-700">
                            <div className="w-5 h-5 flex items-center justify-center bg-indigo-100 rounded-full">
                              <span className="text-indigo-600 text-sm">⚡</span>
                            </div>
                            <span className="font-medium">Scholarship: {item.scholarship ? 'Yes' : 'No'}</span>
                          </div>
                        </div>

                        {/* Action Buttons - Three in One Row with Updated Colors */}
                        <div className="flex gap-2">
                          <Link 
                            href={`/${item.type === 'university' ? `university/${item.slug}` : `${item.university_slug}/${item.slug}`}`}
                            className="flex-1 bg-linear-to-r from-teal-600 to-blue-500 text-white text-center py-2 px-1 rounded-lg hover:from-teal-700 hover:to-blue-600 transition-all duration-300 font-semibold text-sm shadow hover:shadow-md"
                          >
                            Details
                          </Link>
                          
                          <button 
                            onClick={() => openConsultationModal(item)}
                            className="flex-1 border border-teal-600 text-teal-600 text-center py-2 px-2 rounded-lg hover:bg-teal-600 hover:text-white transition-all duration-300 font-semibold text-sm"
                          >
                            Consultation
                          </button>
                          <button 
                            onClick={() => openApplyNowModal(item)}
                            className="flex-1 bg-gray-900 text-white text-center py-2 px-2 rounded-lg hover:bg-black transition-all duration-300 font-semibold text-xs shadow hover:shadow-md"
                          >
                            Apply Now
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* No Results */}
                {results.length === 0 && (
                  <ModernCard className="p-12 text-center">
                    <div className="w-24 h-24 mx-auto mb-6 bg-linear-to-r from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
                      <Search className="w-12 h-12 text-gray-400" />
                    </div>
                    <h3 className="text-2xl font-bold text-gray-800 mb-3">No Results Found</h3>
                    <p className="text-gray-600 mb-6 max-w-md mx-auto">
                      We couldn`t find any matches for your search criteria. Try adjusting your filters or broaden your search.
                    </p>
                    <div className="flex flex-col sm:flex-row gap-4 justify-center">
                      <button 
                        onClick={clearFilters}
                        className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-8 py-3 rounded-xl hover:from-teal-700 hover:to-blue-600 transition font-medium"
                      >
                        Clear All Filters
                      </button>
                      <Link 
                        href="/free-consultation" 
                        className="border-2 border-teal-600 text-teal-600 px-8 py-3 rounded-xl hover:bg-teal-600 hover:text-white transition font-medium"
                      >
                        Get Expert Help
                      </Link>
                    </div>
                  </ModernCard>
                )}

                {/* Pagination */}
                {pagination.totalPages > 1 && (
                  <div className="flex justify-center mt-8">
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => handlePageChange(pagination.currentPage - 1)}
                        disabled={pagination.currentPage === 1}
                        className="px-4 py-3 rounded-xl border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 flex items-center font-medium transition"
                      >
                        <ChevronRight className="w-5 h-5 rotate-180 mr-2" />
                        Previous
                      </button>
                      
                      <div className="flex items-center gap-1">
                        {Array.from({ length: pagination.totalPages }, (_, i) => i + 1)
                          .filter(page => 
                            page === 1 || 
                            page === pagination.totalPages || 
                            Math.abs(page - pagination.currentPage) <= 1
                          )
                          .map((page, index, array) => {
                            const showEllipsis = index > 0 && page - array[index - 1] > 1;
                            return (
                              <div key={page} className="flex items-center">
                                {showEllipsis && <span className="px-2 text-gray-400">...</span>}
                                <button
                                  onClick={() => handlePageChange(page)}
                                  className={`w-12 h-12 rounded-xl font-medium transition ${
                                    pagination.currentPage === page
                                      ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg'
                                      : 'border border-gray-300 hover:bg-gray-50 text-gray-700'
                                  }`}
                                >
                                  {page}
                                </button>
                              </div>
                            );
                          })}
                      </div>
                      
                      <button
                        onClick={() => handlePageChange(pagination.currentPage + 1)}
                        disabled={pagination.currentPage === pagination.totalPages}
                        className="px-4 py-3 rounded-xl border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 flex items-center font-medium transition"
                      >
                        Next
                        <ChevronRight className="w-5 h-5 ml-2" />
                      </button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>

      {/* Why Students Trust Us Section - Moved After Results */}
      <div className="py-16 bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-4">
              <Sparkles className="w-5 h-5" />
              Why Students Trust Us
            </div>
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Join Thousands of Successful Students
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Our proven track record speaks for itself
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <StatCard 
              Icon={Award}
              number="50K+"
              label="Universities & Courses"
              color="teal"
            />
            <StatCard 
              Icon={Users}
              number="10K+"
              label="Happy Students"
              color="blue"
            />
            <StatCard 
              Icon={Clock}
              number="95%"
              label="Success Rate"
              color="emerald"
            />
            <StatCard 
              Icon={GraduationCap}
              number="24/7"
              label="Expert Support"
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* How It Works Section */}
      <div className="py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-4">
              <Sparkles className="w-5 h-5" />
              How It Works
            </div>
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Your Path to{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Success
              </span>
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Three simple steps to find and secure your dream education with expert guidance
            </p>
          </div>

          <div className="grid md:grid-cols-3 gap-8">
            {[
              {
                title: "Smart Search & Match",
                description: "Our platform matches you with perfect programs based on your profile and goals.",
                icon: <Search className="w-8 h-8" />,
                color: "teal"
              },
              {
                title: "Compare & Shortlist",
                description: "Compare programs side-by-side with expert insights and analysis.",
                icon: <FaBalanceScaleLeft className="w-8 h-8" />,
                color: "blue"
              },
              {
                title: "Apply & Succeed",
                description: "Get end-to-end application support for a seamless journey.",
                icon: <GraduationCap className="w-8 h-8" />,
                color: "emerald"
              }
            ].map((step, index) => (
              <ModernCard key={index} className="p-8 text-center">
                <div className={`inline-flex p-4 rounded-2xl bg-linear-to-r from-${step.color}-50 to-${step.color}-100 mb-6`}>
                  <div className={`text-${step.color}-600`}>
                    {step.icon}
                  </div>
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-3">{step.title}</h3>
                <p className="text-gray-600">{step.description}</p>
                <div className="mt-6 text-sm font-semibold text-gray-500">Step {index + 1}</div>
              </ModernCard>
            ))}
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-12 text-center max-w-7xl mx-auto my-20">
        <h2 className="text-3xl font-bold text-white mb-4">Ready to Start Your Journey?</h2>
        <p className="text-white/80 text-lg mb-8 max-w-2xl mx-auto">
          Get free personalized consultation from our education experts and take the first step toward your dream education.
        </p>
        <div className="flex flex-col sm:flex-row gap-4 justify-center">
          <Link 
            href="/free-consultation" 
            className="inline-flex items-center justify-center gap-2 bg-white/20 backdrop-blur-sm text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/30 transition-all duration-300"
          >
            <Sparkles className="w-5 h-5" />
            Free Consultation
          </Link>
          <button 
            onClick={() => clearFilters()}
            className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/10 transition-all duration-300"
          >
            <Filter className="w-5 h-5" />
            Browse All Programs
          </button>
        </div>
      </div>

      {/* Modals */}
      <FreeConsultationModal
        isOpen={isConsultationModalOpen}
        onClose={closeConsultationModal}
        title=""
        description={`Get expert guidance about ${selectedItem?.university || selectedItem?.name} - completely free!`}
      />
      <ApplyNowModal />
    </div>
  );
};

export default function SearchPage() {
  return (
    <Suspense fallback={<div>Loading search page…</div>}>
      <SearchPageInner />
    </Suspense>
  );
}