'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import ConsultantCard from '../../components/ConsultantCard';
import AISearchBox from '../../components/AISearchBox';
import StandardSearchForm from '../../components/StandardSearchForm';
import { useSearchParams } from 'next/navigation';
import AILoadingAnimation from '../../components/AILoadingAnimation';
import { Suspense } from 'react';
import { Search, Sparkles, Filter, Users, X, Brain, AlertCircle, MapPin, Navigation, Target, Globe, ChevronDown } from 'lucide-react';

interface StandardFilters {
  country: string;
  city: string;
  digital_only: boolean;
  exact_match: boolean;
  min_rating: number;
  max_price: number;
  specialization: string[];
  services: string[];
}

interface ConsultantCardData {
  id: number;
  name: string;
  phone?: string;
  company_name: string;
  city: string;
  state?: string;
  average_rating: number;
  rating_count: number;
  services: string[];
  response_time: string;
  digital_only: boolean;
  consultation_fee: number;
  ai_confidence?: number;
}

export interface Consultant {
  id: number;
  name: string;
  phone?: string;
  company_name: string;
  seo_slug: string;
  city: string;              
  state: string;            
  country?: string;
  matched_city?: string;
  services: string[];
  specialization: string[];
  target_countries: string[];
  response_time: string;
  digital_only: boolean;
  consultation_fee: number;
  profile_picture: string;
  average_rating: number;
  rating_count: number;
  ai_confidence?: number;
}

interface SearchMetadata {
  radius_km?: number;
  search_cities?: string[];
  nearby_cities?: string[];
  primary_city?: string;
  target_countries?: string[];
  ai_confidence?: number;
  ai_query?: string;
  ai_extracted_filters?: any;
}

export default function Page() {
  return (
    <Suspense fallback={<div className="p-10 text-center">Loading search…</div>}>
      <FindConsultantsPage />
    </Suspense>
  );
}


