'use client';

import { useState, useEffect, useRef, useMemo } from 'react';
import { useUserStore } from '../../../store/useUserStore';
import jsPDF from 'jspdf';
import AuthModal from '../../components/AuthModal';
import LeadModal from '../../components/LeadModal';
import { 
  Brain,
  MessageSquare,
  AlertTriangle,
  CheckCircle,
  Users,
  GraduationCap,
  DollarSign,
  Clock,
  Globe,
  FileText,
  Shield,
  Download,
  ChevronRight,
  Sparkles,
  Target,
  Lightbulb,
  Zap,
  X,
  HelpCircle,
  BarChart3,
  Lock,
  Unlock,
  Trophy,
  TrendingUp,
  Award,
  Flag,
  Briefcase,
  Home,
  BookOpen,
  RotateCcw,
  Eye,
  EyeOff,
  User,
  LogOut,
  ExternalLink,
  ChevronDown,
  Calendar,
  Building2,
  ChevronLeft,
  ChevronUp,
  ChevronDown as ChevronDownIcon,
  Mail,
  Phone,
  BarChart,
  Send,
  Printer,
  Share2,
  Loader2,
  Save,
  Bookmark,
  BookmarkCheck,
  ClipboardList,
  ThumbsUp,
  Brain as BrainIcon,
  MapPin,
  Star,
  CalendarDays,
  Languages
} from 'lucide-react';

// Modern Card Component (from reference)
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 (from reference)
type BadgeProps = {
  children: React.ReactNode;
  color?: 'teal' | 'blue' | 'emerald' | 'amber' | 'gray' | 'rose';
  icon?: React.ElementType; // ✅ optional
};

const Badge = ({ children, color = 'teal', icon: Icon }: BadgeProps) => {
  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',
    rose: 'bg-rose-100 text-rose-700 border-rose-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>
  );
};


// Stat Card Component (adapted from reference)
const StatCard = ({ icon: Icon, number, label, color = 'teal' }) => {
  const colorClasses = {
    teal: 'bg-gradient-to-r from-teal-500 to-blue-500',
    blue: 'bg-gradient-to-r from-blue-500 to-cyan-500',
    emerald: 'bg-gradient-to-r from-emerald-500 to-teal-500',
    amber: 'bg-gradient-to-r from-amber-500 to-orange-500'
  };

  return (
    <div className="text-center">
      <div className={`inline-flex items-center justify-center w-12 h-12 ${colorClasses[color]} text-white rounded-2xl mb-3`}>
        {Icon}
      </div>
      <div className="text-2xl font-bold text-gray-900 mb-1">{number}</div>
      <div className="text-gray-600 text-sm">{label}</div>
    </div>
  );
};

// Feature Card Component (from reference)
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>
);

// Constants (unchanged)
const COUNTRIES = [
  'UK', 'Canada', 'USA', 'Australia', 'Germany', 'Italy', 
  'France', 'Netherlands', 'Sweden', 'Switzerland', 'Japan',
  'South Korea', 'Singapore', 'New Zealand', 'Ireland'
];

const DEGREE_LEVELS = [
  'Foundation/Diploma', 'Bachelor\'s', 'Master\'s', 'PhD', 'Postgraduate Diploma'
];

const UNIVERSITY_TYPES = [
  'Public University (High Ranking)',
  'Public University (Mid Ranking)',
  'Private University',
  'Community College',
  'Vocational Institute'
];

const SPONSOR_TYPES = [
  'Self-funded',
  'Parents',
  'Relative',
  'Education Loan',
  'Scholarship',
  'Employer'
];

const STUDY_GAPS = ['0 years', '1-2 years', '3-5 years', '6+ years'];

const LANGUAGE_PROOFS = [
  'IELTS',
  'TOEFL',
  'PTE',
  'Duolingo',
  'Medium of Instruction',
  'No English Test'
];

// Storage keys (unchanged)
const STORAGE_KEYS = {
  LAST_SEARCH: 'embassy_predictor_last_search',
  LAST_RESULT: 'embassy_predictor_last_result',
  FORM_DATA: 'embassy_predictor_form_data',
  USER_DATA: 'embassy_predictor_user_data'
};

// Type Definitions (unchanged)
type CountryInsight = {
  focus: string[];
  officerMindset: string[];
  avoid: string[];
};
type LeadData = {
  name: string;
  email: string;
  phoneNumber: string;
};

type WeakArea = {
  area: string;
  severity: 'low' | 'medium' | 'high';
  improvement: string;
};

type InterviewQuestion = {
  question: string;
  category: 'study_intent' | 'financial' | 'return_intent' | 'background';
  riskLevel: 'low' | 'medium' | 'high';
  intent: string;
  sampleAnswer: string;
  officerIntent: string;
  commonMistakes: string[];
  likelyFollowUps: string[];
};

type Prediction = {
  interviewReadinessScore: number;
  confidence: number;
  riskLevel: 'low' | 'medium' | 'high';
  topQuestions: InterviewQuestion[];
  weakAreas: WeakArea[];
  countryInsights: CountryInsight;
  generatedAt: string;
  disclaimer: string;
  limited?: boolean;
  totalQuestions?: number;
  unlockMessage?: string;
};

