'use client';

import Link from 'next/link';
import { useState, useEffect, useCallback } from 'react';
import { 
  Brain, 
  Target, 
  AlertTriangle, 
  CheckCircle, 
  TrendingUp, 
  Calendar,
  DollarSign,
  FileText,
  Globe,
  Users,
  Briefcase,
  GraduationCap,
  Banknote,
  History,
  Home,
  Plane,
  Shield,
  Clock,
  Download,
  Share2,
  Printer,
  BookOpen,
  ChevronRight,
  Sparkles,
  BarChart3,
  Award,
  Lightbulb,
  Zap,
  Rocket,
  Plus,
  Minus,
  MapPin,
  Search,
  ExternalLink,
  FileDown,
  X,
  Mail,
  Phone,
  User,
  Star,
  Trophy,
  ArrowRight,
  Loader2,
  HelpCircle,
  ChevronLeft,
  Eye,
  MessageSquare,
  FileCheck,
  CalendarDays,
  Languages,
  Building2
} from 'lucide-react';
import { jsPDF } from 'jspdf';
import LeadModal from '../../components/LeadModal';

// Define types for lead data
type LeadData = {
  name: string;
  email: string;
  phoneNumber: string;
  expiry?: number;
  // Form fields from lead data
  age?: number;
  destinationCountry?: string;
  visaType?: string;
  educationLevel?: string;
  educationGapYears?: number;
  employmentStatus?: string;
  jobExperienceYears?: number;
  previousRefusals?: number;
  financialSource?: string;
  financialProofAmount?: number;
  languageTest?: string;
  languageScore?: number | null;
  mediumOfInstruction?: string;
  purposeOfTravel?: string;
  familyTiesInHomeCountry?: string;
  residenceCountry?: string;
  residenceCity?: string;
};

// Constants
const DESTINATION_COUNTRIES = [
  'Canada', 'USA', 'UK', 'Australia', 'Germany', 'France', 'New Zealand', 
  'UAE', 'Singapore', 'Japan', 'South Korea', 'Netherlands', 'Sweden', 
  'Switzerland', 'Ireland', 'Spain', 'Italy', 'Portugal', 'Malaysia', 'Qatar'
];

const VISA_PREDICTOR_STORAGE_KEYS = {
  LAST_SEARCH: 'visa_predictor_last_search',
  LAST_RESULT: 'visa_predictor_last_result',
  FORM_DATA: 'visa_predictor_form_data',
  USER_DATA: 'visa_predictor_user_data'
};

const LANGUAGE_TESTS = [
  { value: 'ielts', label: 'IELTS' },
  { value: 'toefl', label: 'TOEFL' },
  { value: 'pte', label: 'PTE Academic' },
  { value: 'celpip', label: 'CELPIP' },
  { value: 'duolingo', label: 'Duolingo English Test' },
  { value: 'cael', label: 'CAEL' },
  { value: 'not_applicable', label: 'Not Required/Not Taken' }
];

const VISA_TYPES = [
  'Student Visa', 'Work Visa', 'Tourist Visa', 'Business Visa', 
  'Family Visa', 'Permanent Residency', 'Investor Visa', 'Visitor Visa'
];

const EDUCATION_LEVELS = [
  'High School', 'Diploma', 'Bachelor\'s Degree', 'Master\'s Degree', 
  'PhD', 'Professional Certificate'
];

const EMPLOYMENT_STATUS = [
  'Employed', 'Self-Employed', 'Student', 'Unemployed', 'Retired'
];

const FINANCIAL_SOURCES = [
  'Personal savings', 'Parents sponsorship', 'Scholarship', 
  'Education loan', 'Employer sponsorship', 'Government funding'
];

const FAMILY_TIES = [
  'Strong (own property, immediate family)',
  'Moderate (parents/siblings, rental property)',
  'Weak (no immediate family, renting)'
];

interface Country {
  name: {
    common: string;
    official: string;
  };
  cca2: string;
  cca3: string;
  flag: string;
}

interface Consultant {
  id: number;
  name: string;
  company_name: string;
  seo_slug: string;
  city: string;
  country: string;
  average_rating: number;
  rating_count: number;
  consultation_fee: number;
  services: string[];
  specialization: string[];
  target_countries: string[];
  response_time: string;
  digital_only: boolean;
  profile_picture: string;
  ai_match_score: number;
  ai_match_reason: string;
}

interface Prediction {
  successProbability: number;
  confidence: number;
  riskLevel: 'low' | 'medium' | 'high';
  predictedOutcome: 'recommended_for_approval' | 'recommended_for_refusal' | 'borderline';
  keyStrengths: string[];
  riskFactors: Array<{
    factor: string;
    severity: 'low' | 'medium' | 'high';
    description: string;
    impact: number;
  }>;
  improvementSuggestions: Array<{
    suggestion: string;
    priority: 'high' | 'medium' | 'low';
    action: string;
    timeline: string;
  }>;
  countrySpecificAdvice: string[];
  processingTimeEstimate: string;
  documentChecklist: string[];
  estimatedVisaFee: number;
  nextSteps: string[];
  disclaimer: string;
  generatedAt: string;
  aiModelUsed: string;
  consultantMatches?: Consultant[];
  consultantMatchCount?: number;
  consultantSearchQuery?: string;
  consultantMatchSuggestion?: string;
}

// Modern Card Component (matching reference design)
const ModernCard = ({ children, className = '', hover = true }: { children: React.ReactNode; className?: string; hover?: boolean }) => (
  <div className={`bg-white rounded-3xl border border-gray-100 shadow-sm hover:shadow-lg transition-all duration-300 ${hover ? 'hover:border-teal-200' : ''} ${className}`}>
    {children}
  </div>
);