function FindConsultantsPage() {
  const searchParams = useSearchParams();
  const [activeMode, setActiveMode] = useState<'standard' | 'ai'>('ai');
  const [consultants, setConsultants] = useState<Consultant[]>([]);
  const [loading, setLoading] = useState(false);
  const [aiQuery, setAiQuery] = useState('');
  const [standardFilters, setStandardFilters] = useState<StandardFilters>({
    country: '',
    city: '',
    digital_only: false,
    exact_match: false,
    min_rating: 0,
    max_price: 0,
    specialization: [],
    services: []
  });

  const [searchInitiated, setSearchInitiated] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchSummary, setSearchSummary] = useState('');
  const [searchMetadata, setSearchMetadata] = useState<SearchMetadata>({});
  const [showAllCities, setShowAllCities] = useState(false);
  const [selectedRadius, setSelectedRadius] = useState<number>(100);
  const [includeRadius, setIncludeRadius] = useState(true);
  const [initialURLLoad, setInitialURLLoad] = useState(true);

  // Refs to track API call status
  const hasPerformedInitialSearchRef = useRef(false);
  const isAutoSearchingRef = useRef(false);
  const hasURLParametersRef = useRef(false);

  const searchConsultants = useCallback(async (mode: 'standard' | 'ai', queryWithRadius?: string) => {
    // Prevent multiple simultaneous searches
    if (loading && mode === activeMode) {
      return;
    }

    setLoading(true);
    setError(null);
    setConsultants([]);
    setSearchSummary('');
    setSearchMetadata({});
    setSearchInitiated(true);
    setShowAllCities(false);

    try {
      let url = '/api/frontend/ai-consultant-search?';
      
      if (mode === 'ai') {
        const finalQuery = queryWithRadius || aiQuery.trim();
        if (finalQuery) {
          url += `ai_query=${encodeURIComponent(finalQuery)}`;
          
          if (includeRadius && selectedRadius > 0) {
            url += `&radius_km=${selectedRadius}`;
          }
        } else {
          throw new Error('Please enter your search query');
        }
      } else {
        const params = new URLSearchParams();
        if (standardFilters.country) params.append('country', standardFilters.country);
        if (standardFilters.city) params.append('city', standardFilters.city);
        if (standardFilters.digital_only) params.append('digital_only', 'true');
        url += params.toString();
      }

      console.log('Making API call:', url);

      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 45000);
      
      const response = await fetch(url, { 
        signal: controller.signal,
        cache: 'no-store'
      });
      clearTimeout(timeoutId);
      
      if (!response.ok) {
        throw new Error(`Server error: ${response.status}`);
      }
      
      const data = await response.json();
      
      if (data.success) {
        setConsultants(data.data || []);
        if (data.summary) {
          setSearchSummary(data.summary);
        }
        
        setSearchMetadata({
          radius_km: data.search_radius_km,
          search_cities: data.search_cities,
          nearby_cities: data.nearby_cities,
          primary_city: data.filters?.city,
          target_countries: data.filters?.target_countries,
          ai_confidence: data.ai_confidence,
          ai_query: data.ai_query,
          ai_extracted_filters: data.filters
        });

      } else {
        throw new Error(data.message || 'Search failed');
      }
    } catch (error: any) {
      console.error('Search error:', error);
      const errorMessage = error.name === 'AbortError' 
        ? 'Search took too long. Please try a more specific search.' 
        : 'Failed to search. Please check your connection and try again.';
      setError(errorMessage);
    } finally {
      setLoading(false);
      setInitialURLLoad(false);
      isAutoSearchingRef.current = false;
    }
  }, [aiQuery, standardFilters, selectedRadius, includeRadius, loading, activeMode]);

  const handleAISearch = useCallback((queryWithRadius?: string) => {
    searchConsultants('ai', queryWithRadius);
  }, [searchConsultants]);

  // Handle AI query URL parameters on component mount - SINGLE TIME ONLY
  useEffect(() => {
    const aiQueryParam = searchParams.get('ai_query');
    const educationLevelParam = searchParams.get('education_level');
    const minFundsParam = searchParams.get('min_funds');
    
    // Check if we have URL parameters
    hasURLParametersRef.current = !!aiQueryParam;
    
    if (aiQueryParam && !hasPerformedInitialSearchRef.current) {
      // Decode the URL-encoded query
      const decodedQuery = decodeURIComponent(aiQueryParam);
      
      // Build the enhanced query
      let enhancedQuery = decodedQuery;
      if (educationLevelParam) {
        enhancedQuery += ` Education level: ${decodeURIComponent(educationLevelParam)}`;
      }
      if (minFundsParam) {
        enhancedQuery += ` Minimum funds: $${decodeURIComponent(minFundsParam)}`;
      }
      
      // Set the query
      setAiQuery(enhancedQuery);
      
      // Mark that we're in auto-search mode
      isAutoSearchingRef.current = true;
      hasPerformedInitialSearchRef.current = true;
      
      // Trigger search immediately ONLY for URL parameters
      searchConsultants('ai', enhancedQuery);
    } else if (!aiQueryParam) {
      // No URL parameters, don't auto-search
      hasPerformedInitialSearchRef.current = false;
      isAutoSearchingRef.current = false;
      setInitialURLLoad(false);
    }
  }, [searchParams]);

  // REMOVE the auto-search useEffect entirely - we don't want auto-search on typing
  // Only manual searches via handleAISearch function

  const handleStandardFilterChange = (newFilters: StandardFilters) => {
    setStandardFilters(newFilters);
  };

  const handleModeSwitch = (mode: 'standard' | 'ai') => {
    setActiveMode(mode);
    setConsultants([]);
    setSearchInitiated(false);
    setError(null);
    setSearchMetadata({});
    setInitialURLLoad(true);
    
    // Reset the auto-search flag when switching modes
    if (mode === 'ai') {
      isAutoSearchingRef.current = false;
    }
  };

  const clearSearch = () => {
    setConsultants([]);
    setAiQuery('');
    setStandardFilters({
      country: '',
      city: '',
      digital_only: false,
      exact_match: false,
      min_rating: 0,
      max_price: 0,
      specialization: [],
      services: []
    });
    setSearchInitiated(false);
    setError(null);
    setSearchSummary('');
    setSearchMetadata({});
    setSelectedRadius(100);
    setIncludeRadius(true);
    setInitialURLLoad(true);
    
    // Reset search flags
    hasPerformedInitialSearchRef.current = false;
    isAutoSearchingRef.current = false;
    hasURLParametersRef.current = false;
  };

  // Handle manual AI query changes - NO auto-search
  const handleAiQueryChange = (value: string) => {
    setAiQuery(value);
    // Don't trigger auto-search - only manual button click will search
  };

  // Group consultants by city
  const groupConsultantsByCity = () => {
    const grouped: Record<string, Consultant[]> = {};
    
    consultants.forEach(consultant => {
      const city = consultant.matched_city || consultant.city;
      if (!grouped[city]) {
        grouped[city] = [];
      }
      grouped[city].push(consultant);
    });
    
    return grouped;
  };

  const consultantsByCity = groupConsultantsByCity();

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative bg-gradient-to-br from-[#0B6F78] via-[#0a4f78] to-[#0a306b] text-white overflow-hidden">
        <div className="absolute inset-0 bg-black/10"></div>
        <div className="absolute top-0 right-0 w-64 h-64 bg-blue-400/20 rounded-full -translate-y-32 translate-x-32"></div>
        <div className="absolute bottom-0 left-0 w-80 h-80 bg-purple-400/10 rounded-full translate-y-40 -translate-x-40"></div>
        
        <div className="relative max-w-7xl mx-auto px-4 py-16 md:py-20">
          <div className="text-center max-w-3xl mx-auto">
            <div className="inline-flex items-center gap-2 bg-white/10 backdrop-blur-sm px-4 py-2 rounded-full mb-6">
              <Brain className="w-4 h-4" />
              <span className="text-sm font-medium">AI-Powered Search</span>
            </div>
            
            <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 leading-tight">
              Find Your Perfect
              <span className="block bg-gradient-to-r from-blue-300 to-cyan-300 bg-clip-text text-transparent">
                Immigration Consultant
              </span>
            </h1>
            
            <p className="text-xl text-blue-100 mb-8 max-w-2xl mx-auto">
              Connect with verified immigration experts using our intelligent AI-powered matching system with radius-based search.
            </p>
            
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <div className="flex items-center gap-2 text-sm">
                <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                <span>Auto-Search from URL</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <div className="w-2 h-2 bg-yellow-400 rounded-full animate-pulse"></div>
                <span>AI Natural Language</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <div className="w-2 h-2 bg-blue-400 rounded-full animate-pulse"></div>
                <span>Radius-Based Results</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-8 -mt-8 md:-mt-12">
        {/* Search Mode Toggle Card */}
        <div className="bg-white rounded-2xl shadow-2xl p-6 mb-8 border border-gray-100">
          <div className="flex flex-col md:flex-row gap-6 mb-8">
            {/* Standard Search */}
            <div className="flex-1">
              <div 
                className={`p-6 rounded-xl border-2 cursor-pointer transition-all duration-300 h-full transform hover:scale-[1.02] ${
                  activeMode === 'standard' 
                    ? 'border-blue-500 bg-gradient-to-br from-blue-50 to-white shadow-lg' 
                    : 'border-gray-200 hover:border-blue-300 bg-white'
                }`}
                onClick={() => handleModeSwitch('standard')}
              >
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className={`p-3 rounded-lg ${activeMode === 'standard' ? 'bg-blue-100' : 'bg-gray-100'}`}>
                      <Filter className={`w-6 h-6 ${activeMode === 'standard' ? 'text-blue-600' : 'text-gray-600'}`} />
                    </div>
                    <div>
                      <h3 className="text-xl font-bold text-gray-900">Standard Search</h3>
                      <p className="text-sm text-gray-500">Traditional filters</p>
                    </div>
                  </div>
                  {activeMode === 'standard' && (
                    <div className="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">
                      Active
                    </div>
                  )}
                </div>
                
                <p className="text-gray-600 mb-4">
                  Use traditional filters to find consultants by location, service type, and availability.
                </p>
                
                <StandardSearchForm
                  filters={standardFilters}
                  onChange={handleStandardFilterChange}
                  onSearch={() => searchConsultants('standard')}
                />
                
                <button
                  onClick={() => searchConsultants('standard')}
                  disabled={loading || (!standardFilters.country && !standardFilters.city)}
                  className="mt-6 w-full px-4 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:opacity-90 transition-all disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {loading && activeMode === 'standard' ? (
                    <>
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      Searching...
                    </>
                  ) : (
                    <>
                      <Search className="w-5 h-5" />
                      Search Consultants
                    </>
                  )}
                </button>
              </div>
            </div>

            {/* AI Search */}
            <div className="flex-1">
              <div 
                className={`p-6 rounded-xl border-2 cursor-pointer transition-all duration-300 h-full transform hover:scale-[1.02] ${
                  activeMode === 'ai' 
                    ? 'border-purple-500 bg-gradient-to-br from-purple-50 to-white shadow-lg' 
                    : 'border-gray-200 hover:border-purple-300 bg-white'
                }`}
                onClick={() => handleModeSwitch('ai')}
              >
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className={`p-3 rounded-lg ${activeMode === 'ai' ? 'bg-purple-100' : 'bg-gray-100'}`}>
                      <Sparkles className={`w-6 h-6 ${activeMode === 'ai' ? 'text-purple-600' : 'text-gray-600'}`} />
                    </div>
                    <div>
                      <h3 className="text-xl font-bold text-gray-900">AI Smart Search</h3>
                      <p className="text-sm text-gray-500">Natural language + Radius + Auto-Search</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    {activeMode === 'ai' && (
                      <div className="px-3 py-1 bg-purple-100 text-purple-700 text-sm font-medium rounded-full">
                        Active
                      </div>
                    )}
                    <div className="px-3 py-1 bg-gradient-to-r from-purple-600 to-pink-600 text-white text-sm font-semibold rounded-full">
                      RECOMMENDED
                    </div>
                  </div>
                </div>
                
                <div className="mb-4">
                  {initialURLLoad && aiQuery && (
                    <div className="mb-3 p-3 bg-gradient-to-r from-purple-50 to-pink-50 border border-purple-200 rounded-lg">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 bg-purple-500 rounded-full animate-pulse"></div>
                        <span className="text-sm text-purple-700">
                          Auto-searching with: {aiQuery.substring(0, 50)}...
                        </span>
                      </div>
                    </div>
                  )}
                  
                  <p className="text-gray-600 mb-4">
                    Describe your needs in plain English. Our AI understands radius requests like within 200km of Lahore.
                    URLs with ai_query parameter auto-search instantly. Manual typing requires clicking Find with AI.
                  </p>
                </div>
                
                <AISearchBox
                  value={aiQuery}
                  onChange={handleAiQueryChange} // Changed from setAiQuery to handleAiQueryChange
                  onSearch={handleAISearch}
                  loading={loading && activeMode === 'ai'}
                  selectedRadius={selectedRadius}
                  onRadiusChange={setSelectedRadius}
                  includeRadius={includeRadius}
                  onIncludeRadiusChange={setIncludeRadius}
                />
                
                <div className="mt-6 flex items-center justify-between">
                  <div className="text-sm text-gray-500">
                    {hasURLParametersRef.current 
                      ? 'URL auto-search active' 
                      : searchInitiated && activeMode === 'ai' 
                        ? 'Manual search completed' 
                        : 'Type and click "Find with AI"'}
                  </div>
                  <button
                    onClick={() => handleAISearch()}
                    disabled={loading || !aiQuery.trim()}
                    className="px-4 py-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white font-semibold rounded-lg hover:opacity-90 transition-all disabled:opacity-50 flex items-center gap-2"
                  >
                    {loading && activeMode === 'ai' ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                        AI Searching...
                      </>
                    ) : (
                      <>
                        <Brain className="w-4 h-4" />
                        Find with AI
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* Search Stats & Actions */}
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4 pt-6 border-t border-gray-100">
            <div className="text-sm text-gray-500">
              {searchInitiated ? (
                <div className="flex flex-col gap-1">
                  <span className="flex items-center gap-2">
                    <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                    Search completed
                  </span>
                  {searchMetadata.radius_km && searchMetadata.radius_km > 0 && (
                    <span className="text-xs text-blue-600 flex items-center gap-1">
                      <Navigation className="w-3 h-3" />
                      {searchMetadata.radius_km}km radius search applied
                    </span>
                  )}
                </div>
              ) : initialURLLoad && aiQuery ? (
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-purple-500 rounded-full animate-pulse"></div>
                  <span className="text-purple-600">Auto-search from URL in progress...</span>
                </div>
              ) : (
                'Ready to search'
              )}
            </div>
            
            <div className="flex items-center gap-4">
              {consultants.length > 0 && (
                <button
                  onClick={clearSearch}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors flex items-center gap-2"
                >
                  <X className="w-4 h-4" />
                  Clear Results
                </button>
              )}
              
              <button
                onClick={() => activeMode === 'ai' ? handleAISearch() : searchConsultants('standard')}
                disabled={loading || (activeMode === 'ai' && !aiQuery.trim())}
                className="px-6 py-3 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white font-semibold rounded-lg hover:shadow-lg transition-all disabled:opacity-50 flex items-center gap-2"
              >
                <Search className="w-5 h-5" />
                {activeMode === 'ai' ? 'Search with AI' : 'Search Now'}
              </button>
            </div>
          </div>
        </div>

        {/* Results Section */}
        <div className="bg-white rounded-2xl shadow-xl p-6 border border-gray-100">
          <div className="flex flex-col md:flex-row items-start md:items-center justify-between mb-8 gap-4">
            <div className="flex-1">
              <div className="flex items-center gap-3 mb-2">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <Users className="w-6 h-6 text-blue-600" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Available Consultants</h2>
                  {searchSummary && (
                    <p className="text-sm text-gray-600 mt-1">{searchSummary}</p>
                  )}
                </div>
              </div>
              
              {/* AI Search Status Indicator */}
              {initialURLLoad && aiQuery && loading && (
                <div className="mb-4 p-3 bg-gradient-to-r from-purple-50 to-pink-50 border border-purple-200 rounded-lg">
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 border-2 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
                    <span className="text-sm font-medium text-purple-700">
                      Auto-searching with AI for: {aiQuery.substring(0, 60)}...
                    </span>
                  </div>
                </div>
              )}

              {/* Enhanced Search Coverage Display for AI */}
              {activeMode === 'ai' && searchMetadata.search_cities && searchMetadata.search_cities.length > 0 && (
                <div className="mt-3">
                  <div className="bg-gradient-to-r from-blue-50/90 via-cyan-50/70 to-blue-50/90 border border-blue-100/60 rounded-2xl p-4 backdrop-blur-sm shadow-sm">
                    <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-4">
                      {/* Left Section */}
                      <div className="flex items-start gap-3">
                        <div className="p-2 bg-gradient-to-r from-blue-500/10 to-cyan-500/10 rounded-xl shadow-xs">
                          <MapPin className="w-5 h-5 text-blue-600" />
                        </div>
                        <div className="flex-1">
                          <h4 className="font-semibold text-blue-800 text-lg mb-1">AI Search Coverage Area</h4>
                          <div className="flex flex-wrap items-center gap-2 text-sm">
                            <span className="text-blue-600/90">
                              {searchMetadata.search_cities.length} cities included
                            </span>
                            <div className="h-4 w-px bg-blue-200/60"></div>
                            {searchMetadata.radius_km !== undefined && (
                              <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                                searchMetadata.radius_km === 0
                                  ? 'bg-gray-100/80 text-gray-700'
                                  : 'bg-gradient-to-r from-blue-500/10 to-cyan-500/10 text-blue-700'
                              }`}>
                                {searchMetadata.radius_km === 0 ? 'Exact City Only' : `${searchMetadata.radius_km}km Radius`}
                              </span>
                            )}
                            {searchMetadata.ai_confidence && (
                              <>
                                <div className="h-4 w-px bg-blue-200/60"></div>
                                <div className="flex items-center gap-1.5">
                                  <Brain className="w-3.5 h-3.5 text-purple-500" />
                                  <span className="text-purple-700 text-xs font-medium">
                                    AI Confidence: {Math.round(searchMetadata.ai_confidence * 100)}%
                                  </span>
                                </div>
                              </>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* Right Section - Stats */}
                      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
                        <div className="flex items-center gap-2">
                          <Navigation className="w-4 h-4 text-green-600" />
                          <div className="text-sm">
                            <div className="text-gray-700">Search Type</div>
                            <div className="font-medium text-green-700">
                              {searchMetadata.radius_km === 0 ? 'Precision Search' : 'Radius Search'}
                            </div>
                          </div>
                        </div>
                        {searchMetadata.nearby_cities && searchMetadata.nearby_cities.length > 0 && (
                          <div className="flex items-center gap-2">
                            <div className="p-1.5 bg-gradient-to-r from-green-500/10 to-emerald-500/10 rounded-lg">
                              <MapPin className="w-3.5 h-3.5 text-green-600" />
                            </div>
                            <div className="text-sm">
                              <div className="text-gray-700">Nearby Cities</div>
                              <div className="font-medium text-green-700">
                                {searchMetadata.nearby_cities.length} included
                              </div>
                            </div>
                          </div>
                        )}
                      </div>

                      <div className="flex items-center gap-4">
                        {consultants.length > 0 && (
                          <div className="px-4 py-2 bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-100 rounded-full">
                            <span className="text-blue-700 font-bold">
                              {consultants.length} {consultants.length === 1 ? 'match' : 'matches'} found
                            </span>
                          </div>
                        )}
                        
                        {activeMode === 'ai' && consultants.length > 0 && (
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <Brain className="w-4 h-4" />
                            <span>AI-Powered Ranking</span>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Target Countries - Improved Layout */}
                    {searchMetadata.target_countries && searchMetadata.target_countries.length > 0 && (
                      <div className="mb-4 p-3 bg-gradient-to-r from-green-50/60 to-emerald-50/60 rounded-xl border border-green-200/40">
                        <div className="flex flex-col sm:flex-row sm:items-center gap-3">
                          <div className="flex items-center gap-2 flex-shrink-0">
                            <Globe className="w-4 h-4 text-green-600" />
                            <span className="text-sm font-medium text-gray-700">Target Countries:</span>
                          </div>
                          <div className="flex flex-wrap gap-1.5">
                            {searchMetadata.target_countries.map((country, index) => (
                              <span 
                                key={index}
                                className="px-2.5 py-1 bg-gradient-to-r from-green-500/5 to-emerald-500/5 text-green-700 text-xs font-medium rounded-full border border-green-200/50 flex items-center gap-1.5 hover:border-green-300 transition-colors"
                              >
                                <div className="w-1.5 h-1.5 bg-gradient-to-r from-green-400 to-emerald-400 rounded-full"></div>
                                {country}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}

                    {/* Cities Display - Enhanced Responsive */}
                    <div className="space-y-3">
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                        <div className="flex items-center gap-2">
                          <div className="p-1 bg-gradient-to-r from-blue-500/10 to-cyan-500/10 rounded">
                            <MapPin className="w-3.5 h-3.5 text-blue-600" />
                          </div>
                          <span className="text-sm font-medium text-gray-700">
                            Cities Included in Search
                          </span>
                          <span className="px-2 py-0.5 bg-white/60 text-blue-600 text-xs font-medium rounded-full">
                            {searchMetadata.search_cities.length} total
                          </span>
                        </div>
                        
                        <div className="flex items-center gap-2">
                          {searchMetadata.search_cities.length > 6 && (
                            <button
                              onClick={() => setShowAllCities(!showAllCities)}
                              className="text-xs text-blue-600 hover:text-blue-800 font-medium px-2.5 py-1 bg-white/60 hover:bg-white rounded-lg transition-colors flex items-center gap-1"
                            >
                              {showAllCities ? 'Show Less' : 'View All'}
                              <ChevronDown className={`w-3 h-3 transition-transform ${showAllCities ? 'rotate-180' : ''}`} />
                            </button>
                          )}
                          {searchMetadata.primary_city && (
                            <div className="text-xs text-gray-500">
                              Primary: <span className="font-medium text-blue-700">{searchMetadata.primary_city}</span>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Cities Grid - Responsive */}
                      <div className="grid grid-cols-1 xs:grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">
                        {(showAllCities ? searchMetadata.search_cities : searchMetadata.search_cities.slice(0, 6)).map((city, index) => {
                          const isPrimaryCity = index === 0 || city === searchMetadata.primary_city;
                          const isNearbyCity = searchMetadata.nearby_cities?.includes(city) && !isPrimaryCity;
                          
                          return (
                            <div
                              key={index}
                              className={`p-2.5 rounded-lg border transition-all ${
                                isPrimaryCity
                                  ? 'bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-300/60 shadow-xs'
                                  : isNearbyCity
                                  ? 'bg-gradient-to-r from-green-50/50 to-emerald-50/50 border-green-200/50'
                                  : 'bg-white/80 border-gray-200/60'
                              }`}
                            >
                              <div className="flex items-center gap-1.5">
                                <div className={`p-1 rounded ${
                                  isPrimaryCity
                                    ? 'bg-gradient-to-r from-blue-500/20 to-cyan-500/20'
                                    : isNearbyCity
                                    ? 'bg-gradient-to-r from-green-500/20 to-emerald-500/20'
                                    : 'bg-gray-100'
                                }`}>
                                  <MapPin className={`w-3 h-3 ${
                                    isPrimaryCity ? 'text-blue-600' : isNearbyCity ? 'text-green-600' : 'text-gray-500'
                                  }`} />
                                </div>
                                <div className="flex-1 min-w-0">
                                  <div className="flex items-center gap-1.5">
                                    <span className={`text-sm font-medium truncate ${
                                      isPrimaryCity ? 'text-blue-800' : isNearbyCity ? 'text-green-800' : 'text-gray-700'
                                    }`}>
                                      {city}
                                    </span>
                                    {isPrimaryCity && (
                                      <span className="px-1 py-0.5 bg-blue-500/10 text-blue-600 text-[10px] font-bold rounded">
                                        PRIMARY
                                      </span>
                                    )}
                                  </div>
                                  {isNearbyCity && (
                                    <div className="flex items-center gap-1 mt-0.5">
                                      <Navigation className="w-2.5 h-2.5 text-green-500" />
                                      <span className="text-[10px] text-green-600">
                                        {searchMetadata.radius_km}km from {searchMetadata.primary_city}
                                      </span>
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>
                          );
                        })}
                        
                        {/* View More Indicator */}
                        {!showAllCities && searchMetadata.search_cities.length > 6 && (
                          <div className="p-2.5 rounded-lg border border-dashed border-blue-200/60 bg-white/40 flex items-center justify-center hover:bg-blue-50/50 transition-colors cursor-pointer group"
                               onClick={() => setShowAllCities(true)}>
                            <div className="text-center">
                              <div className="text-blue-400 group-hover:text-blue-600 mb-1">
                                <MapPin className="w-4 h-4 mx-auto" />
                              </div>
                              <div className="text-xs text-blue-600/80 group-hover:text-blue-700 font-medium">
                                +{searchMetadata.search_cities.length - 6} more
                              </div>
                              <div className="text-[10px] text-gray-500 mt-0.5">
                                Click to view all
                              </div>
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Search Insights */}
                      {searchMetadata.radius_km && searchMetadata.radius_km > 0 && (
                        <div className="mt-3 pt-3 border-t border-blue-100/50">
                          <div className="flex flex-col sm:flex-row sm:items-center gap-3">
                            <div className="flex items-center gap-2">
                              <div className="p-1.5 bg-gradient-to-r from-orange-500/10 to-amber-500/10 rounded-lg">
                                <Target className="w-4 h-4 text-orange-600" />
                              </div>
                              <div>
                                <p className="text-sm font-medium text-gray-700">Radius Search Active</p>
                                <p className="text-xs text-gray-600">
                                  Found consultants from {searchMetadata.primary_city} and {searchMetadata.nearby_cities?.length || 0} nearby cities within {searchMetadata.radius_km}km
                                </p>
                              </div>
                            </div>
                            <div className="flex-1">
                              <div className="h-2 bg-gradient-to-r from-blue-100 via-cyan-100 to-blue-100 rounded-full overflow-hidden">
                                <div 
                                  className="h-full bg-gradient-to-r from-blue-500 to-cyan-500 rounded-full transition-all duration-1000"
                                  style={{ 
                                    width: `${Math.min(100, (searchMetadata.nearby_cities?.length || 0) * 10)}%` 
                                  }}
                                ></div>
                              </div>
                              <div className="flex justify-between text-xs text-gray-500 mt-1">
                                <span>Primary City</span>
                                <span>{searchMetadata.nearby_cities?.length || 0} Nearby Cities</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
            
          </div>

          {/* Error Display */}
          {error && (
            <div className="mb-8 p-4 bg-red-50 border border-red-200 rounded-xl">
              <div className="flex items-center gap-3">
                <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0" />
                <div>
                  <p className="text-red-800 font-medium">Search Error</p>
                  <p className="text-red-600 text-sm mt-1">{error}</p>
                  <button
                    onClick={() => setError(null)}
                    className="mt-2 text-sm text-red-600 hover:text-red-800 underline"
                  >
                    Dismiss
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Loading State */}
          {loading && (
            <div className="py-12">
              <AILoadingAnimation />
              {activeMode === 'ai' && searchMetadata.radius_km && (
                <div className="text-center mt-6 text-gray-500">
                  <p>Searching within {searchMetadata.radius_km}km radius...</p>
                  <p className="text-sm mt-1">Analyzing multiple cities for best matches</p>
                </div>
              )}
              {activeMode === 'ai' && aiQuery && (
                <div className="text-center mt-6 text-gray-500">
                  <p>Processing AI query: {aiQuery.substring(0, 80)}...</p>
                </div>
              )}
            </div>
          )}

          {/* Results Grid with City Grouping */}
          {!loading && consultants.length > 0 ? (
            <>
              {/* City Grouping Toggle */}
              {Object.keys(consultantsByCity).length > 1 && (
                <div className="mb-6 p-4 bg-gray-50 rounded-xl">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <MapPin className="w-5 h-5 text-blue-600" />
                      <span className="font-medium text-gray-700">
                        Consultants found in {Object.keys(consultantsByCity).length} different cities
                      </span>
                    </div>
                    <div className="flex items-center gap-2 text-sm text-gray-500">
                      <div className="flex items-center gap-1">
                        <div className="w-3 h-3 bg-blue-100 border border-blue-300 rounded"></div>
                        <span>Primary city</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <div className="w-3 h-3 bg-green-100 border border-green-300 rounded"></div>
                        <span>Nearby cities</span>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Grouped Results by City */}
              {Object.entries(consultantsByCity).map(([city, cityConsultants], cityIndex) => {
                const isPrimaryCity = city === searchMetadata.primary_city;
                const isNearbyCity = searchMetadata.nearby_cities?.includes(city);
                
                return (
                  <div key={city} className="mb-8 last:mb-0">
                    <div className={`flex items-center gap-3 mb-4 p-3 rounded-lg ${
                      isPrimaryCity 
                        ? 'bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-200' 
                        : 'bg-gray-50 border border-gray-200'
                    }`}>
                      <div className={`p-2 rounded-lg ${
                        isPrimaryCity ? 'bg-blue-100' : 'bg-gray-100'
                      }`}>
                        <MapPin className={`w-5 h-5 ${
                          isPrimaryCity ? 'text-blue-600' : 'text-gray-600'
                        }`} />
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <h3 className="font-bold text-gray-900">{city}</h3>
                          {isPrimaryCity && (
                            <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs font-medium rounded-full">
                              Primary City
                            </span>
                          )}
                          {isNearbyCity && !isPrimaryCity && (
                            <span className="px-2 py-1 bg-green-100 text-green-700 text-xs font-medium rounded-full">
                              Nearby City
                            </span>
                          )}
                          <span className="text-sm text-gray-500">
                            ({cityConsultants.length} consultant{cityConsultants.length !== 1 ? 's' : ''})
                          </span>
                        </div>
                        {searchMetadata.radius_km && isNearbyCity && !isPrimaryCity && (
                          <p className="text-xs text-gray-500 mt-1">
                            Located within {searchMetadata.radius_km}km of {searchMetadata.primary_city}
                          </p>
                        )}
                      </div>
                    </div>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                      {cityConsultants.map((consultant) => (
                        <ConsultantCard 
                          key={consultant.id} 
                          consultant={consultant} 
                          aiMode={activeMode === 'ai'}
                        />
                      ))}
                    </div>
                  </div>
                );
              })}
              
              {/* Results Footer */}
              <div className="mt-10 pt-6 border-t border-gray-100">
                <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
                  <div className="text-sm text-gray-500">
                    <div className="flex flex-col sm:flex-row sm:items-center gap-2">
                      <span>Showing {consultants.length} consultants across {Object.keys(consultantsByCity).length} cities</span>
                      {searchMetadata.search_cities && searchMetadata.search_cities.length > 0 && (
                        <span className="px-2 py-1 bg-blue-50 text-blue-700 rounded-full text-xs">
                          Searched {searchMetadata.search_cities.length} cities
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <button
                      onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
                      className="px-4 py-2 text-blue-600 hover:text-blue-800 font-medium"
                    >
                      Back to top ↑
                    </button>
                    <button
                      onClick={() => activeMode === 'ai' ? handleAISearch() : searchConsultants('standard')}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      Refresh Results
                    </button>
                  </div>
                </div>
              </div>
            </>
          ) : !loading && searchInitiated ? (
            // No results state
            <div className="text-center py-16">
              <div className="w-24 h-24 mx-auto mb-6 text-gray-300">
                <Search className="w-full h-full" />
              </div>
              <h3 className="text-2xl font-bold text-gray-700 mb-3">No consultants found</h3>
              {searchMetadata.radius_km && searchMetadata.radius_km > 0 ? (
                <div className="max-w-md mx-auto mb-8">
                  <p className="text-gray-500 mb-4">
                    No consultants found within {searchMetadata.radius_km}km of {searchMetadata.primary_city}.
                  </p>
                  <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl">
                    <p className="text-sm text-amber-700">
                      💡 <span className="font-medium">Tip:</span> Try increasing the search radius or check different cities.
                    </p>
                  </div>
                </div>
              ) : (
                <p className="text-gray-500 max-w-md mx-auto mb-8">
                  {activeMode === 'ai' 
                    ? `No consultants found for "${aiQuery}". Try being more specific or use different keywords.` 
                    : 'Try adjusting your filters or search criteria.'}
                </p>
              )}
              <div className="flex flex-col sm:flex-row gap-3 justify-center">
                <button
                  onClick={clearSearch}
                  className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  Clear Search
                </button>
                <button
                  onClick={() => setActiveMode(activeMode === 'ai' ? 'standard' : 'ai')}
                  className="px-6 py-3 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white rounded-lg hover:opacity-90 transition-opacity"
                >
                  Try {activeMode === 'ai' ? 'Standard' : 'AI'} Search
                </button>
              </div>
            </div>
          ) : !loading && !searchInitiated ? (
            // Initial state - ready to search
            <div className="text-center py-16">
              <div className="w-32 h-32 mx-auto mb-8 bg-gradient-to-br from-blue-50 to-purple-50 rounded-full flex items-center justify-center">
                <Brain className="w-16 h-16 text-blue-400" />
              </div>
              <h3 className="text-2xl font-bold text-gray-700 mb-3">Ready to Find Your Consultant</h3>
              <p className="text-gray-500 max-w-md mx-auto mb-8">
                {activeMode === 'ai' 
                  ? 'Describe your immigration needs in the AI search box above or use a URL with ai_query parameter for instant results.' 
                  : 'Use the filters above to search for immigration consultants based on your specific requirements.'}
              </p>
              <div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 text-blue-700 rounded-full">
                <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                <span className="text-sm font-medium">Select a search method to begin</span>
              </div>
            </div>
          ) : null}
        </div>

        {/* Info Section */}
        <div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="bg-gradient-to-br from-purple-50 to-white p-6 rounded-xl border border-purple-100">
            <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mb-4">
              <Brain className="w-6 h-6 text-purple-600" />
            </div>
            <h4 className="font-bold text-lg text-gray-900 mb-2">URL Auto-Search</h4>
            <p className="text-gray-600 text-sm">
              Visit URLs like /find-my-consultant?ai_query=Germany+student+visa+consultants to auto-search instantly.
            </p>
          </div>
          
          <div className="bg-gradient-to-br from-blue-50 to-white p-6 rounded-xl border border-blue-100">
            <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mb-4">
              <Navigation className="w-6 h-6 text-blue-600" />
            </div>
            <h4 className="font-bold text-lg text-gray-900 mb-2">Radius-Based Search</h4>
            <p className="text-gray-600 text-sm">
              Find consultants in multiple cities within your preferred distance. Perfect for finding experts in nearby areas.
            </p>
          </div>
          
          <div className="bg-gradient-to-br from-green-50 to-white p-6 rounded-xl border border-green-100">
            <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mb-4">
              <MapPin className="w-6 h-6 text-green-600" />
            </div>
            <h4 className="font-bold text-lg text-gray-900 mb-2">Multi-City Coverage</h4>
            <p className="text-gray-600 text-sm">
              Our AI searches across 20+ nearby cities to ensure you find the best consultants.
            </p>
          </div>
        </div>

        {/* FAQ Section */}
        <div className="mt-8 bg-gradient-to-br from-gray-50 to-white rounded-2xl border border-gray-200 p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">How URL Auto-Search Works</h3>
          <div className="space-y-4">
            <div className="flex items-start gap-3">
              <div className="w-6 h-6 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-medium">
                1
              </div>
              <div>
                <p className="font-medium text-gray-800">Use URL with ai_query Parameter</p>
                <p className="text-sm text-gray-600">Visit /find-my-consultant?ai_query=Germany+student+visa+consultants+Lahore</p>
              </div>
            </div>
            <div className="flex items-start gap-3">
              <div className="w-6 h-6 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-medium">
                2
              </div>
              <div>
                <p className="font-medium text-gray-800">Auto-Fill AI Search</p>
                <p className="text-sm text-gray-600">The AI search box is automatically populated with your query</p>
              </div>
            </div>
            <div className="flex items-start gap-3">
              <div className="w-6 h-6 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-medium">
                3
              </div>
              <div>
                <p className="font-medium text-gray-800">Instant AI Results</p>
                <p className="text-sm text-gray-600">AI analyzes your query and shows consultant matches instantly</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}