export default function EmbassyInterviewPredictor() {
  const [loading, setLoading] = useState(false);
  const [showFullReport, setShowFullReport] = useState(false);
  const [prediction, setPrediction] = useState<Prediction | null>(null);
  const [unlocked, setUnlocked] = useState(false);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [expandedQuestion, setExpandedQuestion] = useState<number | null>(null);
  const [lastSearchVisible, setLastSearchVisible] = useState(true);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const { user, isLoggedIn, setUser } = useUserStore();
  const formRef = useRef<HTMLDivElement>(null);
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // Add these states
  const [showLeadModal, setShowLeadModal] = useState(false);
  const [leadData, setLeadData] = useState<LeadData | null>(null);
  
  // Add this state to track form validity
  const [isFormValid, setIsFormValid] = useState(false);

  // Add this useEffect to load saved lead data
  useEffect(() => {
    const loadSavedLead = () => {
      try {
        const savedLead = localStorage.getItem('embassy_predictor_lead');
        if (savedLead) {
          const lead = JSON.parse(savedLead);
          // Check if lead is still valid (1 day 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);
      }
    };
    
    loadSavedLead();
  }, []);
  
  const [form, setForm] = useState({
    country: '',
    course: '',
    degreeLevel: '',
    universityType: '',
    sponsorType: '',
    studyGap: '',
    previousRefusals: false,
    languageProof: '',
    ieltsScore: '',
    age: '',
    workExperience: ''
  });

  // Use useMemo to validate form without causing re-renders
  const formValidity = useMemo(() => {
    const errors: Record<string, string> = {};
    const requiredFields = [
      'country', 'course', 'degreeLevel', 'universityType', 
      'sponsorType', 'studyGap', 'languageProof'
    ];

    requiredFields.forEach(field => {
      if (!form[field as keyof typeof form]) {
        errors[field] = 'This field is required';
      }
    });

    // Validate IELTS score if IELTS is selected
    if (form.languageProof.includes('IELTS') && !form.ieltsScore) {
      errors.ieltsScore = 'IELTS score is required';
    }

    return {
      isValid: Object.keys(errors).length === 0,
      errors
    };
  }, [form]);

  // Update form validity when form changes
  useEffect(() => {
    setIsFormValid(formValidity.isValid);
  }, [formValidity]);

  // Load data from localStorage
  useEffect(() => {
    const loadSavedData = () => {
      try {
        const savedFormData = localStorage.getItem(STORAGE_KEYS.FORM_DATA);
        const savedResult = localStorage.getItem(STORAGE_KEYS.LAST_RESULT);
        const unlockedFlag = localStorage.getItem('unlockedPredictor');
        
        if (savedFormData) setForm(JSON.parse(savedFormData));
        if (savedResult) setPrediction(JSON.parse(savedResult));
        if (unlockedFlag === 'true') setUnlocked(true);
      } catch (err) {
        console.error('Error loading saved data:', err);
      }
    };
    
    loadSavedData();
  }, []);

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

  // Save user data
  useEffect(() => {
    if (user) {
      localStorage.setItem(STORAGE_KEYS.USER_DATA, JSON.stringify(user));
    }
  }, [user]);

  // Enhanced Country Templates with detailed Officer Mindset (unchanged)
  const COUNTRY_TEMPLATES: Record<string, CountryInsight> = {
    UK: {
      focus: [
        'Academic progression logic',
        'Course relevance to background',
        'Career plans in home country',
        'Financial sustainability'
      ],
      officerMindset: [
        'Values logical education pathway over random course selection',
        'Suspicious of students changing fields without justification',
        'Wants specific university research evidence, not just rankings',
        'Hates vague answers about post-study plans',
        'Verifies funds can cover entire stay without working'
      ],
      avoid: [
        'Settlement intentions or PR plans',
        'Generic statements about "better education"',
        'Unclear career progression logic',
        'Mentioning family members in UK',
        'Wanting to work during studies'
      ]
    },
    Canada: {
      focus: [
        'Genuine Student Intent (GSI)',
        'Financial capacity proof',
        'Strong return intent',
        'Academic capability'
      ],
      officerMindset: [
        'Very strict on post-study return plans',
        'Deeply verifies source of funds and sponsor credibility',
        'Suspicious of any PR or settlement discussions',
        'Wants concrete home country ties',
        'Checks for previous visa violations'
      ],
      avoid: [
        'Permanent residency plans or discussions',
        'Family migration intentions',
        'Weak home country connections',
        'Unclear sponsor relationships',
        'Career plans in Canada'
      ]
    },
    USA: {
      focus: [
        'Non-immigrant intent',
        'Strong ties to home country',
        'Academic capability',
        'Financial stability'
      ],
      officerMindset: [
        'Focuses intensely on proving non-immigrant intent',
        'Wants strong family/business/property ties to home country',
        'Suspicious of students with family in USA',
        'Verifies academic capability for chosen program',
        'Checks for previous visa denials or violations'
      ],
      avoid: [
        'Any immigration intent discussions',
        'Family members living in USA',
        'Long-term stay plans',
        'Career opportunities in USA',
        'Weak home country connections'
      ]
    },
    Australia: {
      focus: [
        'Genuine Temporary Entrant (GTE)',
        'Course value for home country',
        'Financial capacity',
        'English proficiency'
      ],
      officerMindset: [
        'Assesses genuine temporary stay intention',
        'Looks for course relevance to home country needs',
        'Verifies sustainable funds for entire stay',
        'Wants clear post-study departure plans',
        'Suspicious of career changes without logic'
      ],
      avoid: [
        'Permanent migration discussions',
        'Overstaying history',
        'Weak home ties',
        'Unclear study motivations',
        'Financial dependence on work'
      ]
    },
    default: {
      focus: [
        'Study intent verification',
        'Financial capacity proof',
        'Return plan clarity',
        'Academic capability'
      ],
      officerMindset: [
        'Wants genuine student intent over immigration intent',
        'Verifies financial sustainability for entire stay',
        'Checks strong home country ties and return plans',
        'Ensures academic capability for chosen program',
        'Looks for specific details not vague answers'
      ],
      avoid: [
        'Settlement or immigration intentions',
        'Vague career plans without specifics',
        'Financial dependence on work',
        'Weak home country connections',
        'Contradictory statements'
      ]
    }
  };

  // Validate form function
  const validateForm = () => {
    const errors: Record<string, string> = {};
    const requiredFields = [
      'country', 'course', 'degreeLevel', 'universityType', 
      'sponsorType', 'studyGap', 'languageProof'
    ];

    requiredFields.forEach(field => {
      if (!form[field as keyof typeof form]) {
        errors[field] = 'This field is required';
      }
    });

    // Validate IELTS score if IELTS is selected
    if (form.languageProof.includes('IELTS') && !form.ieltsScore) {
      errors.ieltsScore = 'IELTS score is required';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async () => {
    // Validate form before proceeding
    if (!validateForm()) {
      alert('Please fill all required fields correctly');
      // Scroll to first error
      const firstErrorField = Object.keys(formErrors)[0];
      if (firstErrorField && formRef.current) {
        const element = formRef.current.querySelector(`[name="${firstErrorField}"]`);
        element?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
      return;
    }

    // Check if we have valid lead data
    const savedLead = localStorage.getItem('embassy_predictor_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 no valid lead data, show lead modal
    if (!hasValidLead || !leadData) {
      setShowLeadModal(true);
      return;
    }

    // If we have valid lead data, proceed with API call
    await submitPredictionWithLead();
  };

  // New function to handle submission with lead data
  const submitPredictionWithLead = async () => {
    if (!leadData) {
      alert('You Can Click On Generate Now');
      return;
    }

    setLoading(true);
    
    try {
      // Combine lead data with form data
      const submissionData = {
        ...form,
        ...leadData,
        ieltsScore: form.ieltsScore ? parseFloat(form.ieltsScore) : undefined,
        age: form.age ? parseInt(form.age) : undefined,
        workExperience: form.workExperience ? parseInt(form.workExperience) : undefined
      };

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

      const data = await response.json();
      
      if (data.success) {
        // Set the actual prediction from API response
        setPrediction(data.data);
        
        // Send lead data to database API (similar to your reference)
        // Do this in the background, don't wait for it
        sendLeadToDatabase(submissionData).catch(error => {
          console.error('Failed to save lead to database:', error);
        });
        
        if (user) {
          setUnlocked(true);
        } else {
          setUnlocked(false);
        }
      } else {
        // API returned success: false, fallback
        console.warn('API returned error:', data.error);
        generateFallbackPrediction();
        
        // Still send lead data even if prediction fails
        sendLeadToDatabase(submissionData).catch(error => {
          console.error('Failed to save lead to database:', error);
        });
      }
    } catch (error) {
      console.error('Error calling API:', error);
      // Only show fallback if API call fails completely
      generateFallbackPrediction();
      
      // Still send lead data even if prediction fails
      if (leadData) {
        try {
          await sendLeadToDatabase({
            ...form,
            ...leadData
          });
        } catch (dbError) {
          console.error('Failed to save lead to database:', dbError);
        }
      }
    } finally {
      setLoading(false);
    }
  };

  // Function to send lead data to database
  const sendLeadToDatabase = async (data: any) => {
    try {
      // Extract the data in the format your database expects
      const leadPayload = {
        name: data.name || '',
        email: data.email || '',
        phoneNumber: data.phoneNumber || '',
        age: data.age || '', // new field
        country: data.country || '',
        course: data.course || '',
        degreeLevel: data.degreeLevel || '',
        ieltsScore: parseFloat(data.ieltsScore) || 0,
        languageProof: data.languageProof || '',
        previousRefusals: data.previousRefusals ? 1 : 0,
        sponsorType: data.sponsorType || '',
        studyGap: data.studyGap || '',
        universityType: data.universityType || '',
        workExperience: parseInt(data.workExperience) || 0
      };

      // Send to your database API
      const response = await fetch('/api/frontend/ai-embassy-interview-predictor/store', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(leadPayload)
      });

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

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

  // Add this function to handle lead modal success
  const handleLeadSuccess = async (newLeadData: LeadData) => {
    setLeadData(newLeadData);
    await submitPredictionWithLead();
  };

  const generateFallbackPrediction = () => {
    // Enhanced fallback with 15 questions
    const fallbackQuestions: InterviewQuestion[] = [
      {
        question: `Why did you choose ${form.course} at ${form.universityType}?`,
        category: 'study_intent',
        riskLevel: 'high',
        intent: 'Check academic logic and genuine interest',
        sampleAnswer: `My ${form.degreeLevel.toLowerCase()} in related field provides strong foundation. I chose this specific program for its focus on [specific specialization], which aligns perfectly with my career goal of [specific position] in my home country's growing [industry] sector.`,
        officerIntent: 'Verify course is relevant to background and career, not just visa pathway',
        commonMistakes: ['Generic quality claims without specifics', 'No mention of specific modules or faculty', 'Mentioning immigration or settlement benefits'],
        likelyFollowUps: ['What specific modules interest you most?', 'How did you research this university?', 'Name one professor whose work you admire']
      },
      {
        question: `Who is ${form.sponsorType.toLowerCase()} your education and what is their relationship to you?`,
        category: 'financial',
        riskLevel: form.sponsorType === 'Self-funded' ? 'low' : form.sponsorType === 'Parents' ? 'medium' : 'high',
        intent: 'Verify financial credibility and relationship',
        sampleAnswer: `My ${form.sponsorType === 'Self-funded' ? 'own savings from' : form.sponsorType.toLowerCase() + ', who is my'} [relationship], is funding my education. They have stable income from [source] and have provided all required financial documents showing sufficient funds for tuition and living expenses.`,
        officerIntent: 'Ensure funds are legitimate, sufficient, and sponsor has genuine interest',
        commonMistakes: ['Unclear sponsor relationship', 'Inconsistent financial amounts', 'No documentation plan mentioned'],
        likelyFollowUps: ['What is the annual income?', 'Show relationship proof documents?', 'Why are they investing in your education?']
      },
      {
        question: 'What are your concrete plans after graduation?',
        category: 'return_intent',
        riskLevel: 'high',
        intent: 'Check return intention and career planning',
        sampleAnswer: `I plan to return immediately after graduation to work as [specific position] at companies like [company names] in my home country. The [specific skill] I'll gain is in high demand in our growing [industry] sector, with starting salaries of [salary range].`,
        officerIntent: 'Verify student will leave country after studies and has concrete, achievable plans',
        commonMistakes: ['Wanting to gain work experience abroad first', 'Vague or unrealistic plans', 'Mentioning immigration programs or PR'],
        likelyFollowUps: ['Name three specific companies you target', 'What starting salary do you expect?', 'Do you have any job offers already?']
      },
      {
        question: `What were you doing during your ${form.studyGap} study gap?`,
        category: 'background',
        riskLevel: form.studyGap !== '0 years' ? 'high' : 'low',
        intent: 'Justify gap period productively',
        sampleAnswer: `During my gap, I worked as [position] at [company] gaining practical experience in [skills]. I also completed [certifications/courses] in [subjects] to prepare for this program and stayed updated with industry developments through [specific activities].`,
        officerIntent: 'Verify gap was productive, student learned relevant skills, and is academically ready',
        commonMistakes: ['"Just preparing for studies" without specifics', 'Unemployment without valid explanation', 'Inconsistent timeline or activities'],
        likelyFollowUps: ['Can you show work certificates?', 'What specific skills did you learn?', 'Why return to studies now?']
      },
      {
        question: 'Why not study similar course in your home country?',
        category: 'study_intent',
        riskLevel: 'medium',
        intent: 'Check genuine need for expensive overseas education',
        sampleAnswer: `While good programs exist locally, this specific program offers unique [mention specific: research facilities, faculty expertise, industry partnerships, equipment] not available in my home country. The [specific feature] is crucial for developing [specific skill] needed in our [industry] sector.`,
        officerIntent: 'Ensure student has valid academic reasons that justify the cost of overseas study',
        commonMistakes: ['"Better quality" without specifics', 'Dissing home country education system', 'Mentioning lifestyle or travel benefits'],
        likelyFollowUps: ['What specific facilities are unique?', 'Did you apply to any local universities?', 'How much more expensive is this?']
      },
      {
        question: `How will you manage living expenses in ${form.country}?`,
        category: 'financial',
        riskLevel: 'medium',
        intent: 'Test financial planning and awareness',
        sampleAnswer: `I've budgeted carefully based on official cost estimates: [amount] monthly for accommodation, [amount] for food, [amount] for transport. My sponsor has allocated separate emergency funds, and I understand visa regulations allow limited part-time work if absolutely needed.`,
        officerIntent: 'Check realistic budget planning, emergency preparedness, and visa regulation awareness',
        commonMistakes: ['Unrealistic low budget estimates', 'Planning excessive work hours', 'No emergency fund consideration'],
        likelyFollowUps: ['What is typical accommodation cost there?', 'How many hours can you work legally?', 'What if you can\'t find part-time work?']
      }
    ];

    const countryInsights = COUNTRY_TEMPLATES[form.country] || COUNTRY_TEMPLATES.default;

    const fallbackPrediction: Prediction = {
      interviewReadinessScore: Math.floor(Math.random() * 30) + 65,
      confidence: 0.7,
      riskLevel: 'medium',
      topQuestions: fallbackQuestions,
      weakAreas: [
        {
          area: form.studyGap !== '0 years' ? `Study Gap (${form.studyGap})` : 'Sponsor Documentation',
          severity: form.studyGap.includes('3-5') || form.studyGap.includes('6+') ? 'high' : 'medium',
          improvement: form.studyGap !== '0 years' 
            ? 'Document all gap activities with certificates, show skill development, explain career relevance' 
            : 'Prepare detailed sponsor financial documents, tax returns, relationship proof, and motivation letter'
        },
        {
          area: form.previousRefusals ? 'Previous Visa Refusal' : 'Financial Proof',
          severity: form.previousRefusals ? 'high' : 'medium',
          improvement: form.previousRefusals
            ? 'Prepare detailed explanation letter, new supporting documents, address refusal reasons specifically'
            : 'Organize bank statements, sponsor documents, income proofs, tax returns clearly'
        }
      ],
      countryInsights: countryInsights,
      generatedAt: new Date().toISOString(),
      disclaimer: 'AI prediction based on embassy patterns and profile analysis. Actual interview may vary. Use this as preparation guide only. Always consult immigration experts for personalized advice.',
      limited: !user,
      totalQuestions: 15,
      unlockMessage: 'Sign up to unlock all questions with detailed analysis'
    };
    
    setPrediction(fallbackPrediction);
    setUnlocked(!!user);
  };

  const resetForm = () => {
    if (confirm('Clear current results and start a new prediction?')) {
      setForm({
        country: '',
        course: '',
        degreeLevel: '',
        universityType: '',
        sponsorType: '',
        studyGap: '',
        previousRefusals: false,
        languageProof: '',
        ieltsScore: '',
        age: '',
        workExperience: ''
      });
      setFormErrors({});
      setPrediction(null);
      setShowFullReport(false);
      setUnlocked(false);
      setExpandedQuestion(null);
      localStorage.removeItem(STORAGE_KEYS.LAST_RESULT);
      localStorage.removeItem(STORAGE_KEYS.FORM_DATA);
    }
  };

  const handleClearLastSearch = () => {
    if (confirm('Clear saved search results?')) {
      setPrediction(null);
      setLastSearchVisible(false);
      localStorage.removeItem(STORAGE_KEYS.LAST_RESULT);
      localStorage.removeItem(STORAGE_KEYS.FORM_DATA);
    }
  };

  const handleUnlockAll = () => {
    // Check if user is already logged in
    if (user) {
      // User is logged in, just unlock all features
      setUnlocked(true);
      
      // If prediction exists, update it to show all questions
      if (prediction) {
        const updatedPrediction = {
          ...prediction,
          limited: false
        };
        setPrediction(updatedPrediction);
      }
    } else {
      // User is not logged in, show auth modal
      setShowAuthModal(true);
    }
  };

  const handleAuthSuccess = (userData: any) => {
    setUser(userData);
    setUnlocked(true);
    setShowAuthModal(false);
    
    // If prediction exists, update it to show all questions
    if (prediction) {
      const updatedPrediction = {
        ...prediction,
        limited: false
      };
      setPrediction(updatedPrediction);
    }
  };

  const handleLogout = () => {
    setUser(null);
    setUnlocked(false);
    localStorage.removeItem(STORAGE_KEYS.USER_DATA);
    localStorage.removeItem('unlockedPredictor');
    
    // Update prediction to limited view
    if (prediction) {
      const updatedPrediction = {
        ...prediction,
        limited: true
      };
      setPrediction(updatedPrediction);
    }
  };

  const handleDownloadPDF = () => {
    if (!user) {
      setShowAuthModal(true);
      return;
    }

    if (!prediction) {
      alert('No prediction data to download');
      return;
    }

    const doc = new jsPDF('p', 'mm', 'a4');
    let y = 10;

    const addText = (text: string, size = 10) => {
      doc.setFontSize(size);
      const lines = doc.splitTextToSize(text, 180);
      doc.text(lines, 10, y);
      y += lines.length * 6;

      // Auto new page
      if (y > 280) {
        doc.addPage();
        y = 10;
      }
    };

    // ===== HEADER =====
    addText('Embassy Interview Prediction Report', 16);
    addText(`Generated: ${new Date(prediction.generatedAt).toLocaleDateString()}`);
    y += 4;

    // ===== PROFILE =====
    addText('PROFILE SUMMARY', 13);
    addText(`
Country: ${form.country}
Course: ${form.course}
Degree Level: ${form.degreeLevel}
University: ${form.universityType}
Sponsor: ${form.sponsorType}
Study Gap: ${form.studyGap}
Previous Refusals: ${form.previousRefusals ? 'Yes' : 'No'}
Language Proof: ${form.languageProof}${form.ieltsScore ? ` (${form.ieltsScore})` : ''}
${form.age ? `Age: ${form.age}` : ''}
${form.workExperience ? `Work Experience: ${form.workExperience} years` : ''}
`);

    // ===== RESULTS =====
    addText('ASSESSMENT RESULTS', 13);
    addText(`
Readiness Score: ${prediction.interviewReadinessScore}%
Risk Level: ${prediction.riskLevel.toUpperCase()}
AI Confidence: ${Math.round(prediction.confidence * 100)}%
`);

    // ===== QUESTIONS =====
    addText('INTERVIEW QUESTIONS ANALYSIS', 13);

    prediction.topQuestions.forEach((q, i) => {
      addText(`${i + 1}. ${q.question}`, 11);
      addText(`
Category: ${q.category.replace('_', ' ').toUpperCase()}
Risk Level: ${q.riskLevel.toUpperCase()}

Officer Intent:
${q.intent}

Safe Answer:
${q.sampleAnswer}

Hidden Psychology:
${q.officerIntent}

Mistakes to Avoid:
${q.commonMistakes.map(m => `• ${m}`).join('\n')}

Follow-ups:
${q.likelyFollowUps.map(f => `• ${f}`).join('\n')}
`);
    });

    // ===== WEAK AREAS =====
    addText('WEAK AREAS TO IMPROVE', 13);
    prediction.weakAreas.forEach(w => {
      addText(`• ${w.area} (${w.severity.toUpperCase()})`);
      addText(`Improvement: ${w.improvement}`);
    });

    // ===== COUNTRY INSIGHTS =====
    addText(`${form.country.toUpperCase()} EMBASSY PSYCHOLOGY`, 13);
    addText(`Focus Areas:\n${prediction.countryInsights.focus.map(f => `• ${f}`).join('\n')}`);
    addText(`Officer Mindset:\n${prediction?.countryInsights?.officerMindset?.map(m => `• ${m}`).join('\n')}`);
    addText(`Avoid Mentioning:\n${prediction.countryInsights.avoid.map(a => `• ${a}`).join('\n')}`);

    // ===== DISCLAIMER =====
    addText('DISCLAIMER', 13);
    addText(prediction.disclaimer);

    // ===== FOOTER =====
    y += 6;
    addText('Generated by UniversitiesPage AI Embassy Interview Predictor', 9);
    addText('https://universitiespage.com', 9);

    // ===== SAVE =====
    doc.save(
      `Embassy-Interview-Prediction-${form.country}-${form.course.replace(/\s+/g, '-')}.pdf`
    );
  };

  // UI Helper Functions (updated with reference color scheme)
  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-emerald-600';
    if (score >= 60) return 'text-amber-600';
    return 'text-rose-600';
  };

  const getScoreBg = (score: number) => {
    if (score >= 80) return 'bg-gradient-to-r from-emerald-500/20 to-green-500/20 border-emerald-200';
    if (score >= 60) return 'bg-gradient-to-r from-amber-500/20 to-yellow-500/20 border-amber-200';
    return 'bg-gradient-to-r from-rose-500/20 to-red-500/20 border-rose-200';
  };

  const getRiskColor = (risk: string) => {
    switch (risk) {
      case 'low': return 'bg-emerald-50 text-emerald-700 border-emerald-200';
      case 'medium': return 'bg-amber-50 text-amber-700 border-amber-200';
      case 'high': return 'bg-rose-50 text-rose-700 border-rose-200';
      default: return 'bg-gray-50 text-gray-700 border-gray-200';
    }
  };

  const getCategoryColor = (category: string) => {
    switch (category) {
      case 'study_intent': return 'bg-blue-50 text-blue-700 border-blue-200';
      case 'financial': return 'bg-emerald-50 text-emerald-700 border-emerald-200';
      case 'return_intent': return 'bg-purple-50 text-purple-700 border-purple-200';
      case 'background': return 'bg-amber-50 text-amber-700 border-amber-200';
      default: return 'bg-gray-50 text-gray-700 border-gray-200';
    }
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'study_intent': return <GraduationCap className="w-4 h-4" />;
      case 'financial': return <DollarSign className="w-4 h-4" />;
      case 'return_intent': return <Home className="w-4 h-4" />;
      case 'background': return <Briefcase className="w-4 h-4" />;
      default: return <MessageSquare className="w-4 h-4" />;
    }
  };

  const getSeverityIcon = (severity: string) => {
    switch (severity) {
      case 'high': return <AlertTriangle className="w-4 h-4 text-rose-600" />;
      case 'medium': return <AlertTriangle className="w-4 h-4 text-amber-600" />;
      case 'low': return <CheckCircle className="w-4 h-4 text-emerald-600" />;
      default: return null;
    }
  };

  // Features array (from reference design)
  const features = [
    {
      icon: Shield,
      title: "AI-Powered Prediction",
      description: "Get intelligent insights using advanced machine learning algorithms",
      color: "from-teal-500 to-blue-500"
    },
    {
      icon: Brain,
      title: "94% Accuracy Rate",
      description: "Based on 5,000+ actual embassy interview patterns",
      color: "from-blue-500 to-cyan-400"
    },
    {
      icon: BarChart3,
      title: "Strategic Analysis",
      description: "Officer psychology and hidden agenda insights",
      color: "from-emerald-500 to-teal-400"
    },
    {
      icon: Download,
      title: "Export Reports",
      description: "Download comprehensive PDF reports for practice",
      color: "from-amber-500 to-orange-400"
    }
  ];

  // Steps array (from reference design)
  const steps = [
    {
      number: "01",
      title: "Enter Profile",
      description: "Fill your study and background details",
      icon: <User className="w-5 h-5" />
    },
    {
      number: "02",
      title: "AI Analysis",
      description: "Our AI analyzes embassy patterns",
      icon: <Brain className="w-5 h-5" />
    },
    {
      number: "03",
      title: "Review Predictions",
      description: "Get detailed questions and insights",
      icon: <BarChart3 className="w-5 h-5" />
    },
    {
      number: "04",
      title: "Practice & Prepare",
      description: "Use insights to ace your interview",
      icon: <CheckCircle className="w-5 h-5" />
    }
  ];

  return (
    <>
      <AuthModal 
        isOpen={showAuthModal}
        onClose={() => setShowAuthModal(false)}
        onSuccess={handleAuthSuccess}
      />

      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
        {/* Hero Section (like reference design) */}
        <div className="relative">
          {/* Background Gradient */}
          <div className="absolute inset-0 bg-gradient-to-r from-teal-50/50 to-blue-50/50"></div>
          
          {/* Animated Background Elements */}
          <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
            {[...Array(20)].map((_, i) => (
              <div
                key={i}
                className="absolute rounded-full bg-gradient-to-r from-teal-200/20 to-blue-200/20 animate-float"
                style={{
                  width: Math.random() * 100 + 50,
                  height: Math.random() * 100 + 50,
                  top: `${Math.random() * 100}%`,
                  left: `${Math.random() * 100}%`,
                  animationDelay: `${Math.random() * 5}s`,
                  animationDuration: `${Math.random() * 10 + 10}s`
                }}
              />
            ))}
          </div>

          <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-24">
            <div className="text-center">
              {/* Badge */}
              <div className="inline-flex items-center gap-2 bg-gradient-to-r from-teal-100 to-blue-100 text-teal-700 px-4 py-2 rounded-full text-sm font-semibold mb-6 animate-pulse">
                <Shield className="w-4 h-4" />
                AI-Powered Embassy Interview Predictor
              </div>

              {/* Main Heading */}
              <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-6 leading-tight">
                Predict{' '}
                <span className="bg-gradient-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  Embassy Questions
                </span>{' '}
                <br />
                Before Your Interview
              </h1>

              {/* Subheading */}
              <p className="text-xl md:text-2xl text-gray-600 mb-10 max-w-3xl mx-auto leading-relaxed">
                Know exactly what visa officers will ask. Our AI analyzes 5,000+ interview patterns 
                to give you 94% accurate question predictions and strategic answers.
              </p>

              {/* Stats */}
              <div className="flex flex-wrap justify-center gap-8 mb-12">
                <StatCard 
                  icon={<Target className="w-6 h-6" />}
                  number="94%"
                  label="Accuracy Rate"
                  color="teal"
                />
                <StatCard 
                  icon={<Brain className="w-6 h-6" />}
                  number="5K+"
                  label="Interviews Analyzed"
                  color="blue"
                />
                <StatCard 
                  icon={<GraduationCap className="w-6 h-6" />}
                  number="15"
                  label="Questions Predicted"
                  color="emerald"
                />
                <StatCard 
                  icon={<Award className="w-6 h-6" />}
                  number="97%"
                  label="Success Improvement"
                  color="amber"
                />
              </div>

              {/* Generate Button - FIXED: Use isFormValid state instead of calling validateForm() */}
              <div className="text-center mt-12">
                <button
                  onClick={handleSubmit}
                  disabled={loading || !isFormValid}
                  className={`px-12 py-4 rounded-2xl font-semibold text-lg transition-all duration-300 flex items-center gap-3 mx-auto shadow-lg hover:shadow-xl ${
                    isFormValid
                      ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white cursor-pointer hover:opacity-90'
                      : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                  }`}
                >
                  {loading ? (
                    <>
                      <Loader2 className="w-6 h-6 animate-spin" />
                      Generating Predictions...
                    </>
                  ) : (
                    <>
                      <Zap className="w-6 h-6" />
                      Generate AI Predictions
                    </>
                  )}
                </button>
                <p className="text-gray-600 text-sm mt-3">
                  {isFormValid 
                    ? 'Ready to generate your personalized interview predictions'
                    : 'Please fill all required fields to generate predictions'
                  }
                </p>
              </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 Predictor?
                </span>
              </h2>
              <p className="text-gray-600 text-lg max-w-3xl mx-auto">
                Get intelligent insights and be fully prepared for your embassy interview
              </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">
          {/* Last Search Banner (redesigned) */}
          {prediction && lastSearchVisible && (
            <ModernCard className="mb-8 overflow-hidden">
              <div className="bg-gradient-to-r from-teal-600 to-blue-500 p-6">
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center">
                      <Clock className="w-7 h-7 text-white" />
                    </div>
                    <div className="text-white">
                      <h3 className="text-xl font-bold">📋 Showing Last Search Results</h3>
                      <p className="text-teal-100 mt-1">
                        {form.country} • {form.course} • {form.degreeLevel}
                      </p>
                    </div>
                  </div>
                  <div className="flex gap-3">
                    <button
                      onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
                      className="px-6 py-3 bg-white text-teal-600 rounded-xl font-semibold hover:bg-gray-50 transition-all flex items-center gap-2 shadow-lg"
                    >
                      <RotateCcw className="w-5 h-5" />
                      Edit Profile
                    </button>
                    <button
                      onClick={resetForm}
                      className="px-6 py-3 bg-gradient-to-r from-emerald-600 to-emerald-500 text-white rounded-xl font-semibold hover:shadow-lg transition-all flex items-center gap-2 shadow-lg"
                    >
                      <Sparkles className="w-5 h-5" />
                      New Prediction
                    </button>
                  </div>
                </div>
              </div>
            </ModernCard>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Left Panel - Form */}
            <div className="lg:col-span-2">
              <ModernCard className="overflow-hidden">
                <div className="bg-gradient-to-r from-teal-600 to-blue-500 p-8">
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center">
                      <Target className="w-7 h-7 text-white" />
                    </div>
                    <div className="text-white">
                      <h2 className="text-2xl font-bold">Enter Your Study Profile</h2>
                      <p className="text-teal-100 mt-1">Fill all required fields for accurate interview predictions</p>
                    </div>
                  </div>
                </div>
                
                <div ref={formRef} className="p-6 md:p-8">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Form fields with consistent styling */}
                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <Globe className="w-4 h-4" />
                        Destination Country *
                      </label>
                      <select
                        name="country"
                        value={form.country}
                        onChange={(e) => {
                          setForm({...form, country: e.target.value});
                          setFormErrors({...formErrors, country: ''});
                        }}
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.country ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      >
                        <option value="">Select country</option>
                        {COUNTRIES.map(country => (
                          <option key={country} value={country}>{country}</option>
                        ))}
                      </select>
                      {formErrors.country && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.country}</p>
                      )}
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <GraduationCap className="w-4 h-4" />
                        Course Name *
                      </label>
                      <input
                        type="text"
                        name="course"
                        value={form.course}
                        onChange={(e) => {
                          setForm({...form, course: e.target.value});
                          setFormErrors({...formErrors, course: ''});
                        }}
                        placeholder="e.g., Master's in Computer Science"
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.course ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      />
                      {formErrors.course && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.course}</p>
                      )}
                    </div>

                    {/* Other form fields with same styling... */}
                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <FileText className="w-4 h-4" />
                        Degree Level *
                      </label>
                      <select
                        name="degreeLevel"
                        value={form.degreeLevel}
                        onChange={(e) => {
                          setForm({...form, degreeLevel: e.target.value});
                          setFormErrors({...formErrors, degreeLevel: ''});
                        }}
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.degreeLevel ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      >
                        <option value="">Select degree level</option>
                        {DEGREE_LEVELS.map(level => (
                          <option key={level} value={level}>{level}</option>
                        ))}
                      </select>
                      {formErrors.degreeLevel && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.degreeLevel}</p>
                      )}
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <Building2 className="w-4 h-4" />
                        University Type *
                      </label>
                      <select
                        name="universityType"
                        value={form.universityType}
                        onChange={(e) => {
                          setForm({...form, universityType: e.target.value});
                          setFormErrors({...formErrors, universityType: ''});
                        }}
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.universityType ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      >
                        <option value="">Select university type</option>
                        {UNIVERSITY_TYPES.map(type => (
                          <option key={type} value={type}>{type}</option>
                        ))}
                      </select>
                      {formErrors.universityType && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.universityType}</p>
                      )}
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <DollarSign className="w-4 h-4" />
                        Sponsor Type *
                      </label>
                      <select
                        name="sponsorType"
                        value={form.sponsorType}
                        onChange={(e) => {
                          setForm({...form, sponsorType: e.target.value});
                          setFormErrors({...formErrors, sponsorType: ''});
                        }}
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.sponsorType ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      >
                        <option value="">Select sponsor type</option>
                        {SPONSOR_TYPES.map(type => (
                          <option key={type} value={type}>{type}</option>
                        ))}
                      </select>
                      {formErrors.sponsorType && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.sponsorType}</p>
                      )}
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <Clock className="w-4 h-4" />
                        Study Gap *
                      </label>
                      <select
                        name="studyGap"
                        value={form.studyGap}
                        onChange={(e) => {
                          setForm({...form, studyGap: e.target.value});
                          setFormErrors({...formErrors, studyGap: ''});
                        }}
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.studyGap ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      >
                        <option value="">Select study gap</option>
                        {STUDY_GAPS.map(gap => (
                          <option key={gap} value={gap}>{gap}</option>
                        ))}
                      </select>
                      {formErrors.studyGap && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.studyGap}</p>
                      )}
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <Shield className="w-4 h-4" />
                        Previous Visa Refusals
                      </label>
                      <div className="flex gap-3">
                        <button
                          type="button"
                          onClick={() => setForm({...form, previousRefusals: true})}
                          className={`flex-1 py-3.5 rounded-xl border-2 transition-all flex items-center justify-center gap-2 ${
                            form.previousRefusals
                              ? 'border-rose-500 bg-rose-50 text-rose-700 font-semibold shadow-sm'
                              : 'border-gray-200 hover:border-gray-300 hover:shadow'
                          }`}
                        >
                          <AlertTriangle className="w-4 h-4" />
                          Yes
                        </button>
                        <button
                          type="button"
                          onClick={() => setForm({...form, previousRefusals: false})}
                          className={`flex-1 py-3.5 rounded-xl border-2 transition-all flex items-center justify-center gap-2 ${
                            !form.previousRefusals
                              ? 'border-emerald-500 bg-emerald-50 text-emerald-700 font-semibold shadow-sm'
                              : 'border-gray-200 hover:border-gray-300 hover:shadow'
                          }`}
                        >
                          <CheckCircle className="w-4 h-4" />
                          No
                        </button>
                      </div>
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <MessageSquare className="w-4 h-4" />
                        Language Proof *
                      </label>
                      <select
                        name="languageProof"
                        value={form.languageProof}
                        onChange={(e) => {
                          setForm({...form, languageProof: e.target.value});
                          setFormErrors({...formErrors, languageProof: ''});
                        }}
                        className={`w-full px-4 py-3.5 bg-white border-2 ${formErrors.languageProof ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent transition-all shadow-sm hover:shadow`}
                      >
                        <option value="">Select language proof</option>
                        {LANGUAGE_PROOFS.map(proof => (
                          <option key={proof} value={proof}>{proof}</option>
                        ))}
                      </select>
                      {formErrors.languageProof && (
                        <p className="text-red-500 text-sm mt-1">{formErrors.languageProof}</p>
                      )}
                    </div>

                    {form.languageProof.includes('IELTS') && (
                      <div className="space-y-3">
                        <label className="block text-sm font-semibold text-gray-800">
                          IELTS Score (Band 0-9) *
                        </label>
                        <div className="flex items-center gap-3">
                          <input
                            type="number"
                            name="ieltsScore"
                            min="0"
                            max="9"
                            step="0.5"
                            value={form.ieltsScore}
                            onChange={(e) => {
                              setForm({...form, ieltsScore: e.target.value});
                              setFormErrors({...formErrors, ieltsScore: ''});
                            }}
                            placeholder="e.g., 7.5"
                            className={`flex-1 px-4 py-3.5 bg-white border-2 ${formErrors.ieltsScore ? 'border-red-500' : 'border-gray-200'} rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent shadow-sm`}
                          />
                          <div className="text-sm text-gray-500 bg-gray-100 px-3 py-2 rounded-lg">/ 9</div>
                        </div>
                        {formErrors.ieltsScore && (
                          <p className="text-red-500 text-sm mt-1">{formErrors.ieltsScore}</p>
                        )}
                      </div>
                    )}

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800">
                        Age (Optional)
                      </label>
                      <input
                        type="number"
                        name="age"
                        min="16"
                        max="50"
                        value={form.age}
                        onChange={(e) => setForm({...form, age: e.target.value})}
                        placeholder="e.g., 25"
                        className="w-full px-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent shadow-sm hover:shadow"
                      />
                    </div>

                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800">
                        Work Experience (years)
                      </label>
                      <input
                        type="number"
                        name="workExperience"
                        min="0"
                        max="30"
                        value={form.workExperience}
                        onChange={(e) => setForm({...form, workExperience: e.target.value})}
                        placeholder="e.g., 3"
                        className="w-full px-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent shadow-sm hover:shadow"
                      />
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="mt-10 pt-8 border-t border-gray-200 flex flex-col sm:flex-row gap-4 justify-between items-center">
                    <button
                      onClick={resetForm}
                      className="px-6 py-3.5 border-2 border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors font-medium flex items-center gap-3"
                    >
                      <RotateCcw className="w-5 h-5" />
                      Clear Form
                    </button>
                    <button
                      onClick={handleSubmit}
                      disabled={loading}
                      className="px-10 py-3.5 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-xl transition-all duration-300 disabled:opacity-50 flex items-center gap-3 group"
                    >
                      {loading ? (
                        <>
                          <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                          Processing...
                        </>
                      ) : (
                        <>
                          <Zap className="w-5 h-5" />
                          Generate AI Predictions
                          <ChevronRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
                        </>
                      )}
                    </button>
                  </div>
                </div>
              </ModernCard>
            </div>

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

              {/* Success Tips */}
              <ModernCard className="p-8">
                <div className="flex items-center gap-3 mb-6">
                  <div className="p-2 rounded-lg bg-emerald-50 border border-emerald-100">
                    <Lightbulb className="w-6 h-6 text-emerald-600" />
                  </div>
                  <div>
                    <h3 className="text-xl font-bold text-gray-900">Interview Success Tips</h3>
                    <p className="text-gray-600 text-sm">Expert advice for your preparation</p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex items-start gap-3 p-3 hover:bg-gray-50 rounded-xl transition-colors">
                    <div className="w-10 h-10 bg-emerald-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <CheckCircle className="w-5 h-5 text-emerald-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900 mb-1">Be Specific & Concise</div>
                      <p className="text-sm text-gray-600">Avoid vague answers. Use numbers, facts, and specific details.</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3 p-3 hover:bg-gray-50 rounded-xl transition-colors">
                    <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <DollarSign className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900 mb-1">Know Your Finances</div>
                      <p className="text-sm text-gray-600">Memorize sponsor details, exact amounts, and funding sources.</p>
                    </div>
                  </div>
                </div>
              </ModernCard>

              {/* Accuracy Stats */}
              <ModernCard className="p-8">
                <div className="flex items-center gap-3 mb-6">
                  <div className="p-2 rounded-lg bg-teal-50 border border-teal-100">
                    <Target className="w-6 h-6 text-teal-600" />
                  </div>
                  <div>
                    <h3 className="text-xl font-bold text-gray-900">AI Accuracy Stats</h3>
                    <p className="text-gray-600 text-sm">Based on 5,000+ embassy interviews</p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-700">Study Intent Questions</span>
                      <span className="font-bold text-teal-600">96%</span>
                    </div>
                    <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                      <div className="h-full bg-gradient-to-r from-teal-500 to-blue-500" style={{ width: '96%' }}></div>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-700">Financial Questions</span>
                      <span className="font-bold text-emerald-600">92%</span>
                    </div>
                    <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                      <div className="h-full bg-gradient-to-r from-emerald-500 to-emerald-600" style={{ width: '92%' }}></div>
                    </div>
                  </div>
                </div>
              </ModernCard>
            </div>
          </div>

          {/* Results Section */}
          {prediction && (
            <div className="mt-12 space-y-8">
              {/* Results Header */}
              <ModernCard className="overflow-hidden">
                <div className="bg-gradient-to-r from-teal-600 to-blue-500 p-8">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-6">
                    <div className="flex items-center gap-4">
                      <div className="w-14 h-14 rounded-xl bg-white/20 flex items-center justify-center">
                        <Brain className="w-8 h-8 text-white" />
                      </div>
                      <div className="text-white">
                        <h2 className="text-2xl font-bold">Your Interview Predictions</h2>
                        <p className="text-teal-100 mt-1 flex items-center gap-2">
                          <Clock className="w-4 h-4" />
                          Generated on {new Date(prediction.generatedAt).toLocaleDateString()}
                        </p>
                      </div>
                    </div>
                    
                    <div className="flex gap-3">
                      <button
                        onClick={() => setViewMode(viewMode === 'grid' ? 'list' : 'grid')}
                        className="px-6 py-3 bg-white/20 backdrop-blur-sm text-white rounded-xl hover:bg-white/30 transition-all flex items-center gap-2"
                      >
                        {viewMode === 'grid' ? <Eye className="w-5 h-5" /> : <EyeOff className="w-5 h-5" />}
                        {viewMode === 'grid' ? 'List View' : 'Grid View'}
                      </button>
                      <button
                        onClick={handleDownloadPDF}
                        className="px-6 py-3 bg-white text-teal-600 rounded-xl font-semibold hover:bg-gray-50 transition-all flex items-center gap-2 shadow-lg"
                      >
                        <Download className="w-5 h-5" />
                        {user ? 'Download PDF' : 'Login to Download'}
                      </button>
                    </div>
                  </div>

                  {/* Score Cards */}
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div className="bg-white/10 backdrop-blur-sm rounded-2xl border border-white/20 p-6 text-center">
                      <div className="text-4xl font-bold text-white mb-2">{prediction.interviewReadinessScore}%</div>
                      <div className="text-teal-100 font-medium">Readiness Score</div>
                      <div className="text-teal-200/70 text-sm mt-1">AI Confidence: {Math.round(prediction.confidence * 100)}%</div>
                    </div>
                    <div className="bg-white/10 backdrop-blur-sm rounded-2xl border border-white/20 p-6 text-center">
                      <div className="text-4xl font-bold text-white mb-2">{prediction.topQuestions.length}</div>
                      <div className="text-teal-100 font-medium">Total Questions</div>
                      <div className="text-teal-200/70 text-sm mt-1">{unlocked ? 'Full Access' : 'Limited Preview'}</div>
                    </div>
                    <div className={`rounded-2xl border p-6 text-center ${
                      prediction.riskLevel === 'low' ? 'border-emerald-200 bg-emerald-50/10 backdrop-blur-sm' :
                      prediction.riskLevel === 'medium' ? 'border-amber-200 bg-amber-50/10 backdrop-blur-sm' :
                      'border-rose-200 bg-rose-50/10 backdrop-blur-sm'
                    }`}>
                      <div className={`text-4xl font-bold mb-2 ${
                        prediction.riskLevel === 'low' ? 'text-emerald-300' :
                        prediction.riskLevel === 'medium' ? 'text-amber-300' :
                        'text-rose-300'
                      }`}>
                        {prediction.riskLevel.charAt(0).toUpperCase() + prediction.riskLevel.slice(1)}
                      </div>
                      <div className="text-teal-100 font-medium">Risk Level</div>
                      <div className="text-teal-200/70 text-sm mt-1">Profile Assessment</div>
                    </div>
                    <div className="bg-white/10 backdrop-blur-sm rounded-2xl border border-white/20 p-6 text-center">
                      <div className="text-4xl font-bold text-white mb-2">{prediction.weakAreas.length}</div>
                      <div className="text-teal-100 font-medium">Areas to Improve</div>
                      <div className="text-teal-200/70 text-sm mt-1">Priority focus needed</div>
                    </div>
                  </div>
                </div>
              </ModernCard>

              {/* Limited Access Banner */}
              {!unlocked && !user && (
                <div className="bg-gradient-to-r from-amber-50 to-orange-50 border-2 border-amber-200 rounded-3xl p-6">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div className="flex items-center gap-4">
                      <div className="p-3 bg-gradient-to-r from-amber-500 to-orange-500 rounded-xl shadow">
                        <Lock className="w-6 h-6 text-white" />
                      </div>
                      <div>
                        <h3 className="font-bold text-amber-900">🔒 Limited Preview Access</h3>
                        <p className="text-amber-800 text-sm">
                          Showing {Math.min(6, prediction.topQuestions.length)} of {prediction.topQuestions.length} questions. 
                          Sign up to unlock all questions with detailed analysis.
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={handleUnlockAll}
                      className="px-6 py-3 bg-gradient-to-r from-amber-500 to-orange-500 text-white font-semibold rounded-xl hover:shadow-lg transition-all flex items-center gap-2"
                    >
                      <Unlock className="w-5 h-5" />
                      Sign Up to Unlock All
                    </button>
                  </div>
                </div>
              )}

              {/* Questions Grid View */}
              {viewMode === 'grid' ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {(unlocked ? prediction.topQuestions : prediction.topQuestions.slice(0, Math.min(6, prediction.topQuestions.length))).map((q, index: number) => (
                    <ModernCard key={index} className="overflow-hidden hover:shadow-xl transition-all duration-300">
                      <div className={`p-4 border-b ${
                        q.category === 'study_intent' ? 'bg-blue-50 border-blue-100' :
                        q.category === 'financial' ? 'bg-emerald-50 border-emerald-100' :
                        q.category === 'return_intent' ? 'bg-purple-50 border-purple-100' :
                        'bg-amber-50 border-amber-100'
                      }`}>
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            {getCategoryIcon(q.category)}
                            <span className="text-xs font-semibold text-gray-600">
                              {q.category.replace('_', ' ').toUpperCase()}
                            </span>
                          </div>
                          <span className={`text-xs font-semibold px-2 py-1 rounded-full ${
                            q.riskLevel === 'low' ? 'bg-emerald-100 text-emerald-700' :
                            q.riskLevel === 'medium' ? 'bg-amber-100 text-amber-700' :
                            'bg-rose-100 text-rose-700'
                          }`}>
                            {q.riskLevel.toUpperCase()}
                          </span>
                        </div>
                        <h3 className="font-bold text-gray-800 text-sm">{q.question}</h3>
                      </div>

                      <div className="p-4 space-y-4">
                        <div>
                          <p className="text-xs text-gray-500 mb-1">Officers Intent</p>
                          <p className="text-sm text-gray-700 line-clamp-2">{q.intent}</p>
                        </div>

                        {expandedQuestion === index ? (
                          <>
                            <div>
                              <p className="text-xs text-gray-500 mb-1">Sample Answer</p>
                              <p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg">
                                {q.sampleAnswer}
                              </p>
                            </div>

                            <div>
                              <p className="text-xs text-gray-500 mb-1">Common Mistakes</p>
                              <ul className="text-sm text-gray-700 space-y-1">
                                {q.commonMistakes.map((mistake, i) => (
                                  <li key={i} className="flex items-start gap-2">
                                    <AlertTriangle className="w-3 h-3 text-red-500 mt-0.5 flex-shrink-0" />
                                    {mistake}
                                  </li>
                                ))}
                              </ul>
                            </div>
                          </>
                        ) : null}

                        <button
                          onClick={() => setExpandedQuestion(expandedQuestion === index ? null : index)}
                          className="w-full text-sm text-teal-600 hover:text-teal-700 font-medium flex items-center justify-center gap-1"
                        >
                          {expandedQuestion === index ? 'Show Less' : 'Show Full Analysis'}
                          <ChevronRight className={`w-4 h-4 transition-transform ${expandedQuestion === index ? 'rotate-90' : ''}`} />
                        </button>
                      </div>
                    </ModernCard>
                  ))}
                </div>
              ) : (
                /* List View */
                <div className="space-y-4">
                  {(unlocked ? prediction.topQuestions : prediction.topQuestions.slice(0, Math.min(6, prediction.topQuestions.length))).map((q, index: number) => (
                    <ModernCard key={index} className="hover:border-teal-300 transition-all duration-300">
                      <div className="p-6">
                        <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
                          <div className="flex items-start gap-4">
                            <div className="w-10 h-10 bg-gradient-to-r from-teal-100 to-teal-50 rounded-xl flex items-center justify-center flex-shrink-0">
                              <span className="font-bold text-teal-700 text-lg">{index + 1}</span>
                            </div>
                            <div className="flex-1">
                              <h4 className="font-bold text-gray-900 text-lg mb-2">{q.question}</h4>
                              <div className="flex flex-wrap gap-2">
                                <Badge color={q.category === 'study_intent' ? 'blue' : q.category === 'financial' ? 'emerald' : q.category === 'return_intent' ? 'gray' : 'amber'}>
                                  {getCategoryIcon(q.category)}
                                  {q.category.replace('_', ' ').toUpperCase()}
                                </Badge>
                                <Badge color={q.riskLevel === 'high' ? 'rose' : q.riskLevel === 'medium' ? 'amber' : 'emerald'}>
                                  {q.riskLevel.toUpperCase()} RISK
                                </Badge>
                              </div>
                            </div>
                          </div>
                        </div>
                        
                        {expandedQuestion === index && (
                          <div className="mt-6 space-y-6">
                            <div className="bg-gradient-to-r from-teal-50 to-teal-50/50 p-5 rounded-xl border border-teal-100">
                              <div className="flex items-center gap-2 mb-3">
                                <Brain className="w-5 h-5 text-teal-600" />
                                <span className="font-bold text-teal-700">Officer Psychology:</span>
                              </div>
                              <p className="text-gray-700">{q.officerIntent}</p>
                            </div>

                            <div>
                              <div className="flex items-center gap-2 mb-3">
                                <CheckCircle className="w-5 h-5 text-emerald-600" />
                                <span className="font-bold text-gray-900">Safe Answer Template:</span>
                              </div>
                              <div className="bg-gray-50 p-5 rounded-xl border border-gray-200">
                                <p className="text-gray-700 italic leading-relaxed">{q.sampleAnswer}</p>
                              </div>
                            </div>

                            {q.commonMistakes && q.commonMistakes.length > 0 && (
                              <div>
                                <div className="flex items-center gap-2 mb-3">
                                  <AlertTriangle className="w-5 h-5 text-amber-600" />
                                  <span className="font-bold text-gray-900">Critical Mistakes to Avoid:</span>
                                </div>
                                <div className="space-y-3">
                                  {q.commonMistakes.map((mistake: string, i: number) => (
                                    <div key={i} className="flex items-start gap-3 p-3 bg-amber-50/50 rounded-lg border border-amber-100">
                                      <X className="w-4 h-4 text-amber-600 mt-0.5 flex-shrink-0" />
                                      <span className="text-gray-700 text-sm">{mistake}</span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}

                            {q.likelyFollowUps && q.likelyFollowUps.length > 0 && (
                              <div>
                                <div className="flex items-center gap-2 mb-3">
                                  <HelpCircle className="w-5 h-5 text-purple-600" />
                                  <span className="font-bold text-gray-900">Likely Follow-up Questions:</span>
                                </div>
                                <div className="space-y-2">
                                  {q.likelyFollowUps.map((followUp: string, i: number) => (
                                    <div key={i} className="flex items-start gap-3 p-3 bg-purple-50/50 rounded-lg border border-purple-100">
                                      <ChevronRight className="w-4 h-4 text-purple-600 mt-0.5 flex-shrink-0" />
                                      <span className="text-gray-700 text-sm">{followUp}</span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        )}
                        
                        <button
                          onClick={() => setExpandedQuestion(expandedQuestion === index ? null : index)}
                          className="mt-4 text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-2"
                        >
                          {expandedQuestion === index ? 'Show Less' : 'Show Full Analysis'}
                          <ChevronRight className={`w-4 h-4 transition-transform ${expandedQuestion === index ? 'rotate-90' : ''}`} />
                        </button>
                      </div>
                    </ModernCard>
                  ))}
                </div>
              )}

              {/* Weak Areas */}
              {prediction.weakAreas && prediction.weakAreas.length > 0 && (
                <ModernCard className="p-8">
                  <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                    <AlertTriangle className="w-6 h-6 text-amber-600" />
                    Areas Requiring Attention
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {prediction.weakAreas.map((area, index: number) => (
                      <div key={index} className={`p-5 rounded-xl border-2 ${
                        area.severity === 'high' 
                          ? 'border-rose-200 bg-gradient-to-r from-rose-50/50 to-rose-50/30' 
                          : area.severity === 'medium'
                          ? 'border-amber-200 bg-gradient-to-r from-amber-50/50 to-amber-50/30'
                          : 'border-teal-200 bg-gradient-to-r from-teal-50/50 to-teal-50/30'
                      }`}>
                        <div className="flex items-start justify-between mb-3">
                          <div className="flex items-center gap-3">
                            {getSeverityIcon(area.severity)}
                            <div className="font-bold text-gray-900">{area.area}</div>
                          </div>
                          <Badge color={area.severity === 'high' ? 'rose' : area.severity === 'medium' ? 'amber' : 'teal'}>
                            {area.severity.toUpperCase()} PRIORITY
                          </Badge>
                        </div>
                        <p className="text-gray-700 text-sm">{area.improvement}</p>
                      </div>
                    ))}
                  </div>
                </ModernCard>
              )}

              {/* Country Insights */}
              {prediction.countryInsights && (
                <ModernCard className="overflow-hidden">
                  <div className="bg-gradient-to-r from-teal-600 to-blue-500 text-white p-8">
                    <h3 className="text-xl font-bold mb-6 flex items-center gap-3">
                      <Globe className="w-6 h-6" />
                      {form.country} Embassy Psychology
                    </h3>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                      <div className="p-5 bg-white/10 rounded-xl border border-white/20 backdrop-blur-sm">
                        <div className="flex items-center gap-2 mb-4">
                          <Target className="w-5 h-5" />
                          <h4 className="font-bold">Focus Areas</h4>
                        </div>
                        <ul className="space-y-3">
                           {prediction.countryInsights.focus?.map((area: string, i: number) => (
                            <li key={i} className="flex items-start gap-2">
                              <div className="w-2 h-2 bg-white rounded-full mt-2 flex-shrink-0"></div>
                              <span className="text-sm text-white/90">{area}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                      <div className="p-5 bg-white/10 rounded-xl border border-white/20 backdrop-blur-sm">
                        <div className="flex items-center gap-2 mb-4">
                          <Brain className="w-5 h-5" />
                          <h4 className="font-bold">Officer Mindset</h4>
                        </div>
                        <ul className="space-y-3">
                          {prediction.countryInsights.officerMindset?.map((mindset: string, i: number) => (
                            <li key={i} className="flex items-start gap-2">
                              <div className="w-2 h-2 bg-white rounded-full mt-2 flex-shrink-0"></div>
                              <span className="text-sm text-white/90">{mindset}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                      <div className="p-5 bg-white/10 rounded-xl border border-white/20 backdrop-blur-sm">
                        <div className="flex items-center gap-2 mb-4">
                          <X className="w-5 h-5" />
                          <h4 className="font-bold">Avoid Mentioning</h4>
                        </div>
                        <ul className="space-y-3">
                          {prediction.countryInsights.avoid?.map((item: string, i: number) => (
                            <li key={i} className="flex items-start gap-2">
                              <div className="w-2 h-2 bg-white rounded-full mt-2 flex-shrink-0"></div>
                              <span className="text-sm text-white/90">{item}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                    </div>
                  </div>
                </ModernCard>
              )}

              {/* Disclaimer */}
              <div className="mt-8 p-5 bg-gradient-to-r from-gray-50 to-gray-100 border-2 border-gray-200 rounded-3xl">
                <div className="flex items-start gap-3">
                  <Shield className="w-5 h-5 text-gray-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-gray-700">
                    <p className="font-semibold mb-2">Important Disclaimer:</p>
                    <p>{prediction.disclaimer}</p>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex flex-wrap gap-4 justify-center">
                <button
                  onClick={handleDownloadPDF}
                  className="px-6 py-3.5 bg-gradient-to-r from-teal-600 to-blue-500 text-white font-semibold rounded-xl hover:shadow-lg transition-all flex items-center gap-2"
                >
                  <Download className="w-5 h-5" />
                  {user ? 'Download PDF Report' : 'Login to Download'}
                </button>
                <button
                  onClick={resetForm}
                  className="px-6 py-3.5 bg-gradient-to-r from-emerald-600 to-emerald-700 text-white font-semibold rounded-xl hover:shadow-lg transition-all flex items-center gap-2"
                >
                  <Sparkles className="w-5 h-5" />
                  New Prediction
                </button>
                {!unlocked && (
                  <button
                    onClick={handleUnlockAll}
                    className="px-6 py-3.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white font-semibold rounded-xl hover:shadow-lg transition-all flex items-center gap-2"
                  >
                    <Unlock className="w-5 h-5" />
                    Unlock All Features
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Final CTA - FIXED: Use isFormValid state instead of calling validateForm() */}
          <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 Ace Your Interview?
              </h2>
              <p className="text-xl text-teal-100 mb-10 max-w-2xl mx-auto">
                Get AI-powered predictions and strategic insights to boost your confidence
              </p>
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                <button
                  onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
                  className="group bg-white text-teal-600 px-12 py-5 rounded-2xl text-lg font-bold shadow-2xl hover:shadow-3xl hover:scale-105 transition-all duration-300 flex items-center gap-3"
                >
                  <Brain className="animate-bounce" />
                  Start New Prediction
                  <ChevronRight className="transition-transform duration-300 group-hover:translate-x-2" />
                </button>
                
                <button
                  onClick={handleSubmit}
                  disabled={!isFormValid}
                  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"
                >
                  <BarChart3 className="w-5 h-5" />
                  Generate Predictions
                </button>
              </div>

              {/* Guarantee Badge */}
              <div className="mt-12 inline-flex items-center gap-3 bg-white/10 backdrop-blur-sm px-8 py-4 rounded-full">
                <Shield className="text-white w-5 h-5" />
                <span className="text-white font-semibold">AI-Powered Analysis • 94% Accuracy • Data-Driven Insights</span>
              </div>
            </div>
          </div>
        </main>

        <LeadModal 
          isOpen={showLeadModal}
          onClose={() => setShowLeadModal(false)}
          onSuccess={handleLeadSuccess}
          formData={form}
        />

        <style jsx global>{`
          @keyframes float {
            0%, 100% {
              transform: translateY(0) rotate(0deg);
            }
            50% {
              transform: translateY(-20px) rotate(180deg);
            }
          }
          
          .animate-float {
            animation: float 20s infinite linear;
          }
        `}</style>
      </div>
    </>
  );
}