// Badge Component (matching reference design)
const Badge = ({ children, color = 'teal', icon: Icon }: { children: React.ReactNode; color?: string; icon?: any }) => {
  const colorClasses: { [key: string]: string } = {
    teal: 'bg-teal-100 text-teal-700 border-teal-200',
    blue: 'bg-blue-100 text-blue-700 border-blue-200',
    emerald: 'bg-emerald-100 text-emerald-700 border-emerald-200',
    amber: 'bg-amber-100 text-amber-700 border-amber-200',
    gray: 'bg-gray-100 text-gray-700 border-gray-200',
    red: 'bg-red-100 text-red-700 border-red-200',
    green: 'bg-green-100 text-green-700 border-green-200',
    purple: 'bg-purple-100 text-purple-700 border-purple-200'
  };

  return (
    <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium border ${colorClasses[color] || colorClasses.teal}`}>
      {Icon && <Icon className="w-3.5 h-3.5" />}
      {children}
    </span>
  );
};

// Stat Card Component (matching reference design)
const StatCard = ({ icon: Icon, number, label, color = 'teal' }: { icon: any; number: string | number; label: string; color?: string }) => {
  const colorClasses: { [key: string]: string } = {
    teal: 'bg-gradient-to-r from-teal-500 to-blue-500',
    blue: 'bg-gradient-to-r from-blue-500 to-cyan-500',
    emerald: 'bg-gradient-to-r from-emerald-500 to-teal-500',
    amber: 'bg-gradient-to-r from-amber-500 to-orange-500'
  };

  return (
    <div className="text-center">
      <div className={`inline-flex items-center justify-center w-12 h-12 ${colorClasses[color] || colorClasses.teal} text-white rounded-2xl mb-3`}>
        <Icon className="w-6 h-6" />
      </div>
      <div className="text-2xl font-bold text-gray-900 mb-1">{number}</div>
      <div className="text-gray-600 text-sm">{label}</div>
    </div>
  );
};

// Feature Card Component (matching reference design)
const FeatureCard = ({ icon: Icon, title, description, color = 'from-teal-500 to-blue-500' }: { icon: any; title: string; description: string; color?: string }) => (
  <div className="group relative p-8 bg-gradient-to-br from-gray-50 to-white rounded-3xl border border-gray-100 shadow-sm hover:shadow-2xl hover:scale-105 transition-all duration-300 hover:border-teal-200">
    <div className={`absolute inset-0 bg-gradient-to-r ${color} opacity-0 group-hover:opacity-5 rounded-3xl transition-opacity duration-300`}></div>
    <div className={`inline-flex p-4 rounded-2xl bg-gradient-to-r ${color} text-white mb-6`}>
      <Icon className="w-6 h-6" />
    </div>
    <h3 className="text-xl font-bold text-gray-900 mb-3">{title}</h3>
    <p className="text-gray-600">{description}</p>
    <div className="absolute bottom-8 right-8 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
      <ChevronRight className="text-gray-400" />
    </div>
  </div>
);

// Custom Number Input Component with new design
const NumberInputWithButtons = ({ 
  value, 
  onChange, 
  min, 
  max, 
  step = 1,
  label,
  prefix = '',
  suffix = '',
  icon: Icon
}: {
  value: number;
  onChange: (value: number) => void;
  min: number;
  max: number;
  step?: number;
  label: string;
  prefix?: string;
  suffix?: string;
  icon?: any;
}) => (
  <div className="space-y-2">
    <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
      {Icon && <Icon className="w-4 h-4 text-gray-400" />}
      {label}
    </label>
    <div className="flex items-center gap-2">
      <button
        type="button"
        onClick={() => onChange(Math.max(min, value - step))}
        className="p-2.5 rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        disabled={value <= min}
      >
        <Minus className="w-4 h-4 text-gray-600" />
      </button>
      <div className="flex-1 relative">
        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-500">
          {prefix}
        </div>
        <input
          type="number"
          value={value}
          onChange={(e) => {
            const val = parseInt(e.target.value) || min;
            onChange(Math.max(min, Math.min(max, val)));
          }}
          min={min}
          max={max}
          step={step}
          className="w-full pl-10 pr-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent text-center bg-gray-50"
        />
        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none text-gray-500">
          {suffix}
        </div>
      </div>
      <button
        type="button"
        onClick={() => onChange(Math.min(max, value + step))}
        className="p-2.5 rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        disabled={value >= max}
      >
        <Plus className="w-4 h-4 text-gray-600" />
      </button>
    </div>
    <div className="flex justify-between text-xs text-gray-500">
      <span>{min}{suffix}</span>
      <span>{max}{suffix}</span>
    </div>
  </div>
);

// Custom Financial Input Component with new design
const FinancialInput = ({ 
  value, 
  onChange, 
  min = 1000, 
  max = 100000,
  step = 1000
}: {
  value: number;
  onChange: (value: number) => void;
  min?: number;
  max?: number;
  step?: number;
}) => (
  <div className="space-y-2">
    <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
      <DollarSign className="w-4 h-4 text-gray-400" />
      Financial Proof Amount
    </label>
    <div className="flex items-center gap-2">
      <button
        type="button"
        onClick={() => onChange(Math.max(min, value - step))}
        className="p-2.5 rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        disabled={value <= min}
      >
        <Minus className="w-4 h-4 text-gray-600" />
      </button>
      <div className="flex-1 relative">
        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-500">
          $
        </div>
        <input
          type="number"
          value={value}
          onChange={(e) => {
            const val = parseInt(e.target.value) || min;
            onChange(Math.max(min, Math.min(max, val)));
          }}
          min={min}
          max={max}
          step={step}
          className="w-full pl-10 pr-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50"
        />
      </div>
      <button
        type="button"
        onClick={() => onChange(Math.min(max, value + step))}
        className="p-2.5 rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        disabled={value >= max}
      >
        <Plus className="w-4 h-4 text-gray-600" />
      </button>
    </div>
    <div className="flex justify-between text-xs text-gray-500">
      <span>${min.toLocaleString()}</span>
      <span>${max.toLocaleString()}+</span>
    </div>
  </div>
);

// Country Search Component with new design
const CountrySearch = ({ 
  label, 
  value, 
  onChange, 
  placeholder = "Search country..." 
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [countries, setCountries] = useState<Country[]>([]);
  const [filteredCountries, setFilteredCountries] = useState<Country[]>([]);
  const [loading, setLoading] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);

  const fetchCountries = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch('https://restcountries.com/v3.1/all?fields=name,cca2,cca3,flags');
      const data = await response.json();
      setCountries(data);
      setFilteredCountries(data.slice(0, 20));
    } catch (error) {
      console.error('Error fetching countries:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchCountries();
  }, [fetchCountries]);

  useEffect(() => {
    if (searchTerm.trim() === '') {
      setFilteredCountries(countries.slice(0, 20));
    } else {
      const filtered = countries.filter(country =>
        country.name.common.toLowerCase().includes(searchTerm.toLowerCase()) ||
        country.name.official.toLowerCase().includes(searchTerm.toLowerCase())
      ).slice(0, 20);
      setFilteredCountries(filtered);
    }
  }, [searchTerm, countries]);

  const handleSelect = (country: Country) => {
    onChange(country.name.common);
    setSearchTerm(country.name.common);
    setShowDropdown(false);
  };

  return (
    <div className="space-y-2 relative">
      <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
        <Globe className="w-4 h-4 text-gray-400" />
        {label}
      </label>
      <div className="relative">
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => {
            setSearchTerm(e.target.value);
            setShowDropdown(true);
          }}
          onFocus={() => setShowDropdown(true)}
          onBlur={() => setTimeout(() => setShowDropdown(false), 200)}
          placeholder={placeholder}
          className="w-full px-4 py-3 pl-10 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50"
        />
        <Search className="absolute left-3 top-3.5 w-4 h-4 text-gray-400" />
      </div>
      
      {showDropdown && (
        <div className="absolute z-10 w-full mt-2 bg-white border border-gray-200 rounded-2xl shadow-2xl max-h-60 overflow-y-auto">
          {loading ? (
            <div className="p-4 text-center text-gray-500">
              <Loader2 className="w-5 h-5 animate-spin mx-auto mb-2 text-teal-600" />
              Loading countries...
            </div>
          ) : filteredCountries.length > 0 ? (
            filteredCountries.map((country) => (
              <button
                key={country.cca3}
                type="button"
                onClick={() => handleSelect(country)}
                className="w-full text-left px-4 py-3 hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-b-0 transition-colors"
              >
                <span className="text-lg">{country.flag}</span>
                <div>
                  <div className="font-medium text-gray-900">{country.name.common}</div>
                  <div className="text-xs text-gray-500">{country.name.official}</div>
                </div>
              </button>
            ))
          ) : (
            <div className="p-4 text-center text-gray-500">No countries found</div>
          )}
        </div>
      )}
    </div>
  );
};

// City Search Component with new design
const CitySearch = ({ 
  label, 
  country, 
  value, 
  onChange, 
  placeholder = "Search city..." 
}: {
  label: string;
  country: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [cities, setCities] = useState<string[]>([]);
  const [filteredCities, setFilteredCities] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);

  const fetchCities = useCallback(async () => {
    if (!country) return;

    setLoading(true);
    try {
      const response = await fetch(
        "https://countriesnow.space/api/v0.1/countries/cities",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ country })
        }
      );

      const data = await response.json();

      if (data?.data) {
        setCities(data.data);
        setFilteredCities(data.data.slice(0, 20));
      }
    } catch (error) {
      console.error("Error fetching cities:", error);
      setCities([]);
    } finally {
      setLoading(false);
    }
  }, [country]);

  useEffect(() => {
    fetchCities();
  }, [fetchCities]);

  useEffect(() => {
    if (!searchTerm) {
      setFilteredCities(cities.slice(0, 20));
    } else {
      const filtered = cities
        .filter(city =>
          city.toLowerCase().includes(searchTerm.toLowerCase())
        )
        .slice(0, 20);

      setFilteredCities(filtered);
    }
  }, [searchTerm, cities]);

  const handleSelect = (city: string) => {
    onChange(city);
    setSearchTerm(city);
    setShowDropdown(false);
  };

  return (
    <div className="space-y-2 relative">
      <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
        <MapPin className="w-4 h-4 text-gray-400" />
        {label}
      </label>

      <div className="relative">
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => {
            setSearchTerm(e.target.value);
            setShowDropdown(true);
          }}
          onFocus={() => setShowDropdown(true)}
          onBlur={() => setTimeout(() => setShowDropdown(false), 200)}
          placeholder={country ? `${placeholder} in ${country}` : placeholder}
          disabled={!country}
          className="w-full px-4 py-3 pl-10 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50 disabled:bg-gray-100"
        />
        <MapPin className="absolute left-3 top-3.5 w-4 h-4 text-gray-400" />
      </div>

      {showDropdown && (
        <div className="absolute z-10 w-full mt-2 bg-white border border-gray-200 rounded-2xl shadow-2xl max-h-60 overflow-y-auto">
          {loading ? (
            <div className="p-4 text-center text-gray-500">
              <Loader2 className="w-5 h-5 animate-spin mx-auto mb-2 text-teal-600" />
              Loading cities...
            </div>
          ) : filteredCities.length ? (
            filteredCities.map((city, index) => (
              <button
                key={index}
                type="button"
                onClick={() => handleSelect(city)}
                className="w-full text-left px-4 py-3 hover:bg-gray-50 border-b border-gray-100 last:border-b-0 transition-colors"
              >
                {city}
              </button>
            ))
          ) : (
            <div className="p-4 text-center text-gray-500">No cities found</div>
          )}
        </div>
      )}
    </div>
  );
};

// Consultant Card Component with new design
const ConsultantCard = ({ consultant }: { consultant: Consultant }) => (
  <ModernCard className="p-6">
    <div className="flex items-start justify-between mb-4">
      <div>
        <h4 className="font-bold text-gray-900 text-lg">{consultant.company_name}</h4>
        <p className="text-sm text-gray-600 mt-1">{consultant.name}</p>
      </div>
      <div className="text-right">
        <div className="text-lg font-bold text-teal-600">
          ${consultant.consultation_fee}
        </div>
        <div className="text-xs text-gray-500">Consultation Fee</div>
      </div>
    </div>
    
    <div className="flex items-center gap-2 mb-4">
      <div className="flex items-center">
        {[...Array(5)].map((_, i) => (
          <svg
            key={i}
            className={`w-4 h-4 ${i < Math.floor(consultant.average_rating) ? 'text-amber-400' : 'text-gray-300'}`}
            fill="currentColor"
            viewBox="0 0 20 20"
          >
            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
          </svg>
        ))}
        <span className="ml-2 text-sm text-gray-600">
          {consultant.average_rating.toFixed(1)} ({consultant.rating_count})
        </span>
      </div>
    </div>
    
    <div className="text-sm text-gray-700 mb-4">
      <span className="font-medium">Specializes in:</span>{' '}
      {consultant.specialization?.slice(0, 2).join(', ') || 'General immigration'}
    </div>
    
    <div className="text-sm text-gray-500 flex items-center gap-2 mb-4">
      <MapPin className="w-4 h-4" />
      {consultant.city}, {consultant.country}
    </div>
    
    <div className="flex items-center justify-between">
      <Badge color="teal" icon={Sparkles}>
        AI Match: {Math.round(consultant.ai_match_score)}%
      </Badge>
      <Link href={`/consultant/${consultant.seo_slug}`}>
        <button className="px-4 py-2 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 text-sm font-medium">
          View Profile
        </button>
      </Link>
    </div>
  </ModernCard>
);

export default function ChanceMyVisaPredictor() {
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [prediction, setPrediction] = useState<Prediction | null>(null);
  const [consultants, setConsultants] = useState<Consultant[]>([]);
  const [consultantsLoading, setConsultantsLoading] = useState(false);
  const [pdfLoading, setPdfLoading] = useState(false);
  
  // Lead modal states
  const [showLeadModal, setShowLeadModal] = useState(false);
  const [leadData, setLeadData] = useState<LeadData | null>(null);

  // Form state
  const [form, setForm] = useState({
    destinationCountry: '',
    visaType: '',
    age: 25,
    educationLevel: '',
    educationGapYears: 0,
    employmentStatus: '',
    jobExperienceYears: 0,
    previousRefusals: 0,
    financialSource: '',
    financialProofAmount: 10000,
    languageTest: '',
    languageScore: null as number | null,
    mediumOfInstruction: 'English',
    purposeOfTravel: '',
    familyTiesInHomeCountry: '',
    travelHistory: [] as string[],
    residenceCountry: '',
    residenceCity: ''
  });

  // Features array (matching reference design)
  const features = [
    {
      icon: Brain,
      title: "AI-Powered Analysis",
      description: "Advanced machine learning algorithms analyze global visa patterns and requirements",
      color: "from-teal-500 to-blue-500"
    },
    {
      icon: Shield,
      title: "92% Accuracy Rate",
      description: "Based on 10,000+ successful visa cases and real-world outcomes",
      color: "from-blue-500 to-cyan-400"
    },
    {
      icon: Target,
      title: "Personalized Recommendations",
      description: "Get tailored improvement plans based on your specific profile and situation",
      color: "from-emerald-500 to-teal-400"
    },
    {
      icon: Users,
      title: "Consultant Matching",
      description: "Connect with verified immigration experts matched to your needs",
      color: "from-amber-500 to-orange-400"
    }
  ];

  // Steps array (matching reference design)
  const steps = [
    {
      number: "01",
      title: "Profile Setup",
      description: "Enter your details and visa requirements",
      icon: <User className="w-5 h-5" />
    },
    {
      number: "02",
      title: "AI Analysis",
      description: "Our AI analyzes 20+ factors and global patterns",
      icon: <Brain className="w-5 h-5" />
    },
    {
      number: "03",
      title: "Detailed Report",
      description: "Get comprehensive results and recommendations",
      icon: <FileText className="w-5 h-5" />
    },
    {
      number: "04",
      title: "Action Plan",
      description: "Follow personalized steps for visa success",
      icon: <Target className="w-5 h-5" />
    }
  ];

  // Load saved form data from localStorage and merge with lead data
  useEffect(() => {
    const loadSavedData = () => {
      try {
        const savedFormData = localStorage.getItem(VISA_PREDICTOR_STORAGE_KEYS.FORM_DATA);
        const savedResult = localStorage.getItem(VISA_PREDICTOR_STORAGE_KEYS.LAST_RESULT);
        const savedSearch = localStorage.getItem(VISA_PREDICTOR_STORAGE_KEYS.LAST_SEARCH);
        const savedLead = localStorage.getItem('ai_visa_predictor_lead');
        
        let finalFormData = {
          destinationCountry: '',
          visaType: '',
          age: 25,
          educationLevel: '',
          educationGapYears: 0,
          employmentStatus: '',
          jobExperienceYears: 0,
          previousRefusals: 0,
          financialSource: '',
          financialProofAmount: 10000,
          languageTest: '',
          languageScore: null as number | null,
          mediumOfInstruction: 'English',
          purposeOfTravel: '',
          familyTiesInHomeCountry: '',
          travelHistory: [] as string[],
          residenceCountry: '',
          residenceCity: ''
        };

        // First, load from saved form data
        if (savedFormData) {
          try {
            const parsedForm = JSON.parse(savedFormData);
            finalFormData = {
              ...finalFormData,
              ...parsedForm,
              age: parsedForm.age || 25,
              educationGapYears: parsedForm.educationGapYears || 0,
              jobExperienceYears: parsedForm.jobExperienceYears || 0,
              previousRefusals: parsedForm.previousRefusals || 0,
              financialProofAmount: parsedForm.financialProofAmount || 10000,
              travelHistory: parsedForm.travelHistory || [],
              languageScore: parsedForm.languageScore || null
            };
          } catch (e) {
            console.error('Error parsing form data:', e);
          }
        }

        // Then, merge with lead data if it exists and is valid
        if (savedLead) {
          try {
            const lead = JSON.parse(savedLead);
            if (lead.expiry && lead.expiry > Date.now()) {
              // Update lead data state
              const leadDataToSet: LeadData = {
                name: lead.name,
                email: lead.email,
                phoneNumber: lead.phoneNumber
              };
              
              // Add form fields from lead data
              if (lead.destinationCountry) {
                leadDataToSet.destinationCountry = lead.destinationCountry;
                leadDataToSet.visaType = lead.visaType;
                leadDataToSet.age = lead.age;
                leadDataToSet.educationLevel = lead.educationLevel;
                leadDataToSet.educationGapYears = lead.educationGapYears;
                leadDataToSet.employmentStatus = lead.employmentStatus;
                leadDataToSet.jobExperienceYears = lead.jobExperienceYears;
                leadDataToSet.previousRefusals = lead.previousRefusals;
                leadDataToSet.financialSource = lead.financialSource;
                leadDataToSet.financialProofAmount = lead.financialProofAmount;
                leadDataToSet.languageTest = lead.languageTest;
                leadDataToSet.languageScore = lead.languageScore;
                leadDataToSet.mediumOfInstruction = lead.mediumOfInstruction;
                leadDataToSet.purposeOfTravel = lead.purposeOfTravel;
                leadDataToSet.familyTiesInHomeCountry = lead.familyTiesInHomeCountry;
                leadDataToSet.residenceCountry = lead.residenceCountry;
                leadDataToSet.residenceCity = lead.residenceCity;

                // Merge lead data into form
                finalFormData = {
                  ...finalFormData,
                  destinationCountry: lead.destinationCountry || finalFormData.destinationCountry,
                  visaType: lead.visaType || finalFormData.visaType,
                  age: lead.age || finalFormData.age,
                  educationLevel: lead.educationLevel || finalFormData.educationLevel,
                  educationGapYears: lead.educationGapYears || finalFormData.educationGapYears,
                  employmentStatus: lead.employmentStatus || finalFormData.employmentStatus,
                  jobExperienceYears: lead.jobExperienceYears || finalFormData.jobExperienceYears,
                  previousRefusals: lead.previousRefusals || finalFormData.previousRefusals,
                  financialSource: lead.financialSource || finalFormData.financialSource,
                  financialProofAmount: lead.financialProofAmount || finalFormData.financialProofAmount,
                  languageTest: lead.languageTest || finalFormData.languageTest,
                  languageScore: lead.languageScore || finalFormData.languageScore,
                  mediumOfInstruction: lead.mediumOfInstruction || finalFormData.mediumOfInstruction,
                  purposeOfTravel: lead.purposeOfTravel || finalFormData.purposeOfTravel,
                  familyTiesInHomeCountry: lead.familyTiesInHomeCountry || finalFormData.familyTiesInHomeCountry,
                  residenceCountry: lead.residenceCountry || finalFormData.residenceCountry,
                  residenceCity: lead.residenceCity || finalFormData.residenceCity,
                  travelHistory: finalFormData.travelHistory
                };
              }
              
              setLeadData(leadDataToSet);
            } else {
              // Clear expired lead
              localStorage.removeItem('ai_visa_predictor_lead');
            }
          } catch (leadError) {
            console.error('Error parsing lead data:', leadError);
          }
        }

        // Set the merged form data
        setForm(finalFormData);
        
        if (savedResult) {
          try {
            setPrediction(JSON.parse(savedResult));
          } catch (e) {
            console.error('Error parsing prediction:', e);
          }
        }
        
        // Auto-navigate to results if we have recent data
        if (savedSearch && savedResult) {
          try {
            const lastSearchDate = new Date(savedSearch);
            const oneDayAgo = new Date();
            oneDayAgo.setDate(oneDayAgo.getDate() - 1);
            if (lastSearchDate > oneDayAgo) {
              setStep(3);
            }
          } catch (e) {
            console.error('Error checking search date:', e);
          }
        }
      } catch (error) {
        console.error('Error loading saved data:', error);
      }
    };
    
    loadSavedData();
  }, []);

  // Save form data to localStorage whenever form changes
  useEffect(() => {
    const timer = setTimeout(() => {
      try {
        // Only save if form has actual values (not just defaults)
        if (form.destinationCountry || form.visaType || form.residenceCountry) {
          localStorage.setItem(VISA_PREDICTOR_STORAGE_KEYS.FORM_DATA, JSON.stringify(form));
        }
      } catch (error) {
        console.error('Error saving form to localStorage:', error);
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [form]);

  // Save prediction to localStorage
  useEffect(() => {
    if (prediction) {
      try {
        localStorage.setItem(VISA_PREDICTOR_STORAGE_KEYS.LAST_RESULT, JSON.stringify(prediction));
        localStorage.setItem(VISA_PREDICTOR_STORAGE_KEYS.LAST_SEARCH, new Date().toISOString());
      } catch (error) {
        console.error('Error saving prediction to localStorage:', error);
      }
    }
  }, [prediction]);

  // Function to send lead to database
  const sendLeadToDatabase = async (data: any) => {
    try {
      const leadPayload = {
        name: data.name || '',
        email: data.email || '',
        phoneNumber: data.phoneNumber || '',
        age: data.age || null,
        visaType: data.visaType || '',
        purposeOfTravel: data.purposeOfTravel || '',
        country: data.destinationCountry || '',
        destinationCountry: data.destinationCountry || '',
        residenceCountry: data.residenceCountry || '',
        residenceCity: data.residenceCity || '',
        educationLevel: data.educationLevel || '',
        educationGapYears: data.educationGapYears || 0,
        mediumOfInstruction: data.mediumOfInstruction || '',
        employmentStatus: data.employmentStatus || '',
        jobExperienceYears: data.jobExperienceYears || 0,
        languageTest: data.languageTest || '',
        languageScore: data.languageScore || null,
        financialSource: data.financialSource || '',
        financialProofAmount: data.financialProofAmount || 0,
        familyTiesInHomeCountry: data.familyTiesInHomeCountry || '',
        previousRefusals: data.previousRefusals || 0,
        source: 'ai_visa_predictor',
        timestamp: new Date().toISOString()
      };

      // Send to your database API
      const response = await fetch('/api/frontend/ai-visa-predictor/store', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(leadPayload)
      });

      if (!response.ok) {
        throw new Error('Failed to save lead to database');
      }

      console.log('Lead saved to database successfully');
    } catch (error) {
      console.error('Error saving lead to database:', error);
      throw error;
    }
  };

  // Function to handle lead modal success
  const handleLeadSuccess = async (newLeadData: LeadData) => {
    // Save to state
    setLeadData(newLeadData);
    
    // Create complete lead data with form values
    const leadWithExpiry = {
      ...newLeadData,
      expiry: Date.now() + (7 * 24 * 60 * 60 * 1000) // 7 days
    };
    
    // Also save current form data with lead
    const completeLeadData = {
      ...leadWithExpiry,
      // Add form data to lead
      destinationCountry: form.destinationCountry,
      visaType: form.visaType,
      age: form.age,
      educationLevel: form.educationLevel,
      educationGapYears: form.educationGapYears,
      employmentStatus: form.employmentStatus,
      jobExperienceYears: form.jobExperienceYears,
      previousRefusals: form.previousRefusals,
      financialSource: form.financialSource,
      financialProofAmount: form.financialProofAmount,
      languageTest: form.languageTest,
      languageScore: form.languageScore,
      mediumOfInstruction: form.mediumOfInstruction,
      purposeOfTravel: form.purposeOfTravel,
      familyTiesInHomeCountry: form.familyTiesInHomeCountry,
      residenceCountry: form.residenceCountry,
      residenceCity: form.residenceCity,
      travelHistory: form.travelHistory
    };
    
    localStorage.setItem('ai_visa_predictor_lead', JSON.stringify(completeLeadData));
    
    // Now proceed with the prediction
    await submitPredictionWithLead(completeLeadData);
  };

  // Function to submit prediction with lead data
  const submitPredictionWithLead = async (leadData: LeadData) => {
    setLoading(true);
    
    try {
      // Merge lead data with current form data
      const completeFormData = {
        ...form,
        // Override with lead data values if they exist
        destinationCountry: leadData.destinationCountry || form.destinationCountry,
        visaType: leadData.visaType || form.visaType,
        age: leadData.age || form.age,
        educationLevel: leadData.educationLevel || form.educationLevel,
        educationGapYears: leadData.educationGapYears || form.educationGapYears,
        employmentStatus: leadData.employmentStatus || form.employmentStatus,
        jobExperienceYears: leadData.jobExperienceYears || form.jobExperienceYears,
        previousRefusals: leadData.previousRefusals || form.previousRefusals,
        financialSource: leadData.financialSource || form.financialSource,
        financialProofAmount: leadData.financialProofAmount || form.financialProofAmount,
        languageTest: leadData.languageTest || form.languageTest,
        languageScore: leadData.languageScore || form.languageScore,
        mediumOfInstruction: leadData.mediumOfInstruction || form.mediumOfInstruction,
        purposeOfTravel: leadData.purposeOfTravel || form.purposeOfTravel,
        familyTiesInHomeCountry: leadData.familyTiesInHomeCountry || form.familyTiesInHomeCountry,
        residenceCountry: leadData.residenceCountry || form.residenceCountry,
        residenceCity: leadData.residenceCity || form.residenceCity
      };

      // Update form state with complete data
      setForm(completeFormData);
      
      // Save the complete form data
      localStorage.setItem(VISA_PREDICTOR_STORAGE_KEYS.FORM_DATA, JSON.stringify(completeFormData));
      
      // Combine for submission
      const submissionData = {
        ...completeFormData,
        name: leadData.name,
        email: leadData.email,
        phoneNumber: leadData.phoneNumber,
        timestamp: new Date().toISOString(),
        tool: 'AI Visa Success Predictor'
      };

      // 1. Get the AI prediction
      const predictionResponse = await fetch('/api/frontend/ai-visa-predictor', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submissionData)
      });

      const predictionResult = await predictionResponse.json();
      
      if (predictionResult.success) {
        setPrediction(predictionResult.data);
        
        // 2. Send lead data to database API in the background
        sendLeadToDatabase(submissionData).catch(error => {
          console.error('Failed to save lead to database:', error);
        });
        
        // 3. Fetch consultants for the results page
        const consultantQuery = `Find ${completeFormData.destinationCountry} ${completeFormData.visaType} visa consultants from ${completeFormData.residenceCity || completeFormData.residenceCountry}`;
        const consultantResponse = await fetch(
          `/api/frontend/ai-consultant-search?ai_query=${encodeURIComponent(consultantQuery)}`
        );
        
        const consultantData = await consultantResponse.json();
        if (consultantData.success && consultantData.data) {
          setConsultants(consultantData.data.slice(0, 3));
        }
        
        setStep(3);
      } else {
        console.warn('Prediction API returned error:', predictionResult.error);
        alert('Failed to get prediction. Please try again.');
      }
    } catch (error) {
      console.error('Error calling API:', error);
      alert('Failed to get prediction. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  // Handle form submission
  const handleSubmit = async () => {
    // Validate required fields from BOTH form and leadData
    const destinationCountry = form.destinationCountry || (leadData?.destinationCountry || '');
    const visaType = form.visaType || (leadData?.visaType || '');
    const residenceCountry = form.residenceCountry || (leadData?.residenceCountry || '');

    if (!destinationCountry || !visaType || !residenceCountry) {
      alert('Please select destination country, visa type, and your country of residence');
      return;
    }

    // Check if we have valid lead data
    const savedLead = localStorage.getItem('ai_visa_predictor_lead');
    let hasValidLead = false;
    let parsedLead: LeadData | null = null;
    
    if (savedLead) {
      try {
        parsedLead = JSON.parse(savedLead);
        hasValidLead = parsedLead.expiry && parsedLead.expiry > Date.now();
      } catch (error) {
        console.error('Error checking lead expiry:', error);
      }
    }

    // If no valid lead data, show lead modal
    if (!hasValidLead || !parsedLead) {
      setShowLeadModal(true);
      return;
    }

    // If we have valid lead data, update form and proceed
    if (parsedLead) {
      setLeadData(parsedLead);
      await submitPredictionWithLead(parsedLead);
    }
  };

  const downloadPDF = async () => {
    if (!prediction) return;
    
    setPdfLoading(true);
    try {
      const doc = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4'
      });

      doc.setFont("helvetica");
      
      // Title
      doc.setFontSize(20);
      doc.setTextColor(11, 111, 120);
      doc.text("Visa Success Prediction Report", 105, 20, { align: 'center' });
      
      doc.setFontSize(12);
      doc.setTextColor(100, 100, 100);
      doc.text(`Generated on: ${new Date(prediction.generatedAt).toLocaleDateString()}`, 105, 28, { align: 'center' });
      
      // Applicant Information
      doc.setFontSize(16);
      doc.setTextColor(0, 0, 0);
      doc.text("Applicant Information", 20, 40);
      
      doc.setFontSize(11);
      doc.setTextColor(60, 60, 60);
      doc.text(`Destination Country: ${form.destinationCountry}`, 20, 48);
      doc.text(`Visa Type: ${form.visaType}`, 20, 53);
      doc.text(`Age: ${form.age} years`, 20, 58);
      doc.text(`Education: ${form.educationLevel}`, 20, 63);
      doc.text(`Location: ${form.residenceCity ? `${form.residenceCity}, ` : ''}${form.residenceCountry}`, 20, 68);
      
      // Main Prediction Results
      doc.setFontSize(16);
      doc.setTextColor(0, 0, 0);
      doc.text("Prediction Results", 20, 80);
      
      doc.setFontSize(11);
      doc.setTextColor(60, 60, 60);
      
      // Success Probability with color
      const successColor = prediction.successProbability >= 70 ? [46, 125, 50] : 
                          prediction.successProbability >= 50 ? [237, 108, 2] : 
                          [211, 47, 47];
      
      doc.setTextColor(successColor[0], successColor[1], successColor[2]);
      doc.text(`Success Probability: ${prediction.successProbability}%`, 20, 88);
      
      doc.setTextColor(60, 60, 60);
      doc.text(`Risk Level: ${prediction.riskLevel.toUpperCase()}`, 20, 93);
      doc.text(`Predicted Outcome: ${prediction.predictedOutcome.replace(/_/g, ' ').toUpperCase()}`, 20, 98);
      doc.text(`AI Confidence: ${Math.round(prediction.confidence * 100)}%`, 20, 103);
      
      // Key Strengths
      if (prediction.keyStrengths?.length > 0) {
        doc.addPage();
        doc.setFontSize(16);
        doc.setTextColor(0, 0, 0);
        doc.text("Key Strengths", 20, 20);
        
        doc.setFontSize(11);
        doc.setTextColor(60, 60, 60);
        prediction.keyStrengths.forEach((strength, index) => {
          doc.text(`✓ ${strength}`, 25, 30 + (index * 7));
        });
      }
      
      // Risk Factors
      if (prediction.riskFactors?.length > 0) {
        let yPos = prediction.keyStrengths?.length > 0 ? 70 : 30;
        
        if (yPos > 250) {
          doc.addPage();
          yPos = 20;
        }
        
        doc.setFontSize(16);
        doc.setTextColor(0, 0, 0);
        doc.text("Risk Factors", 20, yPos);
        
        doc.setFontSize(11);
        prediction.riskFactors.forEach((risk, index) => {
          const currentY = yPos + 10 + (index * 15);
          if (currentY > 270) {
            doc.addPage();
            yPos = 20;
          }
          
          doc.setTextColor(60, 60, 60);
          doc.setFont("helvetica", "bold");
          doc.text(`${risk.factor} (${risk.severity.toUpperCase()} RISK)`, 25, currentY);
          doc.setFont("helvetica", "normal");
          doc.text(`Impact: ${risk.impact > 0 ? '+' : ''}${risk.impact}%`, 160, currentY);
          doc.text(risk.description, 25, currentY + 5, { maxWidth: 160 });
        });
      }
      
      // Improvement Suggestions
      if (prediction.improvementSuggestions?.length > 0) {
        doc.addPage();
        doc.setFontSize(16);
        doc.setTextColor(0, 0, 0);
        doc.text("Improvement Plan", 20, 20);
        
        doc.setFontSize(11);
        prediction.improvementSuggestions.forEach((suggestion, index) => {
          const y = 30 + (index * 25);
          doc.setTextColor(60, 60, 60);
          doc.setFont("helvetica", "bold");
          doc.text(`${suggestion.suggestion} [${suggestion.priority.toUpperCase()} PRIORITY]`, 25, y);
          doc.setFont("helvetica", "normal");
          doc.text(`Action: ${suggestion.action}`, 25, y + 5);
          doc.text(`Timeline: ${suggestion.timeline}`, 25, y + 10);
        });
      }
      
      // Document Checklist
      if (prediction.documentChecklist?.length > 0) {
        let yPos = 150;
        if (yPos + (prediction.documentChecklist.length * 7) > 270) {
          doc.addPage();
          yPos = 20;
        }
        
        doc.setFontSize(16);
        doc.setTextColor(0, 0, 0);
        doc.text("Required Documents", 20, yPos);
        
        doc.setFontSize(11);
        doc.setTextColor(60, 60, 60);
        prediction.documentChecklist.forEach((docItem, index) => {
          doc.text(`• ${docItem}`, 25, yPos + 10 + (index * 7));
        });
      }
      
      // Next Steps
      if (prediction.nextSteps?.length > 0) {
        doc.addPage();
        doc.setFontSize(16);
        doc.setTextColor(0, 0, 0);
        doc.text("Next Steps", 20, 20);
        
        doc.setFontSize(11);
        doc.setTextColor(60, 60, 60);
        prediction.nextSteps.forEach((step, index) => {
          doc.text(`${index + 1}. ${step}`, 25, 30 + (index * 7));
        });
      }
      
      // Disclaimer
      doc.addPage();
      doc.setFontSize(14);
      doc.setTextColor(211, 47, 47);
      doc.text("Important Disclaimer", 105, 20, { align: 'center' });
      
      doc.setFontSize(11);
      doc.setTextColor(100, 100, 100);
      const disclaimerLines = doc.splitTextToSize(prediction.disclaimer, 170);
      doc.text(disclaimerLines, 20, 30);
      
      // Save the PDF
      doc.save(`Visa-Prediction-Report-${form.destinationCountry}-${Date.now()}.pdf`);
      
    } catch (error) {
      console.error('Error generating PDF:', error);
      alert('Failed to generate PDF. Please try again.');
    } finally {
      setPdfLoading(false);
    }
  };

  const resetForm = () => {
    if (confirm('Clear all form data and start over?')) {
      setPrediction(null);
      setConsultants([]);
      setStep(1);
      
      // Clear localStorage data
      try {
        localStorage.removeItem(VISA_PREDICTOR_STORAGE_KEYS.LAST_RESULT);
        localStorage.removeItem(VISA_PREDICTOR_STORAGE_KEYS.LAST_SEARCH);
      } catch (error) {
        console.error('Error clearing localStorage:', error);
      }
    }
  };

  const getProbabilityColor = (probability: number) => {
    if (probability >= 70) return 'text-emerald-600';
    if (probability >= 50) return 'text-amber-600';
    return 'text-red-600';
  };

  const getProbabilityBgColor = (probability: number) => {
    if (probability >= 70) return 'bg-gradient-to-r from-emerald-500/20 to-teal-500/20';
    if (probability >= 50) return 'bg-gradient-to-r from-amber-500/20 to-yellow-500/20';
    return 'bg-gradient-to-r from-red-500/20 to-rose-500/20';
  };

  const getRiskLevelColor = (level: string) => {
    switch (level) {
      case 'low': return 'text-emerald-600 bg-emerald-100 border-emerald-200';
      case 'medium': return 'text-amber-600 bg-amber-100 border-amber-200';
      case 'high': return 'text-red-600 bg-red-100 border-red-200';
      default: return 'text-gray-600 bg-gray-100 border-gray-200';
    }
  };

  const getOutcomeColor = (outcome: string) => {
    switch (outcome) {
      case 'recommended_for_approval': return 'text-emerald-700 bg-emerald-50 border-emerald-200';
      case 'recommended_for_refusal': return 'text-red-700 bg-red-50 border-red-200';
      case 'borderline': return 'text-amber-700 bg-amber-50 border-amber-200';
      default: return 'text-gray-700 bg-gray-50 border-gray-200';
    }
  };

  const openFindConsultantsPage = () => {
    const queryParams = new URLSearchParams({
      ai_query: `Find consultants for ${form.destinationCountry} ${form.visaType} visa from ${form.residenceCity || form.residenceCountry}`,
      ...(form.educationLevel && { education_level: form.educationLevel }),
      ...(form.financialProofAmount && { min_funds: form.financialProofAmount.toString() }),
    });
    
    window.open(`/find-my-consultant?${queryParams.toString()}`, '_blank');
  };

  // Render progress bar (matching reference design)
  const renderProgressBar = (value: number, max: number, color = 'teal') => {
    const percentage = Math.min(100, Math.max(0, (value / max) * 100));
    
    const colorClasses: { [key: string]: string } = {
      teal: 'bg-gradient-to-r from-teal-500 to-blue-500',
      blue: 'bg-gradient-to-r from-blue-500 to-cyan-500',
      emerald: 'bg-gradient-to-r from-emerald-500 to-teal-500',
      amber: 'bg-gradient-to-r from-amber-500 to-orange-500'
    };
    
    return (
      <div className="w-full bg-gray-100 rounded-full h-2 overflow-hidden">
        <div 
          className={`h-2 rounded-full ${colorClasses[color] || 'bg-gradient-to-r from-teal-500 to-blue-500'}`}
          style={{ width: `${percentage}%` }}
        ></div>
      </div>
    );
  };

  // Main render
  return (
    <>
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
        {/* Hero Section (matching reference design) */}
        <div className="relative">
          {/* Background Gradient */}
          <div className="absolute inset-0 bg-gradient-to-r from-teal-50/50 to-blue-50/50"></div>
          
          {/* Animated Background Elements */}
          <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
            {[...Array(20)].map((_, i) => (
              <div
                key={i}
                className="absolute rounded-full bg-gradient-to-r from-teal-200/20 to-blue-200/20 animate-float"
                style={{
                  width: Math.random() * 100 + 50,
                  height: Math.random() * 100 + 50,
                  top: `${Math.random() * 100}%`,
                  left: `${Math.random() * 100}%`,
                  animationDelay: `${Math.random() * 5}s`,
                  animationDuration: `${Math.random() * 10 + 10}s`
                }}
              />
            ))}
          </div>

          <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-24">
            <div className="text-center">
              {/* Badge */}
              <div className="inline-flex items-center gap-2 bg-gradient-to-r from-teal-100 to-blue-100 text-teal-700 px-4 py-2 rounded-full text-sm font-semibold mb-6 animate-pulse">
                <Shield className="w-4 h-4" />
                AI-Powered Visa Predictor
              </div>

              {/* Main Heading */}
              <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-6 leading-tight">
                Predict Your{' '}
                <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  Visa Success
                </span>{' '}
                <br />
                with AI Analysis
              </h1>

              {/* Subheading */}
              <p className="text-xl md:text-2xl text-gray-600 mb-10 max-w-3xl mx-auto leading-relaxed">
                Get intelligent, data-driven visa success predictions based on global patterns. 
                Our AI analyzes 20+ factors to give you accurate insights and improvement plans.
              </p>

              {/* Start Prediction Button */}
              <div className="text-center mt-12">
                <button
                  onClick={() => setStep(1)}
                  className="px-12 py-4 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-2xl font-semibold text-lg hover:shadow-xl hover:scale-105 transition-all duration-300 flex items-center gap-3 mx-auto shadow-lg"
                >
                  <Brain className="w-6 h-6" />
                  Start AI Prediction
                  <ChevronRight className="w-5 h-5" />
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Features Section (matching reference design) */}
        <div className="py-20 bg-white z-10">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-16">
              <h2 className="text-4xl font-bold text-gray-900 mb-4">
                Why Use Our{' '}
                <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  AI Visa Predictor?
                </span>
              </h2>
              <p className="text-gray-600 text-lg max-w-3xl mx-auto">
                Get intelligent insights and make data-driven decisions for your visa application
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
              {features.map((feature, index) => (
                <FeatureCard
                  key={index}
                  icon={feature.icon}
                  title={feature.title}
                  description={feature.description}
                  color={feature.color}
                />
              ))}
            </div>
          </div>
        </div>

        {/* Main Content */}
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20">
          {/* Progress Steps (matching reference design) */}
          <div className="mb-12">
            <div className="flex items-center justify-center mb-8">
              {[1, 2, 3].map((stepNum) => (
                <div key={stepNum} className="flex items-center">
                  <div className={`flex items-center justify-center w-12 h-12 rounded-full border-2 font-bold text-lg ${
                    step === stepNum 
                      ? 'border-teal-600 bg-teal-600 text-white' 
                      : step > stepNum 
                      ? 'border-green-500 bg-green-500 text-white' 
                      : 'border-gray-300 bg-white text-gray-400'
                  }`}>
                    {step > stepNum ? <CheckCircle className="w-6 h-6" /> : stepNum}
                  </div>
                  {stepNum < 3 && (
                    <div className={`w-24 h-1 ${
                      step > stepNum ? 'bg-green-500' : 'bg-gray-200'
                    }`}></div>
                  )}
                </div>
              ))}
            </div>
            <div className="flex justify-center gap-16 text-center">
              <div>
                <div className="font-semibold text-gray-900">1. Profile Details</div>
                <div className="text-sm text-gray-500">Enter your information</div>
              </div>
              <div>
                <div className="font-semibold text-gray-900">2. AI Analysis</div>
                <div className="text-sm text-gray-500">Processing your data</div>
              </div>
              <div>
                <div className="font-semibold text-gray-900">3. Results & Plan</div>
                <div className="text-sm text-gray-500">Get detailed report</div>
              </div>
            </div>
          </div>

          {/* Main Content Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Left Panel - Form */}
            <div className="lg:col-span-2">
              <ModernCard className="p-8">
                {step === 1 && (
                  <>
                    <div className="flex items-center gap-3 mb-8">
                      <div className="p-3 rounded-xl bg-gradient-to-r from-teal-500 to-blue-500">
                        <Users className="w-6 h-6 text-white" />
                      </div>
                      <div>
                        <h2 className="text-2xl font-bold text-gray-900">Your Visa Profile</h2>
                        <p className="text-gray-600">Fill in your details for accurate prediction</p>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {/* Destination Country */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <Globe className="w-4 h-4 text-gray-400" />
                          Destination Country *
                        </label>
                        <select
                          value={form.destinationCountry}
                          onChange={(e) => setForm({...form, destinationCountry: e.target.value})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select destination country</option>
                          {DESTINATION_COUNTRIES.map(country => (
                            <option key={country} value={country}>{country}</option>
                          ))}
                        </select>
                      </div>

                      {/* Visa Type */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <FileText className="w-4 h-4 text-gray-400" />
                          Visa Type *
                        </label>
                        <select
                          value={form.visaType}
                          onChange={(e) => setForm({...form, visaType: e.target.value})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select visa type</option>
                          {VISA_TYPES.map(type => (
                            <option key={type} value={type}>{type}</option>
                          ))}
                        </select>
                      </div>

                      {/* Country of Residence */}
                      <CountrySearch
                        label="Your Country of Residence *"
                        value={form.residenceCountry}
                        onChange={(value) => setForm({...form, residenceCountry: value, residenceCity: ''})}
                        placeholder="Search your country..."
                      />

                      {/* City of Residence */}
                      <CitySearch
                        label="Your City of Residence"
                        country={form.residenceCountry}
                        value={form.residenceCity}
                        onChange={(value) => setForm({...form, residenceCity: value})}
                        placeholder="Enter your city..."
                      />

                      {/* Age */}
                      <NumberInputWithButtons
                        value={form.age}
                        onChange={(value) => setForm({...form, age: value})}
                        min={18}
                        max={70}
                        step={1}
                        label="Age"
                        suffix=" years"
                        icon={Users}
                      />

                      {/* Education Level */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <GraduationCap className="w-4 h-4 text-gray-400" />
                          Education Level *
                        </label>
                        <select
                          value={form.educationLevel}
                          onChange={(e) => setForm({...form, educationLevel: e.target.value})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select education level</option>
                          {EDUCATION_LEVELS.map(level => (
                            <option key={level} value={level}>{level}</option>
                          ))}
                        </select>
                      </div>

                      {/* Education Gap */}
                      <NumberInputWithButtons
                        value={form.educationGapYears}
                        onChange={(value) => setForm({...form, educationGapYears: value})}
                        min={0}
                        max={20}
                        step={1}
                        label="Education Gap"
                        suffix=" year(s)"
                        icon={History}
                      />

                      {/* Employment Status */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <Briefcase className="w-4 h-4 text-gray-400" />
                          Employment Status *
                        </label>
                        <select
                          value={form.employmentStatus}
                          onChange={(e) => setForm({...form, employmentStatus: e.target.value})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select employment status</option>
                          {EMPLOYMENT_STATUS.map(status => (
                            <option key={status} value={status}>{status}</option>
                          ))}
                        </select>
                      </div>

                      {/* Job Experience */}
                      <NumberInputWithButtons
                        value={form.jobExperienceYears}
                        onChange={(value) => setForm({...form, jobExperienceYears: value})}
                        min={0}
                        max={40}
                        step={1}
                        label="Job Experience"
                        suffix=" year(s)"
                        icon={Briefcase}
                      />

                      {/* Previous Refusals */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <AlertTriangle className="w-4 h-4 text-gray-400" />
                          Previous Visa Refusals
                        </label>
                        <div className="flex items-center gap-4">
                          {[0, 1, 2, 3].map(num => (
                            <button
                              key={num}
                              type="button"
                              onClick={() => setForm({...form, previousRefusals: num})}
                              className={`flex-1 py-3 text-center rounded-xl border-2 transition-all ${
                                form.previousRefusals === num
                                  ? 'border-teal-600 bg-teal-600/10 text-teal-600 font-semibold'
                                  : 'border-gray-200 hover:border-gray-300'
                              }`}
                            >
                              {num === 3 ? '3+' : num}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Financial Source */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <Banknote className="w-4 h-4 text-gray-400" />
                          Financial Source *
                        </label>
                        <select
                          value={form.financialSource}
                          onChange={(e) => setForm({...form, financialSource: e.target.value})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select financial source</option>
                          {FINANCIAL_SOURCES.map(source => (
                            <option key={source} value={source}>{source}</option>
                          ))}
                        </select>
                      </div>

                      {/* Financial Proof Amount */}
                      <FinancialInput
                        value={form.financialProofAmount}
                        onChange={(value) => setForm({...form, financialProofAmount: value})}
                        min={1000}
                        max={100000}
                        step={1000}
                      />

                      {/* Language Test */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <BookOpen className="w-4 h-4 text-gray-400" />
                          Language Test
                        </label>
                        <select
                          value={form.languageTest}
                          onChange={(e) => setForm({...form, languageTest: e.target.value, languageScore: null})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select language test</option>
                          {LANGUAGE_TESTS.map(test => (
                            <option key={test.value} value={test.value}>{test.label}</option>
                          ))}
                        </select>
                      </div>

                      {/* Language Score */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <BookOpen className="w-4 h-4 text-gray-400" />
                          Language Score
                        </label>
                        <div className="flex items-center gap-2">
                          <input
                            type="number"
                            min="0"
                            max="9"
                            step="0.5"
                            value={form.languageScore || ''}
                            onChange={(e) => setForm({...form, languageScore: e.target.value ? parseFloat(e.target.value) : null})}
                            disabled={!form.languageTest || form.languageTest === 'not_applicable'}
                            placeholder={
                              form.languageTest === 'ielts' ? 'e.g., 7.5 (out of 9)' :
                              form.languageTest === 'toefl' ? 'e.g., 100 (out of 120)' :
                              form.languageTest === 'pte' ? 'e.g., 65 (out of 90)' :
                              form.languageTest === 'celpip' ? 'e.g., 9 (out of 12)' :
                              form.languageTest === 'duolingo' ? 'e.g., 125 (out of 160)' :
                              form.languageTest === 'cael' ? 'e.g., 70 (out of 90)' :
                              'Enter score'
                            }
                            className="flex-1 px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent disabled:bg-gray-100"
                          />
                        </div>
                      </div>

                      {/* Family Ties */}
                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <Home className="w-4 h-4 text-gray-400" />
                          Family Ties in Home Country *
                        </label>
                        <select
                          value={form.familyTiesInHomeCountry}
                          onChange={(e) => setForm({...form, familyTiesInHomeCountry: e.target.value})}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        >
                          <option value="">Select strength of ties</option>
                          {FAMILY_TIES.map(tie => (
                            <option key={tie} value={tie}>{tie}</option>
                          ))}
                        </select>
                      </div>

                      {/* Purpose of Travel */}
                      <div className="md:col-span-2 space-y-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                          <Plane className="w-4 h-4 text-gray-400" />
                          Purpose of Travel *
                        </label>
                        <textarea
                          value={form.purposeOfTravel}
                          onChange={(e) => setForm({...form, purposeOfTravel: e.target.value})}
                          placeholder="Describe your purpose of travel in detail..."
                          rows={3}
                          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all bg-gray-50"
                        />
                      </div>
                    </div>

                    <div className="mt-8 flex justify-between items-center">
                      <div className="text-sm text-gray-500">
                        All fields marked with * are required
                      </div>
                      <button
                        onClick={() => setStep(2)}
                        disabled={!form.destinationCountry || !form.visaType || !form.educationLevel || !form.employmentStatus || !form.residenceCountry}
                        className="px-8 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 shadow-lg"
                      >
                        Continue to AI Analysis
                        <ChevronRight className="w-5 h-5" />
                      </button>
                    </div>
                  </>
                )}

                {step === 2 && (
                  <div className="text-center py-12">
                    <div className="relative w-32 h-32 mx-auto mb-8">
                      <div className="absolute inset-0 bg-gradient-to-r from-teal-400 to-blue-500 rounded-full opacity-20 animate-pulse"></div>
                      <div className="absolute inset-4 bg-gradient-to-r from-teal-500 to-blue-600 rounded-full flex items-center justify-center">
                        <Brain className="w-16 h-16 text-white" />
                      </div>
                      <div className="absolute -top-2 -right-2 w-10 h-10 bg-amber-400 rounded-full flex items-center justify-center">
                        <Zap className="w-5 h-5 text-white" />
                      </div>
                    </div>
                    
                    <h3 className="text-2xl font-bold text-gray-900 mb-4">
                      Analyzing Your Profile with AI
                    </h3>
                    
                    <div className="max-w-md mx-auto mb-8">
                      <div className="space-y-4">
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                          <span className="text-gray-600">Processing country requirements</span>
                          <div className="w-3 h-3 bg-emerald-500 rounded-full animate-pulse"></div>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                          <span className="text-gray-600">Analyzing risk factors</span>
                          <div className="w-3 h-3 bg-emerald-500 rounded-full animate-pulse"></div>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                          <span className="text-gray-600">Calculating success probability</span>
                          <div className="w-3 h-3 bg-blue-500 rounded-full animate-pulse"></div>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                          <span className="text-gray-600">Generating improvement plan</span>
                          <div className="w-3 h-3 bg-blue-500 rounded-full animate-pulse"></div>
                        </div>
                      </div>
                      
                      <div className="mt-6 bg-gray-100 rounded-full h-2 overflow-hidden">
                        <div 
                          className="bg-gradient-to-r from-emerald-400 via-blue-500 to-teal-600 h-full transition-all duration-1000 ease-out"
                          style={{ width: loading ? '80%' : '100%' }}
                        ></div>
                      </div>
                    </div>
                    
                    <div className="text-gray-500 text-sm mb-8">
                      <p>Our AI is comparing your profile against thousands of successful visa cases</p>
                      <p className="mt-1">
                        Destination: {form.destinationCountry} • 
                        From: {form.residenceCity ? `${form.residenceCity}, ` : ''}{form.residenceCountry}
                      </p>
                    </div>
                    
                    <div className="flex justify-center gap-4">
                      <button
                        onClick={() => setStep(1)}
                        className="px-6 py-3 border-2 border-gray-200 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors"
                      >
                        Back to Edit
                      </button>
                      <button
                        onClick={handleSubmit}
                        disabled={loading}
                        className="px-8 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 disabled:opacity-50 flex items-center gap-2 shadow-lg"
                      >
                        {loading ? (
                          <>
                            <Loader2 className="w-5 h-5 animate-spin" />
                            Processing...
                          </>
                        ) : (
                          <>
                            <Rocket className="w-5 h-5" />
                            Get AI Prediction
                          </>
                        )}
                      </button>
                    </div>
                  </div>
                )}

                {step === 3 && prediction && (
                  <div>
                    <div className="flex items-center justify-between mb-8">
                      <div className="flex items-center gap-3">
                        <div className="p-3 rounded-xl bg-gradient-to-r from-teal-500 to-blue-500">
                          <Target className="w-6 h-6 text-white" />
                        </div>
                        <div>
                          <h2 className="text-2xl font-bold text-gray-900">Your Visa Prediction Results</h2>
                          <p className="text-gray-600">Generated on {new Date(prediction.generatedAt).toLocaleDateString()}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={downloadPDF}
                          disabled={pdfLoading}
                          className="px-4 py-2 border border-gray-200 text-gray-600 rounded-xl hover:bg-gray-50 transition-colors flex items-center gap-2"
                          title="Download PDF Report"
                        >
                          {pdfLoading ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Download className="w-4 h-4" />
                          )}
                          PDF
                        </button>
                        <button
                          onClick={() => window.print()}
                          className="px-4 py-2 border border-gray-200 text-gray-600 rounded-xl hover:bg-gray-50 transition-colors"
                          title="Print Report"
                        >
                          <Printer className="w-4 h-4" />
                        </button>
                      </div>
                    </div>

                    {/* Location Summary */}
                    <ModernCard className="mb-6 p-6">
                      <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
                        <div className="flex items-center gap-3">
                          <div className="p-2 rounded-lg bg-teal-50 border border-teal-100">
                            <MapPin className="w-5 h-5 text-teal-600" />
                          </div>
                          <div>
                            <div className="text-sm text-gray-600">From</div>
                            <div className="font-bold text-gray-900">
                              {form.residenceCity ? `${form.residenceCity}, ` : ''}{form.residenceCountry}
                            </div>
                          </div>
                        </div>
                        <div className="text-teal-500 text-xl hidden sm:block">→</div>
                        <div className="text-teal-500 text-xl sm:hidden">↓</div>
                        <div className="flex items-center gap-3">
                          <div className="p-2 rounded-lg bg-emerald-50 border border-emerald-100">
                            <Target className="w-5 h-5 text-emerald-600" />
                          </div>
                          <div>
                            <div className="text-sm text-gray-600">Destination</div>
                            <div className="font-bold text-gray-900">{form.destinationCountry}</div>
                          </div>
                        </div>
                      </div>
                    </ModernCard>

                    {/* Main Prediction Card */}
                    <ModernCard className="mb-8 p-8">
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        {/* Success Probability */}
                        <div className={`p-6 rounded-2xl ${getProbabilityBgColor(prediction.successProbability)} border border-gray-200`}>
                          <div className="flex items-center gap-3 mb-4">
                            <div className="p-2 bg-white rounded-lg border border-gray-100">
                              <TrendingUp className={`w-6 h-6 ${getProbabilityColor(prediction.successProbability)}`} />
                            </div>
                            <div>
                              <div className="text-sm text-gray-500">Success Probability</div>
                              <div className={`text-4xl font-bold ${getProbabilityColor(prediction.successProbability)}`}>
                                {prediction.successProbability}%
                              </div>
                            </div>
                          </div>
                          <div className="text-sm text-gray-600">
                            AI Confidence: {Math.round(prediction.confidence * 100)}%
                          </div>
                          {renderProgressBar(prediction.successProbability, 100, 'teal')}
                        </div>

                        {/* Risk Level */}
                        <div className="p-6 rounded-2xl bg-white border border-gray-200">
                          <div className="flex items-center gap-3 mb-4">
                            <div className="p-2 bg-gray-50 rounded-lg border border-gray-100">
                              <Shield className="w-6 h-6 text-gray-600" />
                            </div>
                            <div>
                              <div className="text-sm text-gray-500">Risk Level</div>
                              <div className="text-2xl font-bold capitalize">
                                {prediction.riskLevel}
                              </div>
                            </div>
                          </div>
                          <div className="text-sm text-gray-600">
                            Based on {prediction.riskFactors?.length || 0} risk factors
                          </div>
                          <Badge color={prediction.riskLevel === 'low' ? 'emerald' : prediction.riskLevel === 'medium' ? 'amber' : 'red'}>
                            {prediction.riskLevel.toUpperCase()} RISK
                          </Badge>
                        </div>

                        {/* Predicted Outcome */}
                        <div className={`p-6 rounded-2xl border ${getOutcomeColor(prediction.predictedOutcome)}`}>
                          <div className="flex items-center gap-3 mb-4">
                            <div className="p-2 bg-white rounded-lg border border-gray-100">
                              {prediction.predictedOutcome === 'recommended_for_approval' ? (
                                <CheckCircle className="w-6 h-6 text-emerald-600" />
                              ) : prediction.predictedOutcome === 'recommended_for_refusal' ? (
                                <AlertTriangle className="w-6 h-6 text-red-600" />
                              ) : (
                                <Target className="w-6 h-6 text-amber-600" />
                              )}
                            </div>
                            <div>
                              <div className="text-sm text-gray-500">Predicted Outcome</div>
                              <div className="text-lg font-bold capitalize">
                                {prediction.predictedOutcome?.replace(/_/g, ' ') || 'borderline'}
                              </div>
                            </div>
                          </div>
                          <div className="text-sm text-gray-600">
                            AI recommendation based on patterns
                          </div>
                        </div>
                      </div>
                    </ModernCard>

                    {/* Key Strengths */}
                    {prediction.keyStrengths?.length > 0 && (
                      <ModernCard className="mb-8 p-8">
                        <div className="flex items-center gap-3 mb-6">
                          <div className="p-2 rounded-lg bg-emerald-50 border border-emerald-100">
                            <Award className="w-6 h-6 text-emerald-600" />
                          </div>
                          <div>
                            <h3 className="text-xl font-bold text-gray-900">Your Key Strengths</h3>
                            <p className="text-gray-600 text-sm">Positive factors in your application</p>
                          </div>
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          {prediction.keyStrengths.map((strength, index) => (
                            <div key={index} className="flex items-start gap-3 p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-xl border border-emerald-100">
                              <CheckCircle className="w-5 h-5 text-emerald-600 flex-shrink-0 mt-0.5" />
                              <span className="text-gray-700">{strength}</span>
                            </div>
                          ))}
                        </div>
                      </ModernCard>
                    )}

                    {/* Risk Factors */}
                    {prediction.riskFactors?.length > 0 && (
                      <ModernCard className="mb-8 p-8">
                        <div className="flex items-center gap-3 mb-6">
                          <div className="p-2 rounded-lg bg-amber-50 border border-amber-100">
                            <AlertTriangle className="w-6 h-6 text-amber-600" />
                          </div>
                          <div>
                            <h3 className="text-xl font-bold text-gray-900">Risk Factors Analysis</h3>
                            <p className="text-gray-600 text-sm">Areas that need attention</p>
                          </div>
                        </div>
                        <div className="space-y-4">
                          {prediction.riskFactors?.map((risk, index) => (
                            <div key={index} className="p-4 bg-white rounded-xl border border-gray-200 hover:border-red-200 transition-colors">
                              <div className="flex items-center justify-between mb-2">
                                <div className="flex items-center gap-2">
                                  <div className={`w-3 h-3 rounded-full ${
                                    risk.severity === 'high' ? 'bg-red-500' :
                                    risk.severity === 'medium' ? 'bg-amber-500' : 'bg-blue-500'
                                  }`}></div>
                                  <span className="font-semibold text-gray-900">{risk.factor}</span>
                                  <Badge color={risk.severity === 'high' ? 'red' : risk.severity === 'medium' ? 'amber' : 'blue'}>
                                    {risk.severity?.toUpperCase() || 'MEDIUM'} RISK
                                  </Badge>
                                </div>
                                <div className="text-sm text-gray-500">
                                  Impact: {risk.impact > 0 ? '+' : ''}{risk.impact}%
                                </div>
                              </div>
                              <p className="text-gray-600 text-sm">{risk.description}</p>
                            </div>
                          ))}
                        </div>
                      </ModernCard>
                    )}

                    {/* Improvement Suggestions */}
                    {prediction.improvementSuggestions?.length > 0 && (
                      <ModernCard className="mb-8 p-8">
                        <div className="flex items-center gap-3 mb-6">
                          <div className="p-2 rounded-lg bg-blue-50 border border-blue-100">
                            <Lightbulb className="w-6 h-6 text-blue-600" />
                          </div>
                          <div>
                            <h3 className="text-xl font-bold text-gray-900">AI-Powered Improvement Plan</h3>
                            <p className="text-gray-600 text-sm">Personalized recommendations</p>
                          </div>
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {prediction.improvementSuggestions?.map((suggestion, index) => (
                            <div key={index} className={`p-4 rounded-xl border ${
                              suggestion.priority === 'high' 
                                ? 'border-red-200 bg-red-50' 
                                : suggestion.priority === 'medium'
                                ? 'border-amber-200 bg-amber-50'
                                : 'border-blue-200 bg-blue-50'
                            }`}>
                              <div className="flex items-start justify-between mb-3">
                                <div className="flex items-center gap-2">
                                  <div className={`p-1 rounded ${
                                    suggestion.priority === 'high' 
                                      ? 'bg-red-100 text-red-600' 
                                      : suggestion.priority === 'medium'
                                      ? 'bg-amber-100 text-amber-600'
                                      : 'bg-blue-100 text-blue-600'
                                  }`}>
                                    {suggestion.priority === 'high' ? (
                                      <Zap className="w-3 h-3" />
                                    ) : suggestion.priority === 'medium' ? (
                                      <Clock className="w-3 h-3" />
                                    ) : (
                                      <Calendar className="w-3 h-3" />
                                    )}
                                  </div>
                                  <span className={`text-sm font-bold ${
                                    suggestion.priority === 'high' 
                                      ? 'text-red-700' 
                                      : suggestion.priority === 'medium'
                                      ? 'text-amber-700'
                                      : 'text-blue-700'
                                  }`}>
                                    {suggestion.priority?.toUpperCase() || 'MEDIUM'} PRIORITY
                                  </span>
                                </div>
                                <span className="text-xs text-gray-500">{suggestion.timeline}</span>
                              </div>
                              <h4 className="font-semibold text-gray-900 mb-2">{suggestion.suggestion}</h4>
                              <p className="text-sm text-gray-600">{suggestion.action}</p>
                            </div>
                          ))}
                        </div>
                      </ModernCard>
                    )}

                    {/* Recommended Consultants Section */}
                    {consultants.length > 0 && (
                      <ModernCard className="mb-8 p-8">
                        <div className="flex items-center justify-between mb-6">
                          <div className="flex items-center gap-3">
                            <div className="p-2 rounded-lg bg-teal-50 border border-teal-100">
                              <Users className="w-6 h-6 text-teal-600" />
                            </div>
                            <div>
                              <h3 className="text-xl font-bold text-gray-900">Recommended Consultants</h3>
                              <p className="text-gray-600 text-sm">Based on your profile</p>
                            </div>
                          </div>
                          <span className="text-sm text-gray-500">
                            Top {consultants.length} matches
                          </span>
                        </div>
                        
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          {consultants.map((consultant) => (
                            <ConsultantCard key={consultant.id} consultant={consultant} />
                          ))}
                        </div>
                        
                        <div className="mt-6 text-center">
                          <button
                            onClick={openFindConsultantsPage}
                            className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 font-medium"
                          >
                            View More Consultants
                            <ExternalLink className="w-4 h-4" />
                          </button>
                        </div>
                      </ModernCard>
                    )}

                    {/* Action Section */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                      {/* Document Checklist */}
                      <ModernCard className="p-6">
                        <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                          <FileText className="w-5 h-5 text-teal-600" />
                          Required Documents
                        </h3>
                        <div className="space-y-2">
                          {prediction.documentChecklist?.map((doc, index) => (
                            <div key={index} className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-xl transition-colors">
                              <div className="w-6 h-6 flex items-center justify-center">
                                <div className="w-2 h-2 bg-teal-500 rounded-full"></div>
                              </div>
                              <span className="text-gray-700">{doc}</span>
                            </div>
                          ))}
                        </div>
                      </ModernCard>

                      {/* Next Steps */}
                      <ModernCard className="p-6">
                        <div className="flex items-center gap-3 mb-4">
                          <div className="p-2 rounded-lg bg-gradient-to-r from-teal-500 to-blue-500">
                            <Rocket className="w-5 h-5 text-white" />
                          </div>
                          <h3 className="text-lg font-bold text-gray-900">Recommended Next Steps</h3>
                        </div>
                        <div className="space-y-3">
                          {prediction.nextSteps?.map((stepItem, index) => (
                            <div key={index} className="flex items-start gap-3 p-2 hover:bg-gray-50 rounded-xl transition-colors">
                              <div className="w-6 h-6 flex items-center justify-center bg-white border border-gray-300 rounded-full text-sm font-bold text-gray-700">
                                {index + 1}
                              </div>
                              <span className="text-gray-700">{stepItem}</span>
                            </div>
                          ))}
                        </div>
                      </ModernCard>
                    </div>

                    {/* Disclaimer */}
                    <ModernCard className="p-6 border-2 border-amber-100">
                      <div className="flex items-start gap-3">
                        <AlertTriangle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                        <div className="text-sm text-amber-700">
                          <p className="font-semibold mb-1">Disclaimer:</p>
                          <p>{prediction.disclaimer}</p>
                        </div>
                      </div>
                    </ModernCard>

                    {/* Action Buttons */}
                    <div className="mt-8 flex flex-col sm:flex-row gap-4 justify-between items-center">
                      <button
                        onClick={resetForm}
                        className="px-6 py-3 border-2 border-gray-200 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors flex items-center gap-2"
                      >
                        <Sparkles className="w-5 h-5" />
                        New Prediction
                      </button>
                      <div className="flex items-center gap-4">
                        <button
                          onClick={openFindConsultantsPage}
                          className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300 flex items-center gap-2"
                        >
                          <Users className="w-5 h-5" />
                          Find More Consultants
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </ModernCard>
            </div>

            {/* Right Panel - Stats & Info */}
            <div className="space-y-8">
              {/* AI Accuracy Card */}
              <ModernCard className="p-6">
                <div className="flex items-center gap-3 mb-4">
                  <div className="p-2 rounded-lg bg-gradient-to-r from-teal-500 to-blue-500">
                    <Brain className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <h3 className="font-bold text-gray-900">AI Prediction Accuracy</h3>
                    <p className="text-sm text-gray-600">Based on 10,000+ cases</p>
                  </div>
                </div>
                <div className="text-center py-4">
                  <div className="text-5xl font-bold text-teal-600 mb-2">92%</div>
                  <div className="text-sm text-gray-600">Match Rate with Actual Outcomes</div>
                </div>
                <div className="space-y-3 mt-4">
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600">High Confidence Predictions</span>
                      <span className="font-semibold">96% accurate</span>
                    </div>
                    {renderProgressBar(96, 100, 'emerald')}
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600">Medium Confidence</span>
                      <span className="font-semibold">88% accurate</span>
                    </div>
                    {renderProgressBar(88, 100, 'amber')}
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600">Low Confidence</span>
                      <span className="font-semibold">75% accurate</span>
                    </div>
                    {renderProgressBar(75, 100, 'blue')}
                  </div>
                </div>
              </ModernCard>

              {/* Tips Card */}
              <ModernCard className="p-6">
                <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                  <Sparkles className="w-5 h-5 text-teal-600" />
                  Tips for Higher Success
                </h3>
                <div className="space-y-4">
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 bg-emerald-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <CheckCircle className="w-4 h-4 text-emerald-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900">Complete Documentation</div>
                      <p className="text-sm text-gray-600">Ensure all documents are properly attested and translated</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <DollarSign className="w-4 h-4 text-blue-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900">Strong Financial Proof</div>
                      <p className="text-sm text-gray-600">Show 1.5x required funds with 6-month history</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 bg-teal-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <BookOpen className="w-4 h-4 text-teal-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900">Clear Purpose Statement</div>
                      <p className="text-sm text-gray-600">Articulate your goals and return plans clearly</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 bg-amber-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <Clock className="w-4 h-4 text-amber-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900">Apply Early</div>
                      <p className="text-sm text-gray-600">Apply 3-4 months before intended travel date</p>
                    </div>
                  </div>
                </div>
              </ModernCard>

              {/* CTA Card */}
              <ModernCard className="p-6 bg-gradient-to-r from-teal-50 to-blue-50 border-teal-100">
                <div className="text-center mb-4">
                  <div className="w-16 h-16 mx-auto bg-gradient-to-r from-teal-500 to-blue-500 rounded-full flex items-center justify-center mb-3">
                    <Users className="w-8 h-8 text-white" />
                  </div>
                  <h3 className="text-xl font-bold text-gray-900 mb-2">Need Professional Help?</h3>
                  <p className="text-gray-600 mb-4">Connect with verified immigration consultants</p>
                </div>
                <Link href="/find-my-consultant">
                  <button className="w-full py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-lg hover:scale-105 transition-all duration-300">
                    Find Expert Consultant
                  </button>
                </Link>
              </ModernCard>
            </div>
          </div>

          {/* ADDED: LeadModal component */}
          <LeadModal 
            isOpen={showLeadModal}
            onClose={() => setShowLeadModal(false)}
            onSuccess={handleLeadSuccess}
            formData={form}
          />

          {/* How It Works Section (matching reference design) */}
          <div className="mt-16 bg-gradient-to-br from-teal-50 to-blue-50 rounded-3xl border border-teal-100 p-8">
            <h3 className="text-2xl font-bold text-gray-900 mb-8 flex items-center gap-3">
              <Zap className="w-7 h-7 text-teal-600" />
              How It Works
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
              {steps.map((stepItem, index) => (
                <div key={index} className="flex flex-col items-center text-center">
                  <div className="w-16 h-16 bg-gradient-to-r from-teal-500 to-blue-500 text-white rounded-2xl flex items-center justify-center font-bold text-xl mb-4">
                    {stepItem.number}
                  </div>
                  <h4 className="text-lg font-bold text-gray-900 mb-2">{stepItem.title}</h4>
                  <p className="text-gray-600 text-sm">{stepItem.description}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Features Grid (matching reference design) */}
          <div className="mt-12 grid grid-cols-1 md:grid-cols-4 gap-6">
            <div className="bg-white p-6 rounded-3xl border border-gray-100 text-center hover:shadow-lg transition-all duration-300">
              <div className="w-12 h-12 mx-auto bg-gradient-to-r from-teal-500 to-blue-500 rounded-full flex items-center justify-center mb-3">
                <Brain className="w-6 h-6 text-white" />
              </div>
              <h4 className="font-bold text-gray-900 mb-2">AI-Powered Analysis</h4>
              <p className="text-sm text-gray-600">Uses DeepSeek AI to analyze global visa patterns</p>
            </div>
            <div className="bg-white p-6 rounded-3xl border border-gray-100 text-center hover:shadow-lg transition-all duration-300">
              <div className="w-12 h-12 mx-auto bg-gradient-to-r from-emerald-500 to-teal-500 rounded-full flex items-center justify-center mb-3">
                <Target className="w-6 h-6 text-white" />
              </div>
              <h4 className="font-bold text-gray-900 mb-2">92% Accuracy Rate</h4>
              <p className="text-sm text-gray-600">Based on 10,000+ successful predictions</p>
            </div>
            <div className="bg-white p-6 rounded-3xl border border-gray-100 text-center hover:shadow-lg transition-all duration-300">
              <div className="w-12 h-12 mx-auto bg-gradient-to-r from-blue-500 to-cyan-500 rounded-full flex items-center justify-center mb-3">
                <Shield className="w-6 h-6 text-white" />
              </div>
              <h4 className="font-bold text-gray-900 mb-2">Risk Assessment</h4>
              <p className="text-sm text-gray-600">Identifies 20+ risk factors and provides solutions</p>
            </div>
            <div className="bg-white p-6 rounded-3xl border border-gray-100 text-center hover:shadow-lg transition-all duration-300">
              <div className="w-12 h-12 mx-auto bg-gradient-to-r from-amber-500 to-orange-500 rounded-full flex items-center justify-center mb-3">
                <Rocket className="w-6 h-6 text-white" />
              </div>
              <h4 className="font-bold text-gray-900 mb-2">Actionable Plan</h4>
              <p className="text-sm text-gray-600">Step-by-step improvement roadmap with timelines</p>
            </div>
          </div>

          {/* Final CTA (matching reference design) */}
          <div className="mt-20 py-20 bg-gradient-to-r from-teal-600 to-blue-500 rounded-3xl">
            <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
              <h2 className="text-4xl font-bold text-white mb-6">
                Ready to Predict Your Visa Success?
              </h2>
              <p className="text-xl text-teal-100 mb-10 max-w-2xl mx-auto">
                Let our AI help you understand your chances and create a winning strategy
              </p>
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                <button
                  onClick={() => setStep(1)}
                  className="group bg-white text-teal-600 px-12 py-5 rounded-2xl text-lg font-bold shadow-2xl hover:shadow-3xl hover:scale-105 transition-all duration-300 flex items-center gap-3"
                >
                  <Brain className="animate-bounce" />
                  Start New Prediction
                  <ChevronRight className="transition-transform duration-300 group-hover:translate-x-2" />
                </button>
                
                <button
                  onClick={openFindConsultantsPage}
                  className="px-10 py-5 border-2 border-white/30 text-white rounded-2xl font-semibold hover:bg-white/10 transition-all duration-300 flex items-center gap-2"
                >
                  <Users className="w-5 h-5" />
                  Find Consultants
                </button>
              </div>

              {/* Guarantee Badge */}
              <div className="mt-12 inline-flex items-center gap-3 bg-white/10 backdrop-blur-sm px-8 py-4 rounded-full">
                <Shield className="text-white w-5 h-5" />
                <span className="text-white font-semibold">AI-Powered Analysis • Data-Driven Insights • 92% Accuracy</span>
              </div>
            </div>
          </div>

          {/* Footer Note */}
          <div className="mt-12 text-center text-gray-500 text-sm">
            <p>Note: This tool provides AI-based predictions and should not be considered legal advice.</p>
            <p className="mt-1">Always consult with licensed immigration professionals for your specific case.</p>
          </div>
        </main>
      </div>

      <style jsx global>{`
        @keyframes float {
          0%, 100% {
            transform: translateY(0) rotate(0deg);
          }
          50% {
            transform: translateY(-20px) rotate(180deg);
          }
        }
        
        .animate-float {
          animation: float 20s infinite linear;
        }
      `}</style>
    </>
  );
}