'use client';

import React, { useState, useEffect, useRef } from 'react';
import { 
  Search, Brain, Award, Target, Sparkles, User, 
  GraduationCap, Globe, DollarSign, Clock, TrendingUp,
  Filter, X, MessageSquare, Save, Download,
  ChevronRight, ChevronLeft, Star, Rocket, Coins,
  MapPin, Calendar, Percent, Users, Trophy, AlertCircle,
  BookOpen, FileText, Check, Zap, Eye, Settings,
  BarChart3, Target as TargetIcon, Cpu, Database,
  Mail, Phone, Home, Briefcase, School, Activity,
  Mic, MicOff, Command, Send, Lightbulb, Bot,
  Circle, Shield, AlertTriangle, ThumbsUp,
  Loader2, CheckCircle, Edit3, Info, Globe as GlobeIcon,
  TrendingDown, Award as AwardIcon, Maximize2, Minimize2,
  BarChart, PieChart, LineChart, Gauge, Target as TargetArrow,
  Crown, Gem, ShieldCheck, ShieldAlert, BookMarked,
  Target as TargetIcon2, Smartphone, Laptop,
  Plus, Bookmark, BookmarkCheck, ClipboardList, ExternalLink,
  Home as HomeIcon, Building2, CalendarDays, Languages,
  Send as SendIcon, DownloadCloud, Printer, Share2,
  RefreshCw, HelpCircle, Shield as ShieldIcon
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import LeadModal from '../../components/LeadModal';
import { LucideIcon } from 'lucide-react';

interface BadgeProps {
  children: React.ReactNode;
  color?: 'teal' | 'blue' | 'emerald' | 'amber' | 'gray';
  icon?: LucideIcon;
}


// Types
interface PersonalInfo {
  fullName: string;
  email: string;
  age: string;
  nationality: string;
  currentCountry: string;
}

interface AcademicInfo {
  educationLevel: string;
  cgpa: string;
  fieldOfStudy: string;
  languageScore: string;
  researchExperience?: string;
  publications?: string;
  awards?: string;
}

interface Preferences {
  countries: string[];
  degreeLevel: string;
  scholarshipType: string;
  fundingPriority: 'full' | 'partial' | 'any';
  applicationDeadline?: string;
}

interface Profile {
  personal: PersonalInfo;
  academic: AcademicInfo;
  preferences: Preferences;
}

interface Scholarship {
  id: number;
  title: string;
  slug?: string;
  country: string;
  amount_min?: number;
  amount_max?: number;
  amount?: number;
  deadline: string;
  matchScore: number;
  type: string;
  description: string;
  eligibility: string[];
  aiInsight: string;
  link: string;
  saved: boolean;
  tags?: string[];
  percentage_cover?: number;
  required_cgpa?: string;
  ielts?: number;
  currency_symbol?: string;
}

interface Analysis {
  overallScore: number;
  strengths: {
    category: string;
    items: string[];
    score: number;
  }[];
  weaknesses: {
    category: string;
    items: string[];
    impact: 'high' | 'medium' | 'low';
  }[];
  recommendations: {
    priority: 'high' | 'medium' | 'low';
    action: string;
    timeline: string;
    impact: string;
  }[];
  estimatedSuccess: number;
  totalMatches: number;
  totalFunding: string;
  profileStrength: {
    academic: number;
    profileCompleteness: number;
    competitiveness: number;
    readiness: number;
  };
  riskFactors: {
    factor: string;
    likelihood: 'high' | 'medium' | 'low';
    impact: 'high' | 'medium' | 'low';
    mitigation: string;
  }[];
  timelineRecommendations: {
    task: string;
    deadline: string;
    priority: 'high' | 'medium' | 'low';
  }[];
  scholarshipCategories: {
    highMatch: number;
    mediumMatch: number;
    lowMatch: number;
  };
  matchBreakdown: {
    academicMatch: number;
    countryMatch: number;
    fundingMatch: number;
    timelineMatch: number;
  };
  aiInsights: string[];
  competitiveAnalysis: {
    percentile: number;
    strengths: string[];
    opportunities: string[];
  };
}

interface ScholarshipLeadData {
  name: string;
  email: string;
  phoneNumber: string;
}

// Storage keys
const STORAGE_KEYS = {
  LAST_SEARCH: 'scholarship_last_search',
  LAST_RESULT: 'scholarship_last_result',
  FORM_DATA: 'scholarship_form_data',
  USER_DATA: 'scholarship_user_data',
  SCHOLARSHIP_LEAD: 'scholarship_lead'
};

// Modern Card Component
const ModernCard = ({ children, className = '', hover = true }) => (
  <div className={`bg-white rounded-3xl border border-gray-100 shadow-sm hover:shadow-lg transition-all duration-300 ${hover ? 'hover:border-teal-200' : ''} ${className}`}>
    {children}
  </div>
);

// Badge Component
const Badge: React.FC<BadgeProps> = ({
  children,
  color = 'teal',
  icon: Icon
}) => {
  const colorClasses = {
    teal: 'bg-teal-100 text-teal-700 border-teal-200',
    blue: 'bg-blue-100 text-blue-700 border-blue-200',
    emerald: 'bg-emerald-100 text-emerald-700 border-emerald-200',
    amber: 'bg-amber-100 text-amber-700 border-amber-200',
    gray: 'bg-gray-100 text-gray-700 border-gray-200'
  };

  return (
    <span
      className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium border ${colorClasses[color]}`}
    >
      {Icon && <Icon className="w-3.5 h-3.5" />}
      {children}
    </span>
  );
};


// Feature Card Component
const FeatureCard = ({ icon: Icon, title, description, color = 'from-teal-500 to-blue-500' }) => (
  <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>
);

const AiScholarshipMatch = () => {
  // State
  const [profile, setProfile] = useState<Profile>({
    personal: {
      fullName: '',
      email: '',
      age: '',
      nationality: '',
      currentCountry: ''
    },
    academic: {
      educationLevel: '',
      cgpa: '',
      fieldOfStudy: '',
      languageScore: '',
      researchExperience: '',
      publications: '',
      awards: ''
    },
    preferences: {
      countries: [],
      degreeLevel: '',
      scholarshipType: 'any',
      fundingPriority: 'any'
    }
  });

  const [scholarships, setScholarships] = useState<Scholarship[]>([]);
  const [filteredScholarships, setFilteredScholarships] = useState<Scholarship[]>([]);
  const [analysis, setAnalysis] = useState<Analysis | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [activeTab, setActiveTab] = useState('dashboard');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedFilters, setSelectedFilters] = useState({
    minScore: 70,
    maxAmount: 100000,
    countries: [] as string[],
    types: [] as string[],
    deadlineWithin: 'any'
  });
  const [showFilters, setShowFilters] = useState(false);
  const [profileProgress, setProfileProgress] = useState(0);
  const [aiSuggestions, setAiSuggestions] = useState<string[]>([]);
  const [savedCount, setSavedCount] = useState(0);
  const [toast, setToast] = useState<{message: string; type: 'success' | 'error' | 'info'; visible: boolean}>({
    message: '',
    type: 'success',
    visible: false
  });
  const [isListening, setIsListening] = useState(false);
  const [advancedSearchOpen, setAdvancedSearchOpen] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [isVoiceAvailable, setIsVoiceAvailable] = useState(false);
  const [profileCompletionModal, setProfileCompletionModal] = useState(false);
  const [isAnalysisLoading, setIsAnalysisLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<Scholarship[]>([]);
  const [searchInsights, setSearchInsights] = useState<string[]>([]);
  const [searchSummary, setSearchSummary] = useState<string>('');
  const [showLeadModal, setShowLeadModal] = useState(false);
  const [leadData, setLeadData] = useState<ScholarshipLeadData | null>(null);
  
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);
  const recognitionRef = useRef<any>(null);
  const lastSavedProfile = useRef<string>('');
  const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Countries and options
  const countries = [
    'USA', 'Canada', 'UK', 'Australia', 'Germany',
    'France', 'Japan', 'Singapore', 'China', 'UAE',
    'New Zealand', 'Netherlands', 'Sweden', 'Switzerland',
    'Ireland', 'Norway', 'Denmark', 'Finland'
  ];

  const educationLevels = [
    'High School', 'Diploma', 'Associate Degree', 'Bachelor\'s', 
    'Master\'s', 'PhD', 'Postdoctoral'
  ];

  const fieldsOfStudy = [
    'Computer Science', 'Engineering', 'Business Administration', 'Medicine',
    'Arts & Humanities', 'Social Sciences', 'Natural Sciences', 'Mathematics',
    'Architecture', 'Design', 'Education', 'Law', 'Agriculture',
    'Environmental Science', 'Data Science', 'Artificial Intelligence'
  ];

  const scholarshipTypes = [
    'full_tuition', 'fully_funded', 'partial', 'tuition_waiver',
    'government_scholarship', 'university_scholarship', 'research_grant', 'merit_based'
  ];

  // Enhanced Profile Progress Calculation
  const calculateProfileProgress = (profile: Profile): number => {
    let filledFields = 0;
    let totalFields = 0;

    const personalFields = ['fullName', 'email', 'age', 'nationality', 'currentCountry'];
    totalFields += personalFields.length;
    personalFields.forEach(field => {
      if (profile?.personal?.[field as keyof PersonalInfo]?.trim()) filledFields++;
    });

    const academicFields = ['educationLevel', 'cgpa', 'fieldOfStudy', 'languageScore'];
    totalFields += academicFields.length;
    academicFields.forEach(field => {
      if (profile?.academic?.[field as keyof AcademicInfo]?.trim()) filledFields++;
    });

    const preferenceFields = ['countries', 'degreeLevel', 'fundingPriority'];
    totalFields += preferenceFields.length;
    preferenceFields.forEach(field => {
      const value = profile?.preferences?.[field as keyof Preferences];
      if (Array.isArray(value)) {
        if (value.length > 0) filledFields++;
      } else if (value?.toString()?.trim()) {
        filledFields++;
      }
    });

    return Math.round((filledFields / totalFields) * 100);
  };

  // Load saved data
  useEffect(() => {
    const loadSavedData = () => {
      try {
        const savedFormData = localStorage.getItem(STORAGE_KEYS.FORM_DATA);
        const savedResult = localStorage.getItem(STORAGE_KEYS.LAST_RESULT);
        const savedAnalysis = localStorage.getItem('scholarshipAnalysis');
        const savedHistory = localStorage.getItem('searchHistory');
        const savedLead = localStorage.getItem(STORAGE_KEYS.SCHOLARSHIP_LEAD);
        
        if (savedFormData) setProfile(JSON.parse(savedFormData));
        if (savedResult) setScholarships(JSON.parse(savedResult));
        if (savedAnalysis) setAnalysis(JSON.parse(savedAnalysis));
        if (savedHistory) setSearchHistory(JSON.parse(savedHistory) || []);
        
        // Load lead data
        if (savedLead) {
          try {
            const lead = JSON.parse(savedLead);
            // Check if lead is still valid (7 days expiry)
            if (lead.expiry && lead.expiry > Date.now()) {
              setLeadData({
                name: lead.name,
                email: lead.email,
                phoneNumber: lead.phoneNumber
              });
            }
          } catch (error) {
            console.error('Error loading lead data:', error);
          }
        }
      } catch (err) {
        console.error('Error loading saved data:', err);
      }
    };
    
    loadSavedData();
  }, []);

  // Save data to localStorage
  useEffect(() => {
    if (scholarships.length > 0) {
      try {
        localStorage.setItem(STORAGE_KEYS.LAST_RESULT, JSON.stringify(scholarships));
        localStorage.setItem(STORAGE_KEYS.FORM_DATA, JSON.stringify(profile));
        localStorage.setItem(STORAGE_KEYS.LAST_SEARCH, new Date().toISOString());
      } catch (err) {
        console.error('Error saving to localStorage:', err);
      }
    }
  }, [scholarships, profile]);

  // Update profile progress when profile changes
  useEffect(() => {
    const progress = calculateProfileProgress(profile);
    setProfileProgress(progress);
    
    // Show modal if profile is incomplete and user is trying to use features
    if (progress < 100 && (activeTab === 'matches' || activeTab === 'analysis') && scholarships?.length === 0) {
      setProfileCompletionModal(true);
    }
    
    // Save profile with debounce
    if (saveTimeoutRef.current) {
      clearTimeout(saveTimeoutRef.current);
    }
    
    saveTimeoutRef.current = setTimeout(() => {
      saveProfile();
    }, 1000);
    
    return () => {
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
    };
  }, [profile, activeTab]);

  const saveProfile = () => {
    try {
      const profileString = JSON.stringify(profile);
      
      if (profileString !== lastSavedProfile.current) {
        localStorage.setItem(STORAGE_KEYS.FORM_DATA, profileString);
        lastSavedProfile.current = profileString;
      }
    } catch (error) {
      console.error('Failed to save profile', error);
    }
  };

  // Check for lead data before performing actions
  const checkLeadAndProceed = (action: 'match' | 'search' | 'analysis'): boolean => {
    const savedLead = localStorage.getItem(STORAGE_KEYS.SCHOLARSHIP_LEAD);
    let hasValidLead = false;
    
    if (savedLead) {
      try {
        const lead = JSON.parse(savedLead);
        hasValidLead = lead.expiry && lead.expiry > Date.now();
      } catch (error) {
        console.error('Error checking lead expiry:', error);
      }
    }

    if (!hasValidLead || !leadData) {
      setShowLeadModal(true);
      return false;
    }
    
    return true;
  };

  // Send lead data to backend
  const sendLeadToDatabase = async (searchType: 'match' | 'search' | 'analysis' | 'lead_capture', matchedCount: number = 0, analysisScore: number = 0) => {
    if (!leadData) return;

    try {
      const leadPayload = {
        name: leadData.name,
        email: leadData.email,
        phoneNumber: leadData.phoneNumber,
        age: profile.personal.age || '',
        nationality: profile.personal.nationality || '',
        currentCountry: profile.personal.currentCountry || '',
        educationLevel: profile.academic.educationLevel || '',
        cgpa: parseFloat(profile.academic.cgpa?.replace(/[^0-9.]/g, '')) || 0,
        fieldOfStudy: profile.academic.fieldOfStudy || '',
        languageScore: parseFloat(profile.academic.languageScore?.replace(/[^0-9.]/g, '')) || 0,
        languageProof: profile.academic.languageScore ? 'IELTS' : '',
        researchExperience: profile.academic.researchExperience || '',
        publications: profile.academic.publications || '',
        awards: profile.academic.awards || '',
        preferredCountries: profile.preferences.countries || [],
        degreeLevel: profile.preferences.degreeLevel || '',
        fundingPriority: profile.preferences.fundingPriority || '',
        searchType: searchType,
        matchedCount: matchedCount,
        analysisScore: analysisScore,
        profileProgress: profileProgress,
        profileData: profile
      };

      // Send to Laravel API
      const response = await fetch('/api/frontend/ai-scholarship-match/store', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': process.env.NEXT_PUBLIC_API_SECRET_KEY || ''
        },
        body: JSON.stringify(leadPayload)
      });

      if (!response.ok) {
        throw new Error('Failed to save lead to database');
      }

      console.log('Scholarship lead saved to database successfully');
    } catch (error) {
      console.error('Error saving scholarship lead to database:', error);
    }
  };

  // Calculate AI Match Score
  const calculateAIMatchScore = (scholarship: Scholarship, profile: Profile): number => {
    let score = 60;
    
    // Academic Match (35 points)
    const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const requiredCGPA = parseFloat(scholarship?.required_cgpa || '0');
    
    if (requiredCGPA === 0 || studentCGPA >= requiredCGPA) {
      score += 30;
    } else if (studentCGPA >= (requiredCGPA - 0.3)) {
      score += 20;
    } else if (studentCGPA >= (requiredCGPA - 0.5)) {
      score += 15;
    }
    
    // Field of Study Match (25 points)
    const studentField = profile?.academic?.fieldOfStudy?.toLowerCase() || '';
    const scholarshipTitle = scholarship?.title?.toLowerCase() || '';
    const scholarshipDesc = scholarship?.description?.toLowerCase() || '';
    
    if (studentField && (scholarshipTitle.includes(studentField) || scholarshipDesc.includes(studentField))) {
      score += 25;
    } else if (studentField) {
      const fieldKeywords: { [key: string]: string[] } = {
        'computer science': ['cs', 'computer', 'programming', 'software', 'ai', 'machine learning', 'data science'],
        'engineering': ['engineering', 'mechanical', 'electrical', 'civil', 'chemical', 'aerospace'],
        'business administration': ['business', 'management', 'mba', 'finance', 'marketing', 'administration'],
        'medicine': ['medicine', 'medical', 'health', 'nursing', 'pharmacy', 'healthcare'],
        'arts & humanities': ['arts', 'humanities', 'history', 'literature', 'philosophy'],
        'social sciences': ['social', 'psychology', 'sociology', 'economics', 'political science'],
        'natural sciences': ['science', 'biology', 'chemistry', 'physics', 'environmental'],
        'data science': ['data', 'analytics', 'statistics', 'machine learning', 'ai'],
        'artificial intelligence': ['ai', 'machine learning', 'deep learning', 'neural networks']
      };
      
      const keywords = fieldKeywords[studentField] || [];
      if (keywords.some(keyword => scholarshipTitle.includes(keyword) || scholarshipDesc.includes(keyword))) {
        score += 15;
      }
    }
    
    // Country Preference Match (20 points)
    const preferredCountries = profile?.preferences?.countries || [];
    const scholarshipCountry = scholarship?.country?.toLowerCase() || '';
    
    if (preferredCountries?.length > 0) {
      const isPreferred = preferredCountries.some(country => 
        scholarshipCountry.includes(country?.toLowerCase())
      );
      if (isPreferred) {
        score += 20;
      }
    } else {
      score += 10;
    }
    
    // Funding Priority Match (15 points)
    const fundingPriority = profile?.preferences?.fundingPriority;
    const scholarshipType = scholarship?.type;
    const scholarshipCover = scholarship?.percentage_cover || 0;
    
    if (fundingPriority === 'full' && (scholarshipType === 'fully_funded' || scholarshipCover >= 75)) {
      score += 15;
    } else if (fundingPriority === 'partial' && (scholarshipType === 'partial' || (scholarshipCover >= 25 && scholarshipCover < 75))) {
      score += 15;
    } else if (fundingPriority === 'any') {
      score += 15;
    }
    
    // Language Proficiency Match (10 points)
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    const requiresIELTS = scholarship?.ielts === 1;
    
    if (!requiresIELTS) {
      score += 10;
    } else if (languageScore >= 7.5) {
      score += 10;
    } else if (languageScore >= 7.0) {
      score += 8;
    } else if (languageScore >= 6.5) {
      score += 5;
    }
    
    // Deadline Proximity Bonus (5 points)
    try {
      if (scholarship?.deadline && scholarship.deadline !== 'Rolling Admission') {
        const deadline = new Date(scholarship.deadline);
        const now = new Date();
        const diffTime = deadline.getTime() - now.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        if (diffDays <= 90 && diffDays > 0) {
          score += 5;
        }
      }
    } catch (e) {}
    
    // Amount Bonus (5 points)
    const amount = scholarship?.amount || 0;
    if (amount > 50000) score += 5;
    else if (amount > 25000) score += 3;
    
    return Math.max(40, Math.min(100, Math.round(score)));
  };

  // Generate mock scholarships as fallback
  const generateMockScholarships = (profile: Profile): Scholarship[] => {
    const mockScholarships: Scholarship[] = [
      {
        id: 1,
        title: 'International Computer Science Scholarship',
        country: 'USA',
        amount: 25000,
        deadline: '2024-06-30',
        matchScore: calculateAIMatchScore({
          id: 1,
          title: 'International Computer Science Scholarship',
          country: 'USA',
          amount: 25000,
          deadline: '2024-06-30',
          matchScore: 0,
          type: 'fully_funded',
          description: 'For international students in Computer Science',
          eligibility: ['GPA 3.0+', 'IELTS 6.5+'],
          aiInsight: 'Good match for Computer Science students',
          link: '#',
          saved: false,
          required_cgpa: '3.0'
        }, profile),
        type: 'fully_funded',
        description: 'Scholarship for international Computer Science students in USA',
        eligibility: ['Minimum GPA 3.0', 'IELTS 6.5 or equivalent', 'Admission to accredited university'],
        aiInsight: 'Excellent opportunity for Computer Science students with competitive academic records',
        link: '#',
        saved: false,
        tags: ['Computer Science', 'USA', 'Full Tuition'],
        percentage_cover: 100,
        required_cgpa: '3.0',
        ielts: 1
      },
      {
        id: 2,
        title: 'Engineering Excellence Scholarship',
        country: 'Canada',
        amount: 20000,
        deadline: '2024-07-15',
        matchScore: calculateAIMatchScore({
          id: 2,
          title: 'Engineering Excellence Scholarship',
          country: 'Canada',
          amount: 20000,
          deadline: '2024-07-15',
          matchScore: 0,
          type: 'partial',
          description: 'For Engineering students',
          eligibility: ['GPA 3.2+'],
          aiInsight: 'Partial funding for Engineering',
          link: '#',
          saved: false,
          required_cgpa: '3.2'
        }, profile),
        type: 'partial',
        description: 'Partial scholarship for Engineering students in Canadian universities',
        eligibility: ['GPA 3.2+', 'Proof of admission', 'Letter of recommendation'],
        aiInsight: 'Good match for Engineering students with strong academic performance',
        link: '#',
        saved: false,
        tags: ['Engineering', 'Canada', 'Partial'],
        percentage_cover: 50,
        required_cgpa: '3.2',
        ielts: 0
      }
    ];
    
    return mockScholarships.sort((a, b) => b.matchScore - a.matchScore);
  };

  const calculateAmount = (min?: number, max?: number): number => {
    if (min && max) return Math.round((min + max) / 2);
    if (min) return min;
    if (max) return max;
    return Math.floor(Math.random() * 30000) + 10000;
  };

  const getScholarshipType = (percentage?: number): string => {
    if (!percentage) return 'variable';
    if (percentage === 100) return 'full_tuition';
    if (percentage >= 75) return 'fully_funded';
    if (percentage >= 50) return 'partial';
    return 'variable';
  };

  // Fetch scholarships with lead check
  const fetchScholarships = async () => {
    if (profileProgress < 50) {
      showToast('Complete at least 50% of your profile for better matches', 'info');
      setProfileCompletionModal(true);
      return;
    }

    // Check lead before proceeding
    if (!checkLeadAndProceed('match')) {
      return;
    }

    setIsLoading(true);
    try {
      // Combine lead data with profile data for API
      const submissionData = {
        profile: profile,
        lead: leadData,
        searchType: 'scholarship_match',
        action: 'find_matches'
      };

      // Send to your backend API for scholarship matching
      const response = await fetch('/api/frontend/ai-scholarship-match/match', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submissionData)
      });

      const data = await response.json();
      
      if (data?.success && data?.data) {
        const scholarshipsWithScores = data.data.map((sch: any) => {
          const scholarshipObj = {
            ...sch,
            saved: localStorage.getItem(`saved_${sch?.id}`) === 'true',
            link: sch?.slug ? `/scholarships/${sch.slug}` : `/scholarships/${sch.id}`,
            amount: sch?.amount || calculateAmount(sch?.amount_min, sch?.amount_max),
            type: getScholarshipType(sch?.percentage_cover)
          };
          
          const matchScore = calculateAIMatchScore(scholarshipObj, profile);
          return { ...scholarshipObj, matchScore };
        });

        setScholarships(scholarshipsWithScores);
        setFilteredScholarships(scholarshipsWithScores);
        localStorage.setItem('savedScholarships', JSON.stringify(scholarshipsWithScores));
        
        // Send lead data to database
        await sendLeadToDatabase('match', scholarshipsWithScores.length);
        
        showToast(`Found ${scholarshipsWithScores.length} AI-matched scholarships!`, 'success');
      } else {
        // Fallback to mock data if API fails
        const mockScholarships = generateMockScholarships(profile);
        setScholarships(mockScholarships);
        setFilteredScholarships(mockScholarships);
        localStorage.setItem('savedScholarships', JSON.stringify(mockScholarships));
        
        // Still send lead data even if API fails
        await sendLeadToDatabase('match', mockScholarships.length);
        
        showToast('Using enhanced matching with saved data', 'info');
      }
    } catch (error) {
      console.error('Error fetching scholarships:', error);
      // Fallback to mock data
      const mockScholarships = generateMockScholarships(profile);
      setScholarships(mockScholarships);
      setFilteredScholarships(mockScholarships);
      
      // Still send lead data even if API fails
      if (leadData) {
        await sendLeadToDatabase('match', mockScholarships.length);
      }
      
      showToast('Using enhanced matching with saved data', 'info');
    } finally {
      setIsLoading(false);
    }
  };

  // Advanced search with lead check
  const handleAdvancedSearch = async () => {
    if (!searchQuery.trim()) {
      showToast('Please enter a search query', 'info');
      return;
    }

    // Check lead before proceeding
    if (!checkLeadAndProceed('search')) {
      return;
    }

    setIsSearching(true);
    try {
      const response = await fetch('/api/frontend/ai-scholarship-match/match', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          query: searchQuery,
          profile: profile,
          lead: leadData,
          action: 'search',
        })
      });

      const data = await response.json();
      
      if (data?.success) {
        const scholarshipsWithScores = data.data.map((sch: any) => {
          const scholarshipObj = {
            ...sch,
            saved: localStorage.getItem(`saved_${sch?.id}`) === 'true',
            link: sch?.slug ? `/scholarships/${sch.slug}` : `/scholarships/${sch.id}`,
            amount: sch?.amount || calculateAmount(sch?.amount_min, sch?.amount_max),
            type: getScholarshipType(sch?.percentage_cover)
          };
          
          const matchScore = calculateAIMatchScore(scholarshipObj, profile);
          return { ...scholarshipObj, matchScore };
        });
        
        setSearchResults(scholarshipsWithScores);
        setFilteredScholarships(scholarshipsWithScores);
        setAiSuggestions(data?.insights || []);
        setSearchInsights(data?.insights || []);
        setSearchSummary(data?.aiSummary || '');
        
        setActiveTab('matches');
        
        // Send lead data to database
        await sendLeadToDatabase('search', scholarshipsWithScores.length);
        
        showToast(`Found ${scholarshipsWithScores.length} AI-powered matches`, 'success');
      } else {
        setSearchResults([]);
        setFilteredScholarships([]);
        setSearchInsights([]);
        setSearchSummary('');
        showToast(data?.error || 'No scholarships found', 'info');
      }
    } catch (error: any) {
      console.error('Advanced search error:', error);
      showToast('Search failed. Please try again.', 'error');
      setSearchResults([]);
      setFilteredScholarships([]);
      setSearchInsights([]);
      setSearchSummary('');
    } finally {
      setIsSearching(false);
    }
  };

  // Run analysis with lead check
  const runAnalysis = async () => {
    if (profileProgress < 60) {
      showToast('Complete at least 60% of your profile for detailed analysis', 'info');
      setProfileCompletionModal(true);
      return;
    }

    // Check lead before proceeding
    if (!checkLeadAndProceed('analysis')) {
      return;
    }

    setActiveTab('analysis');
    setIsAnalysisLoading(true);
    
    try {
      const enhancedAnalysis = await generateEnhancedAnalysis(profile, scholarships);
      setAnalysis(enhancedAnalysis);
      localStorage.setItem('scholarshipAnalysis', JSON.stringify(enhancedAnalysis));
      
      // Send analysis lead to database
      await sendLeadToDatabase('analysis', scholarships.length, enhancedAnalysis.overallScore);
      
      showToast('AI Analysis completed!', 'success');
    } catch (error: any) {
      console.error('Analysis error:', error);
      showToast('Analysis completed with basic insights', 'info');
    } finally {
      setIsAnalysisLoading(false);
    }
  };

  // Handle lead modal success
  const handleLeadSuccess = async (newLeadData: ScholarshipLeadData) => {
    setLeadData(newLeadData);
    
    // Save lead to localStorage with 7 days expiry
    const leadDataToSave = {
      ...newLeadData,
      expiry: Date.now() + (7 * 24 * 60 * 60 * 1000), // 7 days
      savedAt: new Date().toISOString(),
      profileData: profile
    };
    
    localStorage.setItem(STORAGE_KEYS.SCHOLARSHIP_LEAD, JSON.stringify(leadDataToSave));
    
    // Send lead to database immediately
    try {
      await sendLeadToDatabase('lead_capture', 0, 0);
    } catch (error) {
      console.error('Failed to save lead to database:', error);
    }
    
    // Continue with the action that triggered the modal
    if (activeTab === 'matches') {
      await fetchScholarships();
    } else if (searchQuery.trim()) {
      await handleAdvancedSearch();
    } else if (activeTab === 'analysis') {
      await runAnalysis();
    }
  };

  // Generate enhanced analysis
  const generateEnhancedAnalysis = async (profile: Profile, scholarships: Scholarship[]): Promise<Analysis> => {
    setIsAnalysisLoading(true);
    
    const academicScore = calculateAcademicScore(profile);
    const completeness = profileProgress;
    const competitiveness = calculateCompetitivenessScore(profile);
    
    const overallScore = Math.round(
      (academicScore * 0.40) + 
      (completeness * 0.30) + 
      (competitiveness * 0.30)
    );
    
    const totalFunding = scholarships?.reduce((sum, s) => sum + (s?.amount || 0), 0) || 0;
    
    try {
      // Get AI-powered analysis from API
      const response = await fetch('/api/frontend/ai-scholarship-match/match', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          profile, 
          action: 'analyze',
          enhanced: true 
        })
      });

      const data = await response.json();
      
      if (data?.success && data?.data) {
        // Transform API data to match our interface
        const apiData = data.data;
        
        // Transform strengths if they're strings
        let strengthsArray = [];
        if (Array.isArray(apiData.strengths) && apiData.strengths.length > 0) {
          // Check if first item is a string or object
          if (typeof apiData.strengths[0] === 'string') {
            strengthsArray = [
              {
                category: 'Academic Strengths',
                items: apiData.strengths,
                score: academicScore
              },
              {
                category: 'Profile Strengths',
                items: ['Complete profile provides better matching'],
                score: completeness
              }
            ];
          } else {
            strengthsArray = apiData.strengths;
          }
        } else {
          strengthsArray = [
            {
              category: 'Academic Excellence',
              items: generateStrengths(profile, academicScore),
              score: academicScore
            },
            {
              category: 'Profile Strength',
              items: ['Complete profile provides better matching'],
              score: completeness
            }
          ];
        }
        
        // Transform weaknesses if they're strings
        let weaknessesArray = [];
        if (Array.isArray(apiData.weaknesses) && apiData.weaknesses.length > 0) {
          if (typeof apiData.weaknesses[0] === 'string') {
            weaknessesArray = [
              {
                category: 'Areas Needing Improvement',
                items: apiData.weaknesses,
                impact: academicScore < 70 ? 'high' : completeness < 80 ? 'medium' : 'low'
              }
            ];
          } else {
            weaknessesArray = apiData.weaknesses;
          }
        } else {
          weaknessesArray = [
            {
              category: 'Areas Needing Improvement',
              items: generateWeaknesses(profile, academicScore),
              impact: academicScore < 70 ? 'high' : completeness < 80 ? 'medium' : 'low'
            }
          ];
        }
        
        // Transform recommendations if needed
        let recommendationsArray = [];
        if (Array.isArray(apiData.recommendations) && apiData.recommendations.length > 0) {
          if (typeof apiData.recommendations[0] === 'string') {
            recommendationsArray = apiData.recommendations.map((rec: string, idx: number) => ({
              priority: idx === 0 ? 'high' : idx === 1 ? 'medium' : 'low',
              action: rec,
              timeline: idx === 0 ? 'Immediately' : idx === 1 ? 'Within 2 months' : 'Before deadlines',
              impact: idx === 0 ? 'High' : idx === 1 ? 'Medium' : 'Medium'
            }));
          } else {
            recommendationsArray = apiData.recommendations;
          }
        } else {
          recommendationsArray = generateRecommendations(profile, profileProgress);
        }
        
        // Transform risk factors if needed
        let riskFactorsArray = [];
        if (Array.isArray(apiData.riskFactors) && apiData.riskFactors.length > 0) {
          riskFactorsArray = apiData.riskFactors;
        } else {
          riskFactorsArray = generateRiskFactors(profile, academicScore, completeness).map(factor => ({
            factor,
            likelihood: factor.includes('low') ? 'low' : factor.includes('competitive') ? 'high' : 'medium',
            impact: factor.includes('application') ? 'high' : factor.includes('language') ? 'medium' : 'low',
            mitigation: getMitigationStrategy(factor)
          }));
        }
        
        // Transform timeline recommendations if needed
        let timelineRecommendationsArray = [];
        if (Array.isArray(apiData.timelineRecommendations) && apiData.timelineRecommendations.length > 0) {
          if (typeof apiData.timelineRecommendations[0] === 'string') {
            timelineRecommendationsArray = apiData.timelineRecommendations.map((task: string, idx: number) => ({
              task,
              deadline: idx === 0 ? 'Immediately' : idx === 1 ? 'Within 1 week' : idx === 2 ? 'Within 2 weeks' : 'Within 1 month',
              priority: idx < 2 ? 'high' : idx < 4 ? 'medium' : 'low'
            }));
          } else {
            timelineRecommendationsArray = apiData.timelineRecommendations;
          }
        } else {
          timelineRecommendationsArray = generateTimelineRecommendations(profile);
        }
        
        // Transform match breakdown if provided
        const matchBreakdown = apiData.matchBreakdown || {
          academicMatch: academicScore,
          countryMatch: calculateCountryMatch(profile, scholarships),
          fundingMatch: calculateFundingMatch(profile, scholarships),
          timelineMatch: 85
        };
        
        // Transform AI insights if provided
        const aiInsights = apiData.aiInsights || generateAIInsights(profile, scholarships);
        
        // Transform competitive analysis if provided
        const competitiveAnalysis = apiData.competitiveAnalysis || {
          percentile: calculatePercentile(overallScore),
          strengths: ['Strong academic foundation', 'Clear career goals', 'International perspective'],
          opportunities: ['Research experience', 'Leadership roles', 'Community service']
        };
        
        // Transform scholarship categories if provided
        const scholarshipCategories = apiData.scholarshipCategories || estimateScholarshipCategories(profile, overallScore);
        
        return {
          overallScore: apiData.overallScore || overallScore,
          strengths: strengthsArray,
          weaknesses: weaknessesArray,
          recommendations: recommendationsArray,
          estimatedSuccess: apiData.estimatedSuccess || calculateEstimatedSuccess(overallScore, scholarships),
          totalMatches: apiData.totalMatches || scholarships?.length || 0,
          totalFunding: apiData.totalFunding || `$${totalFunding.toLocaleString()}`,
          profileStrength: apiData.profileStrength || {
            academic: academicScore,
            profileCompleteness: completeness,
            competitiveness: competitiveness,
            readiness: Math.round((academicScore + completeness + competitiveness) / 3)
          },
          riskFactors: riskFactorsArray,
          timelineRecommendations: timelineRecommendationsArray,
          scholarshipCategories: scholarshipCategories,
          matchBreakdown: matchBreakdown,
          aiInsights: aiInsights,
          competitiveAnalysis: competitiveAnalysis
        };
      }
    } catch (error) {
      console.error('AI analysis API error:', error);
    } finally {
      setIsAnalysisLoading(false);
    }
    
    // Fallback to generated analysis
    return {
      overallScore,
      strengths: [
        {
          category: 'Academic Excellence',
          items: generateStrengths(profile, academicScore),
          score: academicScore
        },
        {
          category: 'Profile Strength',
          items: ['Complete profile provides better matching'],
          score: completeness
        },
        {
          category: 'Competitiveness',
          items: ['Good foundation for scholarship applications'],
          score: competitiveness
        }
      ],
      weaknesses: [
        {
          category: 'Areas Needing Improvement',
          items: generateWeaknesses(profile, academicScore),
          impact: academicScore < 70 ? 'high' : completeness < 80 ? 'medium' : 'low'
        },
        {
          category: 'Missing Information',
          items: getMissingFields(profile),
          impact: completeness < 90 ? 'high' : 'medium'
        }
      ],
      recommendations: generateRecommendations(profile, profileProgress),
      estimatedSuccess: calculateEstimatedSuccess(overallScore, scholarships),
      totalMatches: scholarships?.length || 0,
      totalFunding: `$${totalFunding.toLocaleString()}`,
      profileStrength: {
        academic: academicScore,
        profileCompleteness: completeness,
        competitiveness: competitiveness,
        readiness: Math.round((academicScore + completeness + competitiveness) / 3)
      },
      riskFactors: generateRiskFactors(profile, academicScore, completeness).map(factor => ({
        factor,
        likelihood: factor.includes('low') ? 'low' : factor.includes('competitive') ? 'high' : 'medium',
        impact: factor.includes('application') ? 'high' : factor.includes('language') ? 'medium' : 'low',
        mitigation: getMitigationStrategy(factor)
      })),
      timelineRecommendations: generateTimelineRecommendations(profile),
      scholarshipCategories: estimateScholarshipCategories(profile, overallScore),
      matchBreakdown: {
        academicMatch: academicScore,
        countryMatch: calculateCountryMatch(profile, scholarships),
        fundingMatch: calculateFundingMatch(profile, scholarships),
        timelineMatch: 85
      },
      aiInsights: generateAIInsights(profile, scholarships),
      competitiveAnalysis: {
        percentile: calculatePercentile(overallScore),
        strengths: ['Strong academic foundation', 'Clear career goals', 'International perspective'],
        opportunities: ['Research experience', 'Leadership roles', 'Community service']
      }
    };
  };

  // Helper functions for generating analysis data
  const generateStrengths = (profile: Profile, academicScore: number): string[] => {
    const strengths = [];
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    
    if (cgpa >= 3.5) strengths.push('Strong academic performance (GPA ≥ 3.5)');
    if (languageScore >= 7.0) strengths.push('Good English proficiency (≥ 7.0 IELTS equivalent)');
    if (profile?.academic?.researchExperience) strengths.push('Research experience');
    if (profile?.academic?.publications) strengths.push('Publications record');
    if (profile?.academic?.awards) strengths.push('Academic awards/honors');
    if (profile?.preferences?.countries?.length > 0) strengths.push('Clear geographical preferences');
    if (profile?.preferences?.fundingPriority !== 'any') strengths.push('Specific funding requirements');
    
    if (strengths.length === 0) {
      strengths.push('Good foundational profile for scholarship applications');
    }
    
    return strengths.slice(0, 3);
  };

  const generateWeaknesses = (profile: Profile, academicScore: number): string[] => {
    const weaknesses = [];
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    
    if (cgpa < 3.0) weaknesses.push('GPA below competitive threshold (3.0)');
    if (languageScore < 6.5) weaknesses.push('English proficiency below scholarship requirements');
    if (!profile?.academic?.researchExperience) weaknesses.push('Limited research experience');
    if (!profile?.academic?.publications) weaknesses.push('No publications');
    if (profile?.preferences?.countries?.length === 0) weaknesses.push('No specific country preferences');
    if (!profile?.preferences?.degreeLevel) weaknesses.push('Degree level not specified');
    
    return weaknesses.slice(0, 3);
  };

  const generateRecommendations = (profile: Profile, profileProgress: number) => {
    const recommendations = [];
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    
    if (cgpa < 3.0) {
      recommendations.push({
        priority: 'high' as const,
        action: 'Improve GPA through additional courses or retaking key subjects',
        timeline: 'Before next application cycle',
        impact: 'High'
      });
    }
    
    if (languageScore < 6.5) {
      recommendations.push({
        priority: languageScore < 6.0 ? 'high' as const : 'medium' as const,
        action: languageScore < 6.0 ? 'Retake IELTS/TOEFL to achieve minimum 6.5' : 'Consider improving English score to 7.0+',
        timeline: 'Within 3 months',
        impact: languageScore < 6.0 ? 'Critical' : 'Medium'
      });
    }
    
    if (!profile?.academic?.researchExperience) {
      recommendations.push({
        priority: 'medium' as const,
        action: 'Gain research experience through internships or university projects',
        timeline: 'Within 6 months',
        impact: 'Medium'
      });
    }
    
    if (profileProgress < 100) {
      recommendations.push({
        priority: 'high' as const,
        action: 'Complete your profile for better matching accuracy',
        timeline: 'Immediately',
        impact: 'High'
      });
    }
    
    if (recommendations.length === 0) {
      recommendations.push({
        priority: 'low' as const,
        action: 'Focus on writing strong recommendation letters and personal statements',
        timeline: 'Within 2 months',
        impact: 'Medium'
      });
    }
    
    return recommendations.slice(0, 3);
  };

  const generateRiskFactors = (profile: Profile, academicScore: number, completeness: number): string[] => {
    const risks = [];
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    
    if (cgpa < 3.0) risks.push('Low GPA may disqualify from many competitive scholarships');
    if (languageScore < 6.5) risks.push('Language scores below minimum requirements for many programs');
    if (completeness < 80) risks.push('Incomplete profile leads to inaccurate matching');
    if (profile?.preferences?.countries?.length === 0) risks.push('No country preferences may result in mismatched opportunities');
    
    return risks.length > 0 ? risks : ['Competitive application process for all scholarships'];
  };

  const getMitigationStrategy = (riskFactor: string): string => {
    if (riskFactor.includes('GPA')) return 'Focus on scholarships with lower GPA requirements or improve grades through additional courses';
    if (riskFactor.includes('Language')) return 'Retake language tests or target scholarships with lower language requirements';
    if (riskFactor.includes('profile')) return 'Complete all profile sections immediately for better matching';
    if (riskFactor.includes('country')) return 'Specify at least 3 preferred countries in your profile';
    return 'Apply to more scholarships and consider less competitive options';
  };

  const generateTimelineRecommendations = (profile: Profile) => {
    return [
      {
        task: 'Complete scholarship applications for top 3 matches',
        deadline: 'Within 2 weeks',
        priority: 'high' as const
      },
      {
        task: 'Prepare application documents (CV, transcripts, etc.)',
        deadline: 'Within 1 week',
        priority: 'high' as const
      },
      {
        task: 'Request recommendation letters from professors',
        deadline: 'Within 3 weeks',
        priority: 'medium' as const
      },
      {
        task: 'Prepare for potential interviews',
        deadline: 'Ongoing',
        priority: 'low' as const
      }
    ];
  };

  const generateAIInsights = (profile: Profile, scholarships: Scholarship[]): string[] => {
    const insights = [];
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    
    if (cgpa >= 3.8) {
      insights.push('Your high GPA makes you eligible for prestigious merit-based scholarships');
    }
    
    if (scholarships.length > 10) {
      insights.push(`You have ${scholarships.length} potential matches - focus on those with >80% match scores`);
    } else if (scholarships.length > 0) {
      insights.push(`Consider expanding your country preferences to increase match count`);
    }
    
    if (profile?.preferences?.fundingPriority === 'full') {
      insights.push('Full scholarships are highly competitive - also consider partial funding options');
    }
    
    insights.push('Apply early as scholarship deadlines approach quickly');
    
    return insights;
  };

  const estimateScholarshipCategories = (profile: Profile, overallScore: number) => {
    return {
      highMatch: Math.min(100, Math.round(overallScore * 0.8)),
      mediumMatch: Math.min(100, Math.round(overallScore * 0.6)),
      lowMatch: Math.min(100, Math.round(overallScore * 0.4))
    };
  };

  // Helper functions for calculations
  const calculateAcademicScore = (profile: Profile): number => {
    let score = 50;
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    
    if (cgpa >= 3.8) score += 40;
    else if (cgpa >= 3.5) score += 35;
    else if (cgpa >= 3.0) score += 30;
    else if (cgpa >= 2.5) score += 20;
    
    if (languageScore >= 8.0) score += 20;
    else if (languageScore >= 7.5) score += 18;
    else if (languageScore >= 7.0) score += 15;
    else if (languageScore >= 6.5) score += 12;
    
    if (profile?.academic?.researchExperience) score += 10;
    if (profile?.academic?.publications) score += 5;
    if (profile?.academic?.awards) score += 5;
    
    return Math.min(100, score);
  };

  const calculateCompetitivenessScore = (profile: Profile): number => {
    let score = 60;
    score += Math.min(20, profileProgress / 5);
    
    const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    if (cgpa >= 3.5) score += 15;
    
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    if (languageScore >= 7.5) score += 15;
    
    if (profile?.academic?.researchExperience) score += 10;
    
    return Math.min(100, score);
  };

  const calculateEstimatedSuccess = (overallScore: number, scholarships: Scholarship[]): number => {
    let base = overallScore * 0.7;
    const highMatches = scholarships?.filter(s => s?.matchScore >= 80)?.length || 0;
    base += Math.min(20, highMatches * 2);
    base += Math.min(10, profileProgress / 10);
    return Math.min(95, Math.max(30, Math.round(base)));
  };

  const calculateCountryMatch = (profile: Profile, scholarships: Scholarship[]): number => {
    const preferredCountries = profile?.preferences?.countries || [];
    if (preferredCountries?.length === 0) return 70;
    const countryMatches = scholarships?.filter(s => 
      preferredCountries.some(country => s?.country?.toLowerCase().includes(country?.toLowerCase()))
    )?.length || 0;
    return Math.min(100, Math.round((countryMatches / scholarships?.length) * 100) || 70);
  };

  const calculateFundingMatch = (profile: Profile, scholarships: Scholarship[]): number => {
    const fundingPriority = profile?.preferences?.fundingPriority;
    if (fundingPriority === 'any') return 80;
    const fundingMatches = scholarships?.filter(s => {
      if (fundingPriority === 'full') return s?.type === 'fully_funded' || (s?.percentage_cover || 0) >= 75;
      if (fundingPriority === 'partial') return s?.type === 'partial' || ((s?.percentage_cover || 0) >= 25 && (s?.percentage_cover || 0) < 75);
      return true;
    })?.length || 0;
    return Math.min(100, Math.round((fundingMatches / scholarships?.length) * 100) || 80);
  };

  const calculatePercentile = (overallScore: number): number => {
    if (overallScore >= 90) return 95;
    if (overallScore >= 80) return 85;
    if (overallScore >= 70) return 70;
    if (overallScore >= 60) return 50;
    return 30;
  };

  const showToast = (message: string, type: 'success' | 'error' | 'info') => {
    setToast({ message, type, visible: true });
    setTimeout(() => {
      setToast(prev => ({ ...prev, visible: false }));
    }, 3000);
  };

  const formatDate = (dateString?: string): string => {
    if (!dateString) return 'Rolling Admission';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', { 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric' 
      });
    } catch {
      return 'Rolling Admission';
    }
  };

  // Input change handlers
  const handleInputChange = (
    section: keyof Profile,
    field: string,
    value: any,
    type: 'input' | 'select' | 'multiselect' = 'input'
  ) => {
    setProfile(prev => {
      const newProfile = JSON.parse(JSON.stringify(prev));
      
      if (type === 'multiselect') {
        const currentArray = newProfile[section][field] || [];
        let newArray;
        
        if (currentArray.includes(value)) {
          newArray = currentArray.filter((item: string) => item !== value);
        } else {
          newArray = [...currentArray, value];
        }
        
        newProfile[section][field] = newArray;
      } else {
        newProfile[section][field] = value;
      }
      
      return newProfile;
    });
  };

  const handleCountrySelection = (country: string) => {
    const currentCountries = [...(profile?.preferences?.countries || [])];
    const isSelected = currentCountries.includes(country);
    
    let newCountries;
    if (isSelected) {
      newCountries = currentCountries.filter(c => c !== country);
    } else {
      newCountries = [...currentCountries, country];
    }
    
    setProfile(prev => ({
      ...prev,
      preferences: {
        ...prev.preferences,
        countries: newCountries
      }
    }));
  };

  const toggleSaveScholarship = (id: number) => {
    const updatedScholarships = scholarships.map(sch => {
      if (sch?.id === id) {
        const updated = { ...sch, saved: !sch?.saved };
        localStorage.setItem(`saved_${id}`, updated.saved.toString());
        return updated;
      }
      return sch;
    });
    
    setScholarships(updatedScholarships);
    setFilteredScholarships(updatedScholarships);
    const savedItems = updatedScholarships.filter(s => s?.saved);
    setSavedCount(savedItems?.length);
    
    const scholarship = scholarships.find(s => s?.id === id);
    showToast(scholarship?.saved ? 'Removed from saved' : 'Scholarship saved!', 'success');
  };

  // Check for speech recognition support
  useEffect(() => {
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
      const SpeechRecognition = (window as any).webkitSpeechRecognition || (window as any).SpeechRecognition;
      recognitionRef.current = new SpeechRecognition();
      recognitionRef.current.continuous = false;
      recognitionRef.current.interimResults = false;
      recognitionRef.current.lang = 'en-US';
      
      recognitionRef.current.onresult = (event: any) => {
        const transcript = event?.results?.[0]?.[0]?.transcript;
        setSearchQuery(transcript || '');
        setIsListening(false);
      };
      
      recognitionRef.current.onerror = () => {
        setIsListening(false);
        showToast('Voice recognition failed. Please try again.', 'error');
      };
      
      recognitionRef.current.onend = () => {
        setIsListening(false);
      };
      
      setIsVoiceAvailable(true);
    }
  }, []);

  // Features array matching reference design
  const features = [
    {
      icon: Brain,
      title: "AI-Powered Matching",
      description: "Advanced algorithms analyze your profile to find perfect scholarship matches",
      color: "from-teal-500 to-blue-500"
    },
    {
      icon: Target,
      title: "Personalized Recommendations",
      description: "Get tailored scholarship suggestions based on your academic background and goals",
      color: "from-blue-500 to-cyan-400"
    },
    {
      icon: BarChart3,
      title: "Success Analysis",
      description: "Detailed insights on your scholarship application competitiveness",
      color: "from-emerald-500 to-teal-400"
    },
    {
      icon: Shield,
      title: "Lead Tracking",
      description: "Secure storage of your profile for continuous improvement",
      color: "from-amber-500 to-orange-400"
    }
  ];

  // Steps array matching reference design
  const steps = [
    {
      number: "01",
      title: "Build Profile",
      description: "Complete your academic profile and preferences",
      icon: <User className="w-5 h-5" />
    },
    {
      number: "02",
      title: "AI Matching",
      description: "Our AI finds scholarships matching your profile",
      icon: <Brain className="w-5 h-5" />
    },
    {
      number: "03",
      title: "Review Matches",
      description: "Explore personalized scholarship opportunities",
      icon: <Target className="w-5 h-5" />
    },
    {
      number: "04",
      title: "Get Analysis",
      description: "Receive AI-powered insights and recommendations",
      icon: <BarChart3 className="w-5 h-5" />
    }
  ];

  // UI Components with updated design
  const ProgressRing = ({ size = 120, progress }: { size: number; progress: number }) => {
    const radius = (size - 12) / 2;
    const circumference = radius * 2 * Math.PI;
    const offset = circumference - (progress / 100) * circumference;

    return (
      <div className="relative" style={{ width: size, height: size }}>
        <svg width={size} height={size} className="transform -rotate-90">
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            strokeWidth="12"
            className="fill-none stroke-gray-200"
          />
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            strokeWidth="12"
            className="fill-none stroke-gradient-to-r from-teal-500 to-blue-500"
            strokeDasharray={circumference}
            strokeDashoffset={offset}
            strokeLinecap="round"
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="text-center">
            <div className="text-3xl font-bold text-gray-800">{progress}%</div>
            <div className="text-sm text-gray-500">Complete</div>
          </div>
        </div>
      </div>
    );
  };

  const ScholarshipCard = ({ scholarship }: { scholarship: Scholarship }) => (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      whileHover={{ y: -8, scale: 1.02 }}
      className="bg-white rounded-3xl border border-gray-100 shadow-sm hover:shadow-2xl transition-all duration-300 group overflow-hidden hover:border-teal-200"
    >
      <div className="p-8">
        <div className="flex justify-between items-start mb-6">
          <div className="flex-1">
            <div className="flex items-center mb-4">
              <div className="w-14 h-14 rounded-2xl bg-gradient-to-r from-teal-100 to-blue-100 flex items-center justify-center mr-4 group-hover:scale-110 transition-transform duration-300 border border-teal-200">
                <Award className="w-7 h-7 text-teal-600" />
              </div>
              <div>
                <a 
                  href={scholarship?.link || `#`} 
                  className="hover:no-underline"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <h3 className="font-bold text-gray-900 text-xl hover:text-teal-600 transition-colors">
                    {scholarship?.title || 'Untitled Scholarship'}
                  </h3>
                </a>
                <div className="flex items-center text-sm text-gray-600 mt-2">
                  <MapPin className="w-4 h-4 mr-2 text-teal-500" />
                  <span className="font-medium">{scholarship?.country || 'International'}</span>
                </div>
              </div>
            </div>
          </div>
          <div className="text-right">
            <div className={`px-4 py-2 rounded-full text-sm font-bold mb-3 ${
              scholarship?.matchScore >= 90 ? 'bg-gradient-to-r from-green-100 to-emerald-100 text-green-800 border border-green-200' :
              scholarship?.matchScore >= 80 ? 'bg-gradient-to-r from-blue-100 to-cyan-100 text-blue-800 border border-blue-200' :
              scholarship?.matchScore >= 70 ? 'bg-gradient-to-r from-yellow-100 to-amber-100 text-yellow-800 border border-yellow-200' :
              'bg-gradient-to-r from-gray-100 to-slate-100 text-gray-800 border border-gray-200'
            }`}>
              {scholarship?.matchScore}% Match
            </div>
            <div className="text-2xl font-bold text-gray-900 bg-gradient-to-r from-teal-600 to-blue-600 bg-clip-text text-transparent">
              ${(scholarship?.amount || 0).toLocaleString()}
            </div>
          </div>
        </div>

        {scholarship?.tags && scholarship.tags.length > 0 && (
          <div className="flex flex-wrap gap-2 mb-6">
            {scholarship.tags.slice(0, 3).map((tag, idx) => (
              <Badge key={idx} color="teal">
                {tag}
              </Badge>
            ))}
          </div>
        )}

        <div className="grid grid-cols-2 gap-6 mb-6">
          <div className="space-y-2">
            <div className="flex items-center text-sm">
              <Calendar className="w-5 h-5 text-teal-500 mr-3" />
              <span className="font-medium">Deadline:</span>
            </div>
            <div className="text-gray-900 font-semibold text-base">{formatDate(scholarship?.deadline)}</div>
          </div>
          <div className="space-y-2">
            <div className="flex items-center text-sm">
              <Percent className="w-5 h-5 text-blue-500 mr-3" />
              <span className="font-medium">Type:</span>
            </div>
            <div className="text-gray-900 font-semibold text-base">
              {scholarship?.type?.replace(/_/g, ' ')?.toUpperCase() || 'VARIABLE'}
            </div>
          </div>
        </div>

        <div className="mb-6">
          <div className="flex items-center text-sm text-gray-600 mb-3">
            <CheckCircle className="w-5 h-5 text-green-500 mr-3" />
            <span>Requirements:</span>
          </div>
          <div className="space-y-2">
            {scholarship?.eligibility?.slice(0, 3).map((req, idx) => (
              <div key={idx} className="text-sm text-gray-700 flex items-start">
                <div className="w-1.5 h-1.5 bg-teal-500 rounded-full mt-1.5 mr-3 flex-shrink-0"></div>
                <span>{req}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="bg-gradient-to-r from-teal-50 to-blue-50 rounded-2xl p-5 mb-6 border border-teal-100">
          <div className="flex items-center mb-3">
            <Brain className="w-5 h-5 text-teal-600 mr-3" />
            <span className="text-sm font-semibold text-teal-800">AI Insight</span>
          </div>
          <p className="text-sm text-gray-700">{scholarship?.aiInsight || 'No insight available'}</p>
        </div>

        <div className="flex space-x-4">
          <a 
            href={scholarship?.link || `#`}
            target="_blank"
            rel="noopener noreferrer"
            className="flex-1 bg-gradient-to-r from-teal-600 to-blue-600 text-white py-3 px-5 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 flex items-center justify-center group-hover:from-teal-700 group-hover:to-blue-700 hover:scale-105"
          >
            <Eye className="w-5 h-5 mr-2" />
            View Details
            <ChevronRight className="w-5 h-5 ml-2" />
          </a>
          <button
            type="button"
            onClick={() => toggleSaveScholarship(scholarship.id)}
            className={`p-3 rounded-xl border transition-all hover:scale-105 ${
              scholarship.saved 
                ? 'bg-gradient-to-r from-amber-50 to-orange-50 border-amber-200 text-amber-600' 
                : 'bg-white border-gray-200 text-gray-600 hover:border-gray-300'
            }`}
          >
            {scholarship.saved ? (
              <Star className="w-6 h-6 fill-amber-500 text-amber-500" />
            ) : (
              <Star className="w-6 h-6" />
            )}
          </button>
        </div>
      </div>
    </motion.div>
  );

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
      {/* Hero Section matching reference design */}
      <div className="relative">
        <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 border border-teal-200">
              <Shield className="w-4 h-4" />
              AI-Powered Scholarship Matching
            </div>

            {/* Main Heading */}
            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-6 leading-tight">
              Find Your Perfect{' '}
              <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Scholarship Match
              </span>{' '}
              <br />
              with UniversitiesPage AI
            </h1>

            {/* Subheading */}
            <p className="text-xl md:text-2xl text-gray-600 mb-10 max-w-3xl mx-auto leading-relaxed">
              Get intelligent, data-driven insights to discover the best scholarship opportunities.
              Our AI analyzes your profile and matches you with personalized funding options.
            </p>

            {/* Main Navigation Tabs */}
            <div className="max-w-2xl mx-auto mb-8">
              <div className="bg-white border-2 border-gray-200 rounded-2xl p-1 shadow-sm">
                <div className="flex">
                  <button
                    type="button"
                    onClick={() => setActiveTab('dashboard')}
                    className={`flex-1 py-3 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
                      activeTab === 'dashboard' 
                        ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <Cpu className="w-5 h-5" />
                    Dashboard
                  </button>
                  <button
                    type="button"
                    onClick={() => setActiveTab('profile')}
                    className={`flex-1 py-3 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
                      activeTab === 'profile' 
                        ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <User className="w-5 h-5" />
                    Profile Builder
                    <span className="px-2 py-1 text-xs font-bold bg-gradient-to-r from-orange-500 to-amber-500 text-white rounded-full">
                      {profileProgress}%
                    </span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setActiveTab('matches')}
                    className={`flex-1 py-3 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
                      activeTab === 'matches' 
                        ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <Target className="w-5 h-5" />
                    Matches
                    {scholarships.length > 0 && (
                      <span className="px-2 py-1 text-xs font-bold bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-full">
                        {scholarships.length}
                      </span>
                    )}
                  </button>
                  <button
                    type="button"
                    onClick={() => setActiveTab('analysis')}
                    className={`flex-1 py-3 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
                      activeTab === 'analysis' 
                        ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <BarChart3 className="w-5 h-5" />
                    AI Analysis
                    {analysis && (
                      <span className="px-2 py-1 text-xs font-bold bg-gradient-to-r from-blue-500 to-cyan-500 text-white rounded-full">
                        {analysis?.overallScore || 0}%
                      </span>
                    )}
                  </button>
                </div>
              </div>
            </div>

            {/* AI Search Bar */}
            <div className="max-w-2xl mx-auto mb-8">
              <div className="relative">
                <div className="absolute left-4 top-1/2 transform -translate-y-1/2 text-teal-500">
                  <Brain className="w-5 h-5" />
                </div>
                <input
                  ref={searchInputRef}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleAdvancedSearch()}
                  placeholder="Example: 'Find fully-funded computer science scholarships in USA for international students'"
                  className="w-full pl-12 pr-32 py-4 bg-white border-2 border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent text-lg shadow-lg hover:shadow-xl transition-shadow duration-300"
                />
                <div className="absolute right-2 top-1/2 transform -translate-y-1/2 flex items-center space-x-2">
                  {isVoiceAvailable && (
                    <button
                      type="button"
                      onClick={() => {
                        if (isListening) {
                          recognitionRef?.current?.stop();
                          setIsListening(false);
                        } else {
                          recognitionRef?.current?.start();
                          setIsListening(true);
                          showToast('Listening... Speak now', 'info');
                        }
                      }}
                      className={`p-3 rounded-xl ${isListening ? 'bg-red-100 text-red-600 animate-pulse' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                    >
                      {isListening ? <MicOff className="w-5 h-5" /> : <Mic className="w-5 h-5" />}
                    </button>
                  )}
                  <button
                    type="button"
                    onClick={handleAdvancedSearch}
                    disabled={isSearching || !searchQuery.trim()}
                    className="px-5 py-3 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 flex items-center hover:scale-105"
                  >
                    {isSearching ? (
                      <>
                        <Loader2 className="w-4 h-4 animate-spin mr-2" />
                        Searching...
                      </>
                    ) : (
                      <>
                        <Search className="w-4 h-4 mr-2" />
                        AI Search
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>

            {/* Quick Action Buttons */}
            <div className="flex flex-col sm:flex-row gap-4 justify-center mt-8">
              <button
                type="button"
                onClick={fetchScholarships}
                disabled={isLoading || profileProgress < 50}
                className={`px-8 py-4 rounded-2xl font-semibold text-lg transition-all duration-300 flex items-center gap-3 shadow-lg hover:shadow-xl ${
                  profileProgress >= 50
                    ? 'bg-gradient-to-r from-teal-600 to-blue-600 text-white cursor-pointer hover:opacity-90'
                    : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                }`}
              >
                {isLoading ? (
                  <>
                    <Loader2 className="w-6 h-6 animate-spin" />
                    Finding Matches...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-6 h-6" />
                    Find AI Matches
                  </>
                )}
              </button>
              <button
                type="button"
                onClick={runAnalysis}
                disabled={profileProgress < 60}
                className={`px-8 py-4 rounded-2xl font-semibold text-lg transition-all duration-300 flex items-center gap-3 shadow-lg hover:shadow-xl ${
                  profileProgress >= 60
                    ? 'bg-gradient-to-r from-green-600 to-emerald-600 text-white cursor-pointer hover:opacity-90'
                    : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                }`}
              >
                <Brain className="w-6 h-6" />
                Get AI Analysis
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Features Section */}
      <div className="py-20 bg-white z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">
              Why Use Our{' '}
              <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                AI Scholarship Tool?
              </span>
            </h2>
            <p className="text-gray-600 text-lg max-w-3xl mx-auto">
              Get intelligent insights and maximize your scholarship opportunities
            </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">
        <AnimatePresence mode="wait">
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="max-w-7xl mx-auto"
          >
            {/* Dashboard View */}
            {activeTab === 'dashboard' && (
              <div className="space-y-8">
                {/* Quick Stats */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                  <ModernCard className="p-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="p-3 rounded-2xl bg-gradient-to-r from-teal-100 to-blue-100">
                        <Database className="w-6 h-6 text-teal-600" />
                      </div>
                      <span className="text-2xl font-bold text-gray-900">{scholarships.length}</span>
                    </div>
                    <h3 className="font-semibold text-gray-800 mb-2">AI Matches</h3>
                    <p className="text-sm text-gray-600">Personalized scholarships</p>
                  </ModernCard>

                  <ModernCard className="p-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="p-3 rounded-2xl bg-gradient-to-r from-green-100 to-emerald-100">
                        <TrendingUp className="w-6 h-6 text-green-600" />
                      </div>
                      <span className="text-2xl font-bold text-gray-900">
                        {analysis?.overallScore || '--'}%
                      </span>
                    </div>
                    <h3 className="font-semibold text-gray-800 mb-2">Success Score</h3>
                    <p className="text-sm text-gray-600">AI assessment</p>
                  </ModernCard>

                  <ModernCard className="p-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="p-3 rounded-2xl bg-gradient-to-r from-purple-100 to-pink-100">
                        <Clock className="w-6 h-6 text-purple-600" />
                      </div>
                      <span className="text-2xl font-bold text-gray-900">
                        {scholarships.filter(s => {
                          try {
                            if (!s?.deadline) return false;
                            const deadline = new Date(s.deadline);
                            const now = new Date();
                            const diffTime = deadline.getTime() - now.getTime();
                            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                            return diffDays <= 30 && diffDays > 0;
                          } catch {
                            return false;
                          }
                        }).length}
                      </span>
                    </div>
                    <h3 className="font-semibold text-gray-800 mb-2">Urgent Deadlines</h3>
                    <p className="text-sm text-gray-600">Within 30 days</p>
                  </ModernCard>

                  <ModernCard className="p-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="p-3 rounded-2xl bg-gradient-to-r from-amber-100 to-orange-100">
                        <Coins className="w-6 h-6 text-amber-600" />
                      </div>
                      <span className="text-2xl font-bold text-gray-900">
                        ${scholarships.reduce((sum, s) => sum + (s?.amount || 0), 0).toLocaleString()}
                      </span>
                    </div>
                    <h3 className="font-semibold text-gray-800 mb-2">Total Funding</h3>
                    <p className="text-sm text-gray-600">Available amount</p>
                  </ModernCard>
                </div>

                {/* Top Matches Section */}
                <ModernCard className="p-8">
                  <div className="flex justify-between items-center mb-8">
                    <div>
                      <h3 className="text-2xl font-bold text-gray-900">Top AI Matches</h3>
                      <p className="text-gray-600">Personalized based on your profile</p>
                    </div>
                    <div className="flex space-x-3">
                      <button
                        type="button"
                        onClick={fetchScholarships}
                        disabled={isLoading || profileProgress < 50}
                        className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300 disabled:opacity-50 flex items-center space-x-2 hover:scale-105"
                      >
                        <Sparkles className="w-5 h-5" />
                        <span>{isLoading ? 'Finding...' : 'Refresh Matches'}</span>
                      </button>
                      <button
                        type="button"
                        onClick={runAnalysis}
                        disabled={profileProgress < 60}
                        className="px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300 disabled:opacity-50 flex items-center space-x-2 hover:scale-105"
                      >
                        <Brain className="w-5 h-5" />
                        <span>Get Analysis</span>
                      </button>
                    </div>
                  </div>

                  {isLoading ? (
                    <div className="text-center py-12">
                      <div className="w-16 h-16 border-4 border-teal-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                      <p className="text-gray-600">Finding perfect matches for you...</p>
                    </div>
                  ) : scholarships.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                      {scholarships.slice(0, 20).map((scholarship) => (
                        <ScholarshipCard key={scholarship?.id} scholarship={scholarship} />
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-12">
                      <Target className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                      <h3 className="text-2xl font-bold text-gray-900 mb-2">No matches yet</h3>
                      <p className="text-gray-600 mb-6">
                        {profileProgress < 50 
                          ? 'Complete your profile to start finding matches' 
                          : 'Click "Find AI Matches" to discover scholarships'}
                      </p>
                      <div className="flex justify-center gap-3">
                        {profileProgress < 100 && (
                          <button
                            type="button"
                            onClick={() => setActiveTab('profile')}
                            className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300 hover:scale-105"
                          >
                            Complete Profile ({profileProgress}%)
                          </button>
                        )}
                        <button
                          type="button"
                          onClick={fetchScholarships}
                          disabled={profileProgress < 50}
                          className="px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300 disabled:opacity-50 hover:scale-105"
                        >
                          Find AI Matches
                        </button>
                      </div>
                    </div>
                  )}
                </ModernCard>

                {/* How It Works Section */}
                <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((step, 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">
                          {step.number}
                        </div>
                        <h4 className="text-lg font-bold text-gray-900 mb-2">{step.title}</h4>
                        <p className="text-gray-600 text-sm">{step.description}</p>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* Profile Builder View */}
            {activeTab === 'profile' && (
              <div className="space-y-8">
                <div className="flex justify-between items-center mb-8">
                  <div>
                    <h1 className="text-3xl font-bold text-gray-900">Build Your Profile</h1>
                    <p className="text-gray-600">Complete all sections for optimal AI matching</p>
                  </div>
                  <div className="text-right">
                    <div className="text-4xl font-bold bg-gradient-to-r from-teal-600 to-blue-600 bg-clip-text text-transparent">
                      {profileProgress}%
                    </div>
                    <div className="text-sm text-gray-600">Profile Complete</div>
                  </div>
                </div>

                {/* Profile Progress Bar */}
                <ModernCard className="p-8">
                  <div className="flex items-center justify-between mb-6">
                    <div>
                      <h3 className="text-xl font-bold text-gray-900">Profile Progress</h3>
                      <p className="text-gray-600">
                        {profileProgress < 50 ? 'Complete basic information to start' :
                         profileProgress < 80 ? 'Great progress! Add more details' :
                         profileProgress < 100 ? 'Almost complete! Finish for perfect matches' :
                         'Profile complete! Ready for AI matching'}
                      </p>
                    </div>
                    {profileProgress < 100 && (
                      <button
                        type="button"
                        onClick={() => {
                          const missingFields = getMissingFields(profile);
                          if (missingFields.length > 0) {
                            showToast(`Complete: ${missingFields[0]}`, 'info');
                          }
                        }}
                        className="px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-xl font-semibold hover:shadow-lg transition-all hover:scale-105"
                      >
                        {100 - profileProgress}% Remaining
                      </button>
                    )}
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-3">
                    <div 
                      className="h-3 rounded-full bg-gradient-to-r from-teal-500 to-blue-500 transition-all duration-500"
                      style={{ width: `${profileProgress}%` }}
                    ></div>
                  </div>
                  <div className="flex justify-between mt-2 text-sm text-gray-600">
                    <span>Basic</span>
                    <span>Academic</span>
                    <span>Preferences</span>
                    <span>Complete</span>
                  </div>
                </ModernCard>

                {/* Profile Form Sections */}
                <div className="space-y-8">
                  {/* Personal Info */}
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                  >
                    <ModernCard className="p-8">
                      <div className="flex items-center mb-8">
                        <div className="w-14 h-14 rounded-2xl bg-gradient-to-r from-teal-100 to-blue-100 flex items-center justify-center mr-4 border border-teal-200">
                          <User className="w-7 h-7 text-teal-600" />
                        </div>
                        <div>
                          <h3 className="text-2xl font-bold text-gray-900">Personal Information</h3>
                          <p className="text-gray-600">Basic details for scholarship eligibility</p>
                        </div>
                        <div className="ml-auto">
                          <Badge color={getPersonalCompletion(profile) >= 80 ? 'emerald' : getPersonalCompletion(profile) >= 50 ? 'amber' : 'gray'}>
                            {getPersonalCompletion(profile)}% Complete
                          </Badge>
                        </div>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {[
                          { id: 'fullName', label: 'Full Name *', type: 'text', placeholder: 'John Doe', value: profile?.personal?.fullName },
                          { id: 'email', label: 'Email Address *', type: 'email', placeholder: 'john@example.com', value: profile?.personal?.email },
                          { id: 'age', label: 'Age *', type: 'number', placeholder: '25', value: profile?.personal?.age },
                          { id: 'nationality', label: 'Nationality *', type: 'select', options: countries, value: profile?.personal?.nationality },
                          { id: 'currentCountry', label: 'Current Country', type: 'select', options: countries, value: profile?.personal?.currentCountry }
                        ].map(field => (
                          <div key={field.id}>
                            <label htmlFor={field.id} className="block text-sm font-medium text-gray-700 mb-2">
                              {field.label}
                            </label>
                            {field.type === 'select' ? (
                              <select
                                id={field.id}
                                value={field.value || ''}
                                onChange={(e) => handleInputChange('personal', field.id, e.target.value)}
                                className="w-full px-4 py-3 bg-gray-50 rounded-xl border-2 border-gray-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 transition-all outline-none hover:border-gray-300"
                              >
                                <option value="">Select {field.label.toLowerCase().replace(' *', '')}</option>
                                {field.options?.map(opt => <option key={opt} value={opt}>{opt}</option>)}
                              </select>
                            ) : (
                              <input
                                type={field.type}
                                id={field.id}
                                value={field.value || ''}
                                onChange={(e) => handleInputChange('personal', field.id, e.target.value)}
                                className="w-full px-4 py-3 bg-gray-50 rounded-xl border-2 border-gray-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 transition-all outline-none hover:border-gray-300"
                                placeholder={field.placeholder}
                              />
                            )}
                          </div>
                        ))}
                      </div>
                    </ModernCard>
                  </motion.div>

                  {/* Academic Info */}
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.1 }}
                  >
                    <ModernCard className="p-8">
                      <div className="flex items-center mb-8">
                        <div className="w-14 h-14 rounded-2xl bg-gradient-to-r from-green-100 to-emerald-100 flex items-center justify-center mr-4 border border-emerald-200">
                          <GraduationCap className="w-7 h-7 text-emerald-600" />
                        </div>
                        <div>
                          <h3 className="text-2xl font-bold text-gray-900">Academic Information</h3>
                          <p className="text-gray-600">Academic credentials and achievements</p>
                        </div>
                        <div className="ml-auto">
                          <Badge color={getAcademicCompletion(profile) >= 80 ? 'emerald' : getAcademicCompletion(profile) >= 50 ? 'amber' : 'gray'}>
                            {getAcademicCompletion(profile)}% Complete
                          </Badge>
                        </div>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {[
                          { id: 'educationLevel', label: 'Education Level *', type: 'select', options: educationLevels, value: profile?.academic?.educationLevel },
                          { id: 'cgpa', label: 'CGPA/GPA *', type: 'text', placeholder: '3.5/4.0 or 8.5/10', value: profile?.academic?.cgpa },
                          { id: 'fieldOfStudy', label: 'Field of Study *', type: 'select', options: fieldsOfStudy, value: profile?.academic?.fieldOfStudy },
                          { id: 'languageScore', label: 'Language Test Score *', type: 'text', placeholder: 'IELTS 7.5 or TOEFL 100', value: profile?.academic?.languageScore },
                          { id: 'researchExperience', label: 'Research Experience', type: 'text', placeholder: 'e.g., 2 years in AI research', value: profile?.academic?.researchExperience },
                          { id: 'publications', label: 'Publications', type: 'text', placeholder: 'e.g., 3 journal papers', value: profile?.academic?.publications },
                          { id: 'awards', label: 'Awards & Honors', type: 'text', placeholder: 'e.g., Dean\'s List, Scholarships', value: profile?.academic?.awards }
                        ].map(field => (
                          <div key={field.id} className={field.id === 'awards' || field.id === 'publications' ? 'md:col-span-2' : ''}>
                            <label htmlFor={field.id} className="block text-sm font-medium text-gray-700 mb-2">
                              {field.label}
                            </label>
                            {field.type === 'select' ? (
                              <select
                                id={field.id}
                                value={field.value || ''}
                                onChange={(e) => handleInputChange('academic', field.id, e.target.value)}
                                className="w-full px-4 py-3 bg-gray-50 rounded-xl border-2 border-gray-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 transition-all outline-none hover:border-gray-300"
                              >
                                <option value="">Select {field.label.toLowerCase().replace(' *', '')}</option>
                                {field.options?.map(opt => <option key={opt} value={opt}>{opt}</option>)}
                              </select>
                            ) : (
                              <input
                                type={field.type}
                                id={field.id}
                                value={field.value || ''}
                                onChange={(e) => handleInputChange('academic', field.id, e.target.value)}
                                className="w-full px-4 py-3 bg-gray-50 rounded-xl border-2 border-gray-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 transition-all outline-none hover:border-gray-300"
                                placeholder={field.placeholder}
                              />
                            )}
                          </div>
                        ))}
                      </div>
                    </ModernCard>
                  </motion.div>

                  {/* Preferences */}
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2 }}
                  >
                    <ModernCard className="p-8">
                      <div className="flex items-center mb-8">
                        <div className="w-14 h-14 rounded-2xl bg-gradient-to-r from-purple-100 to-pink-100 flex items-center justify-center mr-4 border border-purple-200">
                          <Target className="w-7 h-7 text-purple-600" />
                        </div>
                        <div>
                          <h3 className="text-2xl font-bold text-gray-900">Study Preferences</h3>
                          <p className="text-gray-600">Your scholarship and study preferences</p>
                        </div>
                        <div className="ml-auto">
                          <Badge color={getPreferencesCompletion(profile) >= 80 ? 'emerald' : getPreferencesCompletion(profile) >= 50 ? 'amber' : 'gray'}>
                            {getPreferencesCompletion(profile)}% Complete
                          </Badge>
                        </div>
                      </div>
                      
                      <div className="space-y-8">
                        {/* Country Selection */}
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-4">
                            Preferred Countries *
                          </label>
                          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                            {countries.map(country => (
                              <button
                                key={country}
                                type="button"
                                onClick={() => handleCountrySelection(country)}
                                className={`flex items-center justify-between px-4 py-3 rounded-xl border-2 transition-all hover:scale-105 ${
                                  profile?.preferences?.countries?.includes(country)
                                    ? 'bg-gradient-to-r from-teal-50 to-blue-50 border-teal-300 text-teal-700'
                                    : 'bg-white border-gray-200 text-gray-700 hover:border-teal-200'
                                }`}
                              >
                                <div className="flex items-center">
                                  <Globe className="w-4 h-4 mr-2" />
                                  <span className="text-sm font-medium">{country}</span>
                                </div>
                                {profile?.preferences?.countries?.includes(country) && (
                                  <Check className="w-4 h-4 text-teal-600" />
                                )}
                              </button>
                            ))}
                          </div>
                        </div>
                        
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          <div>
                            <label htmlFor="degreeLevel" className="block text-sm font-medium text-gray-700 mb-2">
                              Degree Level *
                            </label>
                            <select
                              id="degreeLevel"
                              value={profile?.preferences?.degreeLevel || ''}
                              onChange={(e) => handleInputChange('preferences', 'degreeLevel', e.target.value)}
                              className="w-full px-4 py-3 bg-gray-50 rounded-xl border-2 border-gray-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 transition-all outline-none hover:border-gray-300"
                            >
                              <option value="">Select degree level</option>
                              <option value="bachelors">Bachelors</option>
                              <option value="masters">Masters</option>
                              <option value="phd">PhD</option>
                              <option value="postdoctoral">Postdoctoral</option>
                            </select>
                          </div>
                          <div>
                            <label htmlFor="fundingPriority" className="block text-sm font-medium text-gray-700 mb-2">
                              Funding Priority *
                            </label>
                            <select
                              id="fundingPriority"
                              value={profile?.preferences?.fundingPriority || 'any'}
                              onChange={(e) => handleInputChange('preferences', 'fundingPriority', e.target.value)}
                              className="w-full px-4 py-3 bg-gray-50 rounded-xl border-2 border-gray-200 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 transition-all outline-none hover:border-gray-300"
                            >
                              <option value="any">Any Funding</option>
                              <option value="full">Full Scholarship</option>
                              <option value="partial">Partial Scholarship</option>
                            </select>
                          </div>
                        </div>
                      </div>
                    </ModernCard>
                  </motion.div>
                </div>

                {/* Action Buttons */}
                <div className="flex flex-col sm:flex-row gap-4 justify-between pt-8 border-t border-gray-200">
                  <button
                    type="button"
                    onClick={() => setActiveTab('dashboard')}
                    className="px-6 py-3 bg-gray-100 text-gray-700 rounded-xl font-semibold hover:bg-gray-200 transition-all flex items-center justify-center hover:scale-105"
                  >
                    <ChevronLeft className="w-5 h-5 mr-2" />
                    Back to Dashboard
                  </button>
                  <div className="flex flex-col sm:flex-row gap-4">
                    <button
                      type="button"
                      onClick={saveProfile}
                      className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all flex items-center justify-center hover:scale-105"
                    >
                      <Save className="w-5 h-5 mr-2" />
                      Save Profile
                    </button>
                    <button
                      type="button"
                      onClick={fetchScholarships}
                      disabled={profileProgress < 50}
                      className="px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 flex items-center justify-center hover:scale-105"
                    >
                      <Sparkles className="w-5 h-5 mr-2" />
                      Find AI Matches
                    </button>
                    <button
                      type="button"
                      onClick={runAnalysis}
                      disabled={profileProgress < 60}
                      className="px-6 py-3 bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 flex items-center justify-center hover:scale-105"
                    >
                      <Brain className="w-5 h-5 mr-2" />
                      Get AI Analysis
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* Matches View */}
            {activeTab === 'matches' && (
              <div className="space-y-8">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
                  <div>
                    <h1 className="text-3xl font-bold text-gray-900">AI Scholarship Matches</h1>
                    <p className="text-gray-600">Personalized matches based on your profile</p>
                  </div>
                  <div className="flex flex-wrap gap-3">
                    <Badge color="teal" icon={User}>
                      Profile: {profileProgress}%
                    </Badge>
                    <button
                      type="button"
                      onClick={fetchScholarships}
                      disabled={isLoading}
                      className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 flex items-center space-x-2 hover:scale-105"
                    >
                      <Sparkles className="w-5 h-5" />
                      <span>{isLoading ? 'Refreshing...' : 'Refresh Matches'}</span>
                    </button>
                    <button
                      type="button"
                      onClick={runAnalysis}
                      disabled={profileProgress < 60}
                      className="px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 flex items-center space-x-2 hover:scale-105"
                    >
                      <Brain className="w-5 h-5" />
                      <span>AI Analysis</span>
                    </button>
                  </div>
                </div>

                {filteredScholarships.length > 0 ? (
                  <>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                      {filteredScholarships.map((scholarship) => (
                        <ScholarshipCard key={scholarship?.id} scholarship={scholarship} />
                      ))}
                    </div>
                    <div className="text-center pt-8 border-t border-gray-200">
                      <p className="text-gray-600">
                        Showing {filteredScholarships.length} of {scholarships.length} matches
                      </p>
                    </div>
                  </>
                ) : (
                  <ModernCard className="text-center py-12">
                    <Target className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                    <h3 className="text-2xl font-bold text-gray-900 mb-2">No matches found</h3>
                    <p className="text-gray-600 mb-6">
                      {profileProgress < 50 
                        ? 'Complete your profile to find matches' 
                        : 'Click "Refresh Matches" to find scholarships'}
                    </p>
                    <div className="flex flex-col sm:flex-row gap-3 justify-center">
                      <button
                        type="button"
                        onClick={() => setActiveTab('profile')}
                        className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all hover:scale-105"
                      >
                        Complete Profile ({profileProgress}%)
                      </button>
                      <button
                        type="button"
                        onClick={fetchScholarships}
                        disabled={profileProgress < 50}
                        className="px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 hover:scale-105"
                      >
                        Find AI Matches
                      </button>
                    </div>
                  </ModernCard>
                )}
              </div>
            )}

            {/* Analysis View */}
            {activeTab === 'analysis' && (
              <div className="space-y-8">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
                  <div>
                    <h1 className="text-3xl font-bold text-gray-900">AI Profile Analysis</h1>
                    <p className="text-gray-600">Comprehensive analysis of your scholarship readiness</p>
                  </div>
                  <div className="flex flex-wrap gap-3">
                    <Badge color="teal" icon={User}>
                      Profile: {profileProgress}%
                    </Badge>
                    <button
                      type="button"
                      onClick={runAnalysis}
                      disabled={isAnalysisLoading}
                      className="px-6 py-3 bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 flex items-center space-x-2 hover:scale-105"
                    >
                      {isAnalysisLoading ? (
                        <>
                          <Loader2 className="w-5 h-5 animate-spin mr-2" />
                          <span>Analyzing...</span>
                        </>
                      ) : (
                        <>
                          <Brain className="w-5 h-5 mr-2" />
                          <span>Refresh Analysis</span>
                        </>
                      )}
                    </button>
                  </div>
                </div>

                {/* Loading State */}
                {isAnalysisLoading ? (
                  <ModernCard className="text-center py-12">
                    <div className="w-16 h-16 border-4 border-teal-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                    <h3 className="text-2xl font-bold text-gray-900 mb-2">Generating AI Analysis</h3>
                    <p className="text-gray-600">Our AI is analyzing your profile and scholarship matches...</p>
                  </ModernCard>
                ) : analysis ? (
                  <>
                    {/* Overall Score */}
                    <ModernCard className="p-8">
                      <div className="flex flex-col lg:flex-row gap-8">
                        <div className="lg:w-1/3">
                          <div className="text-center">
                            <div className="text-6xl font-bold bg-gradient-to-r from-teal-600 to-blue-600 bg-clip-text text-transparent mb-2">
                              {analysis?.overallScore}%
                            </div>
                            <div className="text-xl font-semibold text-gray-900">Overall Score</div>
                            <div className="text-gray-600 mb-6">Scholarship Readiness</div>
                            <Badge color={analysis?.overallScore >= 80 ? 'emerald' : analysis?.overallScore >= 60 ? 'amber' : 'gray'}>
                              {analysis?.overallScore >= 80 ? 'Excellent' :
                               analysis?.overallScore >= 60 ? 'Good' :
                               'Needs Improvement'}
                            </Badge>
                          </div>
                        </div>
                        <div className="lg:w-2/3">
                          <h3 className="text-2xl font-bold text-gray-900 mb-6">Profile Strength Breakdown</h3>
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                            <div className="bg-gradient-to-br from-teal-50 to-blue-50 p-6 rounded-2xl border border-teal-100">
                              <div className="text-sm text-gray-600 mb-2">Academic</div>
                              <div className="text-3xl font-bold text-teal-700">{analysis?.profileStrength?.academic}%</div>
                            </div>
                            <div className="bg-gradient-to-br from-green-50 to-emerald-50 p-6 rounded-2xl border border-green-100">
                              <div className="text-sm text-gray-600 mb-2">Completeness</div>
                              <div className="text-3xl font-bold text-green-700">{analysis?.profileStrength?.profileCompleteness}%</div>
                            </div>
                            <div className="bg-gradient-to-br from-blue-50 to-cyan-50 p-6 rounded-2xl border border-blue-100">
                              <div className="text-sm text-gray-600 mb-2">Competitiveness</div>
                              <div className="text-3xl font-bold text-blue-700">{analysis?.profileStrength?.competitiveness}%</div>
                            </div>
                            <div className="bg-gradient-to-br from-purple-50 to-pink-50 p-6 rounded-2xl border border-purple-100">
                              <div className="text-sm text-gray-600 mb-2">Readiness</div>
                              <div className="text-3xl font-bold text-purple-700">{analysis?.profileStrength?.readiness}%</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </ModernCard>

                    {/* Match Breakdown */}
                    <ModernCard className="p-8">
                      <h3 className="text-2xl font-bold text-gray-900 mb-8">Match Breakdown</h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                        <div className="space-y-4">
                          <div className="flex items-center">
                            <GraduationCap className="w-6 h-6 text-teal-600 mr-3" />
                            <span className="font-semibold">Academic Match</span>
                          </div>
                          <div className="text-4xl font-bold text-teal-700">{analysis?.matchBreakdown?.academicMatch}%</div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div 
                              className="h-2 rounded-full bg-gradient-to-r from-teal-500 to-blue-500"
                              style={{ width: `${analysis?.matchBreakdown?.academicMatch}%` }}
                            ></div>
                          </div>
                        </div>
                        <div className="space-y-4">
                          <div className="flex items-center">
                            <Globe className="w-6 h-6 text-blue-600 mr-3" />
                            <span className="font-semibold">Country Match</span>
                          </div>
                          <div className="text-4xl font-bold text-blue-700">{analysis?.matchBreakdown?.countryMatch}%</div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div 
                              className="h-2 rounded-full bg-gradient-to-r from-blue-500 to-cyan-500"
                              style={{ width: `${analysis?.matchBreakdown?.countryMatch}%` }}
                            ></div>
                          </div>
                        </div>
                        <div className="space-y-4">
                          <div className="flex items-center">
                            <DollarSign className="w-6 h-6 text-emerald-600 mr-3" />
                            <span className="font-semibold">Funding Match</span>
                          </div>
                          <div className="text-4xl font-bold text-emerald-700">{analysis?.matchBreakdown?.fundingMatch}%</div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div 
                              className="h-2 rounded-full bg-gradient-to-r from-emerald-500 to-teal-500"
                              style={{ width: `${analysis?.matchBreakdown?.fundingMatch}%` }}
                            ></div>
                          </div>
                        </div>
                        <div className="space-y-4">
                          <div className="flex items-center">
                            <Calendar className="w-6 h-6 text-purple-600 mr-3" />
                            <span className="font-semibold">Timeline Match</span>
                          </div>
                          <div className="text-4xl font-bold text-purple-700">{analysis?.matchBreakdown?.timelineMatch}%</div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div 
                              className="h-2 rounded-full bg-gradient-to-r from-purple-500 to-pink-500"
                              style={{ width: `${analysis?.matchBreakdown?.timelineMatch}%` }}
                            ></div>
                          </div>
                        </div>
                      </div>
                    </ModernCard>

                    {/* AI Insights */}
                    {analysis?.aiInsights && analysis.aiInsights.length > 0 && (
                      <div className="bg-gradient-to-r from-teal-50 to-blue-50 rounded-3xl p-8 border border-teal-200">
                        <h3 className="text-2xl font-bold text-gray-900 mb-6 flex items-center">
                          <Brain className="w-7 h-7 text-teal-600 mr-3" />
                          AI Insights
                        </h3>
                        <div className="space-y-4">
                          {analysis.aiInsights.map((insight, idx) => (
                            <div key={idx} className="flex items-start">
                              <Lightbulb className="w-6 h-6 text-amber-500 mt-0.5 mr-4 flex-shrink-0" />
                              <p className="text-gray-700 text-lg">{insight}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Strengths & Weaknesses */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                      <ModernCard className="p-8">
                        <h3 className="text-2xl font-bold text-gray-900 mb-8 flex items-center">
                          <CheckCircle className="w-7 h-7 text-emerald-600 mr-3" />
                          Key Strengths
                        </h3>
                        <div className="space-y-6">
                          {analysis?.strengths?.map((category, idx) => (
                            <div key={idx} className="border-l-4 border-emerald-500 pl-6 py-4">
                              <div className="flex justify-between items-center mb-4">
                                <h4 className="font-bold text-gray-900 text-lg">{category.category}</h4>
                                <span className="text-sm font-semibold text-emerald-700">{category.score}%</span>
                              </div>
                              <ul className="space-y-3">
                                {category.items?.slice(0, 2).map((item, itemIdx) => (
                                  <li key={itemIdx} className="flex items-start">
                                    <div className="w-2 h-2 bg-emerald-500 rounded-full mt-2 mr-4 flex-shrink-0"></div>
                                    <span className="text-gray-700">{item}</span>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          ))}
                        </div>
                      </ModernCard>

                      <ModernCard className="p-8">
                        <h3 className="text-2xl font-bold text-gray-900 mb-8 flex items-center">
                          <AlertTriangle className="w-7 h-7 text-amber-600 mr-3" />
                          Areas for Improvement
                        </h3>
                        <div className="space-y-6">
                          {analysis?.weaknesses?.map((category, idx) => (
                            <div key={idx} className="border-l-4 border-amber-500 pl-6 py-4">
                              <div className="flex justify-between items-center mb-4">
                                <h4 className="font-bold text-gray-900 text-lg">{category.category}</h4>
                                <Badge color={category.impact === 'high' ? 'gray' : category.impact === 'medium' ? 'amber' : 'amber'}>
                                  {category.impact?.toUpperCase()} IMPACT
                                </Badge>
                              </div>
                              <ul className="space-y-3">
                                {category.items?.slice(0, 2).map((item, itemIdx) => (
                                  <li key={itemIdx} className="flex items-start">
                                    <div className="w-2 h-2 bg-amber-500 rounded-full mt-2 mr-4 flex-shrink-0"></div>
                                    <span className="text-gray-700">{item}</span>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          ))}
                        </div>
                      </ModernCard>
                    </div>

                    {/* Recommendations */}
                    <ModernCard className="p-8">
                      <h3 className="text-2xl font-bold text-gray-900 mb-8 flex items-center">
                        <Sparkles className="w-7 h-7 text-blue-600 mr-3" />
                        AI Recommendations
                      </h3>
                      <div className="space-y-6">
                        {analysis?.recommendations?.map((rec, idx) => (
                          <div key={idx} className={`p-6 rounded-2xl border-2 ${
                            rec.priority === 'high' ? 'bg-gradient-to-r from-red-50 to-orange-50 border-red-200' :
                            rec.priority === 'medium' ? 'bg-gradient-to-r from-yellow-50 to-amber-50 border-yellow-200' :
                            'bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200'
                          }`}>
                            <div className="flex items-start">
                              <div className={`w-10 h-10 rounded-full flex items-center justify-center mr-6 flex-shrink-0 ${
                                rec.priority === 'high' ? 'bg-gradient-to-r from-red-500 to-orange-500' :
                                rec.priority === 'medium' ? 'bg-gradient-to-r from-yellow-500 to-amber-500' :
                                'bg-gradient-to-r from-blue-500 to-cyan-500'
                              }`}>
                                <span className="text-white font-bold text-lg">{idx + 1}</span>
                              </div>
                              <div className="flex-1">
                                <div className="flex justify-between items-start mb-4">
                                  <h4 className="font-bold text-gray-900 text-lg">{rec.action}</h4>
                                  <Badge color={rec.priority === 'high' ? 'gray' : rec.priority === 'medium' ? 'amber' : 'blue'}>
                                    {rec.priority?.toUpperCase()} PRIORITY
                                  </Badge>
                                </div>
                                <div className="grid grid-cols-2 gap-6">
                                  <div>
                                    <div className="text-gray-600 mb-2">Timeline</div>
                                    <div className="font-semibold text-gray-900 text-lg">{rec.timeline}</div>
                                  </div>
                                  <div>
                                    <div className="text-gray-600 mb-2">Impact</div>
                                    <div className="font-semibold text-gray-900 text-lg">{rec.impact}</div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </ModernCard>

                    {/* Statistics */}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                      <ModernCard className="p-6">
                        <div className="flex items-center mb-6">
                          <Target className="w-8 h-8 text-teal-600 mr-4" />
                          <div>
                            <div className="text-3xl font-bold text-gray-900">{analysis?.estimatedSuccess}%</div>
                            <div className="text-sm text-gray-600">Estimated Success Rate</div>
                          </div>
                        </div>
                        <p className="text-sm text-gray-700">
                          Based on your profile and current scholarship landscape
                        </p>
                      </ModernCard>
                      <ModernCard className="p-6">
                        <div className="flex items-center mb-6">
                          <TrendingUp className="w-8 h-8 text-emerald-600 mr-4" />
                          <div>
                            <div className="text-3xl font-bold text-gray-900">{analysis?.totalMatches}</div>
                            <div className="text-sm text-gray-600">Total Matches Found</div>
                          </div>
                        </div>
                        <p className="text-sm text-gray-700">
                          Scholarships matching your profile criteria
                        </p>
                      </ModernCard>
                      <ModernCard className="p-6">
                        <div className="flex items-center mb-6">
                          <Coins className="w-8 h-8 text-amber-600 mr-4" />
                          <div>
                            <div className="text-3xl font-bold text-gray-900">{analysis?.totalFunding}</div>
                            <div className="text-sm text-gray-600">Total Funding Available</div>
                          </div>
                        </div>
                        <p className="text-sm text-gray-700">
                          Combined value of matching scholarships
                        </p>
                      </ModernCard>
                    </div>
                  </>
                ) : (
                  <ModernCard className="text-center py-12">
                    <Brain className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                    <h3 className="text-2xl font-bold text-gray-900 mb-2">No analysis available</h3>
                    <p className="text-gray-600 mb-6">
                      Click Get AI Analysis to generate detailed insights about your scholarship readiness
                    </p>
                    <button
                      type="button"
                      onClick={runAnalysis}
                      disabled={profileProgress < 60}
                      className="px-6 py-3 bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50 hover:scale-105"
                    >
                      Get AI Analysis
                    </button>
                  </ModernCard>
                )}
              </div>
            )}
          </motion.div>
        </AnimatePresence>

        {/* Tips Section */}
        <div className="mt-16">
          <div className="text-center mb-8">
            <Badge color="teal" icon={Sparkles}>
              Expert Tips
            </Badge>
            <h3 className="text-3xl font-bold text-gray-900 mt-4 mb-4">
              Maximize Your Scholarship Success
            </h3>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Follow these expert recommendations to improve your scholarship applications
            </p>
          </div>
          
          <div className="grid md:grid-cols-2 gap-8">
            <ModernCard className="p-8">
              <div className="flex items-center gap-4 mb-6">
                <div className="p-3 rounded-2xl bg-gradient-to-r from-teal-50 to-blue-50 border border-teal-100">
                  <Target className="w-7 h-7 text-teal-600" />
                </div>
                <h4 className="text-2xl font-bold text-gray-900">
                  Application Strategy
                </h4>
              </div>
              <ul className="space-y-6">
                <li className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center flex-shrink-0">
                    <CheckCircle className="w-5 h-5 text-emerald-600" />
                  </div>
                  <span className="text-gray-700">Apply to multiple scholarships to increase your chances</span>
                </li>
                <li className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center flex-shrink-0">
                    <Award className="w-5 h-5 text-emerald-600" />
                  </div>
                  <span className="text-gray-700">Tailor your application to each scholarships specific requirements</span>
                </li>
                <li className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center flex-shrink-0">
                    <Clock className="w-5 h-5 text-emerald-600" />
                  </div>
                  <span className="text-gray-700">Start your applications early to avoid last-minute stress</span>
                </li>
              </ul>
            </ModernCard>
            
            <ModernCard className="p-8">
              <div className="flex items-center gap-4 mb-6">
                <div className="p-3 rounded-2xl bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-100">
                  <Trophy className="w-7 h-7 text-blue-600" />
                </div>
                <h4 className="text-2xl font-bold text-gray-900">
                  Best Practices
                </h4>
              </div>
              <ul className="space-y-6">
                <li className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-teal-100 flex items-center justify-center flex-shrink-0">
                    <ExternalLink className="w-5 h-5 text-teal-600" />
                  </div>
                  <span className="text-gray-700">Always verify scholarship details on official websites</span>
                </li>
                <li className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-teal-100 flex items-center justify-center flex-shrink-0">
                    <DollarSign className="w-5 h-5 text-teal-600" />
                  </div>
                  <span className="text-gray-700">Factor in all costs including living expenses and travel</span>
                </li>
                <li className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-teal-100 flex items-center justify-center flex-shrink-0">
                    <Award className="w-5 h-5 text-teal-600" />
                  </div>
                  <span className="text-gray-700">Highlight unique experiences and achievements in your applications</span>
                </li>
              </ul>
            </ModernCard>
          </div>
        </div>

        {/* Final CTA */}
        <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 Find Your Perfect Scholarship?
            </h2>
            <p className="text-xl text-teal-100 mb-10 max-w-2xl mx-auto">
              Let our AI help you discover and secure the best funding opportunities for your education
            </p>
            
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <button
                type="button"
                onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
                className="group bg-white text-teal-600 px-12 py-5 rounded-2xl text-lg font-bold shadow-2xl hover:shadow-3xl hover:scale-105 transition-all duration-300 flex items-center gap-3"
              >
                <Brain className="animate-bounce" />
                Start New Search
                <ChevronRight className="transition-transform duration-300 group-hover:translate-x-2" />
              </button>
              
              <button
                type="button"
                onClick={fetchScholarships}
                disabled={profileProgress < 50}
                className="px-10 py-5 border-2 border-white/30 text-white rounded-2xl font-semibold hover:bg-white/10 transition-all duration-300 flex items-center gap-2 disabled:opacity-50 hover:scale-105"
              >
                <Target className="w-5 h-5" />
                Find AI Matches
              </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 Matching • Data-Driven Insights</span>
            </div>
          </div>
        </div>
      </main>

      {/* Scholarship Lead Modal */}
      <LeadModal 
        isOpen={showLeadModal}
        onClose={() => setShowLeadModal(false)}
        onSuccess={handleLeadSuccess}
        formData={profile}
      />

      {/* Profile Completion Modal */}
      <AnimatePresence>
        {profileCompletionModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
            onClick={() => setProfileCompletionModal(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="bg-white rounded-3xl p-8 max-w-md w-full border border-gray-100 shadow-2xl"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="text-center mb-6">
                <div className="w-16 h-16 rounded-full bg-gradient-to-r from-teal-500 to-blue-500 flex items-center justify-center mx-auto mb-4">
                  <User className="w-8 h-8 text-white" />
                </div>
                <h3 className="text-2xl font-bold text-gray-900 mb-2">
                  Complete Your Profile First
                </h3>
                <p className="text-gray-600">
                  Your profile is {profileProgress}% complete. Complete it to unlock AI matching and analysis features.
                </p>
              </div>
              
              <div className="mb-8">
                <div className="w-full bg-gray-200 rounded-full h-3">
                  <div 
                    className="h-3 rounded-full bg-gradient-to-r from-teal-500 to-blue-500"
                    style={{ width: `${profileProgress}%` }}
                  ></div>
                </div>
                <div className="flex justify-between mt-2 text-sm text-gray-600">
                  <span>{profileProgress}% Complete</span>
                  <span>{100 - profileProgress}% Remaining</span>
                </div>
              </div>
              
              <div className="space-y-3">
                <button
                  type="button"
                  onClick={() => {
                    setProfileCompletionModal(false);
                    setActiveTab('profile');
                  }}
                  className="w-full px-6 py-4 bg-gradient-to-r from-teal-600 to-blue-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all hover:scale-105"
                >
                  Complete Profile Now
                </button>
                <button
                  type="button"
                  onClick={() => setProfileCompletionModal(false)}
                  className="w-full px-6 py-4 bg-gray-100 text-gray-700 rounded-xl font-semibold hover:bg-gray-200 transition-all"
                >
                  Maybe Later
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Toast Notification */}
      {toast.visible && (
        <motion.div
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 50 }}
          className={`fixed bottom-4 right-4 px-6 py-3 rounded-xl shadow-lg z-50 border ${
            toast.type === 'success' ? 'bg-gradient-to-r from-green-50 to-emerald-50 border-green-200 text-green-800' :
            toast.type === 'error' ? 'bg-gradient-to-r from-red-50 to-orange-50 border-red-200 text-red-800' :
            'bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200 text-blue-800'
          }`}
        >
          <div className="flex items-center">
            {toast.type === 'success' && <CheckCircle className="w-5 h-5 mr-3" />}
            {toast.type === 'error' && <AlertCircle className="w-5 h-5 mr-3" />}
            {toast.type === 'info' && <Info className="w-5 h-5 mr-3" />}
            <span className="font-medium">{toast.message}</span>
          </div>
        </motion.div>
      )}
    </div>
  );
};

// Helper functions for profile completion
const getPersonalCompletion = (profile: Profile): number => {
  const fields = ['fullName', 'email', 'age', 'nationality', 'currentCountry'];
  const filled = fields.filter(field => profile?.personal?.[field as keyof PersonalInfo]?.trim()).length;
  return Math.round((filled / fields.length) * 100);
};

const getAcademicCompletion = (profile: Profile): number => {
  const fields = ['educationLevel', 'cgpa', 'fieldOfStudy', 'languageScore'];
  const filled = fields.filter(field => profile?.academic?.[field as keyof AcademicInfo]?.trim()).length;
  return Math.round((filled / fields.length) * 100);
};

const getPreferencesCompletion = (profile: Profile): number => {
  let score = 0;
  if (profile?.preferences?.countries?.length > 0) score += 40;
  if (profile?.preferences?.degreeLevel) score += 30;
  if (profile?.preferences?.fundingPriority) score += 30;
  return score;
};

const getMissingFields = (profile: Profile): string[] => {
  const missing = [];
  
  if (!profile?.personal?.fullName) missing.push('Full Name');
  if (!profile?.personal?.email) missing.push('Email');
  if (!profile?.personal?.age) missing.push('Age');
  if (!profile?.personal?.nationality) missing.push('Nationality');
  if (!profile?.academic?.cgpa) missing.push('GPA/CGPA');
  if (!profile?.academic?.fieldOfStudy) missing.push('Field of Study');
  if (!profile?.academic?.languageScore) missing.push('Language Score');
  if (profile?.preferences?.countries?.length === 0) missing.push('Country Preferences');
  if (!profile?.preferences?.degreeLevel) missing.push('Degree Level');
  
  return missing;
};

// Animation styles
const animationStyles = `
  @keyframes float {
    0%, 100% {
      transform: translateY(0) rotate(0deg);
    }
    50% {
      transform: translateY(-20px) rotate(180deg);
    }
  }
  
  .animate-float {
    animation: float 20s infinite linear;
  }
`;

// Add styles to head
if (typeof document !== 'undefined') {
  const style = document.createElement('style');
  style.innerHTML = animationStyles;
  document.head.appendChild(style);
}

export default AiScholarshipMatch;