'use client';

import { useState, useEffect } from 'react';
import { useUserStore } from '../../store/useUserStore';
import { 
  X, 
  User, 
  GraduationCap, 
  CheckCircle,
  Mail,
  Lock,
  Eye,
  EyeOff,
  Globe,
  Phone,
  MapPin,
  Loader2,
  AlertCircle,
  Check
} from 'lucide-react';

interface AuthModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (userData: any) => void;
}

interface Country {
  id: number;
  name: string;
}

interface State {
  id: number;
  name: string;
}

interface City {
  id: number;
  name: string;
}

const AuthModal = ({ isOpen, onClose, onSuccess }: AuthModalProps) => {
  const [activeTab, setActiveTab] = useState<'login' | 'register'>('login');
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [agreeTerms, setAgreeTerms] = useState(false);
  const [registrationSuccess, setRegistrationSuccess] = useState(false);

  const [formErrors, setFormErrors] = useState<Record<string, string[]>>({});
  const [loginForm, setLoginForm] = useState({ email: '', password: '' });
  const [studentRegForm, setStudentRegForm] = useState({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    password: '',
    confirm_password: '',
    nationality: '',
    state: '',
    city: '',
    program_type: '',
    gender: ''
  });

  const [countries, setCountries] = useState<Country[]>([]);
  const [states, setStates] = useState<State[]>([]);
  const [cities, setCities] = useState<City[]>([]);
  const [loadingCountries, setLoadingCountries] = useState(false);
  const [loadingStates, setLoadingStates] = useState(false);
  const [loadingCities, setLoadingCities] = useState(false);

  // Clear errors when switching tabs
  useEffect(() => {
    setFormErrors({});
    setRegistrationSuccess(false);
  }, [activeTab]);

  // Reset forms when modal closes
  useEffect(() => {
    if (!isOpen) {
      resetForms();
    }
  }, [isOpen]);

  const resetForms = () => {
    setLoginForm({ email: '', password: '' });
    setStudentRegForm({
      first_name: '',
      last_name: '',
      email: '',
      phone: '',
      password: '',
      confirm_password: '',
      nationality: '',
      state: '',
      city: '',
      program_type: '',
      gender: ''
    });
    setCountries([]);
    setStates([]);
    setCities([]);
    setAgreeTerms(false);
    setFormErrors({});
    setRegistrationSuccess(false);
  };

  useEffect(() => {
    if (isOpen) {
      fetchCountries();
    }
  }, [isOpen]);

  // Fetch countries from your API
  const fetchCountries = async () => {
    setLoadingCountries(true);
    try {
      const response = await fetch('/api/frontend/countries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      });
      
      const data = await response.json();
      
      if (data.countries && Array.isArray(data.countries)) {
        setCountries(data.countries);
      } else if (Array.isArray(data)) {
        setCountries(data);
      }
    } catch (error) {
      console.error('Error fetching countries:', error);
    } finally {
      setLoadingCountries(false);
    }
  };

  // Fetch states
  const fetchStates = async (countryId: string) => {
    setLoadingStates(true);
    try {
      const numericCountryId = parseInt(countryId);
      if (isNaN(numericCountryId)) {
        setStates([]);
        return;
      }

      const response = await fetch(`/api/frontend/states?countryId=${numericCountryId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      });
      
      const data = await response.json();
      
      if (data.states && Array.isArray(data.states)) {
        setStates(data.states);
      } else if (Array.isArray(data)) {
        setStates(data);
      } else {
        setStates([]);
      }
      
      setCities([]);
      setStudentRegForm(prev => ({ ...prev, state: '', city: '' }));
    } catch (error) {
      console.error('Error fetching states:', error);
      setStates([]);
    } finally {
      setLoadingStates(false);
    }
  };

  // Fetch cities
  const fetchCities = async (stateId: string) => {
    setLoadingCities(true);
    try {
      const numericStateId = parseInt(stateId);
      if (isNaN(numericStateId)) {
        setCities([]);
        return;
      }

      const response = await fetch(`/api/frontend/cities?stateId=${numericStateId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      });
      
      const data = await response.json();
      
      if (data.cities && Array.isArray(data.cities)) {
        setCities(data.cities);
      } else if (Array.isArray(data)) {
        setCities(data);
      } else {
        setCities([]);
      }
      
      setStudentRegForm(prev => ({ ...prev, city: '' }));
    } catch (error) {
      console.error('Error fetching cities:', error);
      setCities([]);
    } finally {
      setLoadingCities(false);
    }
  };

  const handleCountryChange = (countryId: string) => {
    setStudentRegForm({
      ...studentRegForm,
      nationality: countryId,
      state: '',
      city: ''
    });
    
    setStates([]);
    setCities([]);
    
    if (countryId) {
      fetchStates(countryId);
    }
  };

  const handleStateChange = (stateId: string) => {
    setStudentRegForm({
      ...studentRegForm,
      state: stateId,
      city: ''
    });
    
    setCities([]);
    
    if (stateId) {
      fetchCities(stateId);
    }
  };

  const handleCityChange = (cityId: string) => {
    setStudentRegForm({
      ...studentRegForm,
      city: cityId
    });
  };

  // Display form errors
  const displayErrors = (field: string) => {
    if (formErrors[field]) {
      return (
        <div className="mt-2 flex items-center gap-2 text-sm text-red-600">
          <AlertCircle className="w-4 h-4" />
          {formErrors[field][0]}
        </div>
      );
    }
    return null;
  };

  const { user, isLoggedIn, setUser } = useUserStore();

// In AuthModal's handleLogin function, update the success handler:

const handleLogin = async (e: React.FormEvent) => {
  e.preventDefault();
  setLoading(true);
  setFormErrors({});

  try {
    const response = await fetch('/api/frontend/login/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(loginForm),
      credentials: 'include' // Important for cookies
    });

    const data = await response.json();

    if (!response.ok) {
      if (data.message) {
        if (typeof data.message === 'object') {
          setFormErrors(data.message);
        } else {
          setFormErrors({ general: [data.message] });
        }
      } else if (data.ok === false) {
        setFormErrors({ general: [data.message || 'Login failed'] });
      } else {
        setFormErrors({ general: ['Invalid credentials'] });
      }
      return;
    }

    // SUCCESS: Login worked!
    const userData = {
      id: data.data.id,
      name: data.data.name,
      email: data.data.email,
      role: data.data.role || data.role
    };

    // Update Zustand store FIRST
    setUser(userData);
    
    // Dispatch event for other components
    window.dispatchEvent(new CustomEvent('authSuccess', { 
      detail: { 
        user: userData,
        message: data.message 
      } 
    }));
    
    // Call the onSuccess callback
    onSuccess(userData);
    
    // Close modal
    onClose();
    
    // Give a small delay for store to update, then reload
    // setTimeout(() => {
    //   window.location.reload();
    // }, 300);
    
  } catch (error: any) {
    console.error('Login error:', error);
    setFormErrors({ general: ['Login failed. Please try again.'] });
  } finally {
    setLoading(false);
  }
};

  const handleStudentRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormErrors({});

    // Basic validation
    if (!agreeTerms) {
      setFormErrors({ agree: ['You must agree to the terms and conditions'] });
      return;
    }

    if (studentRegForm.password !== studentRegForm.confirm_password) {
      setFormErrors({ confirm_password: ['Passwords do not match'] });
      return;
    }

    // Check if location fields are selected
    if (!studentRegForm.nationality || !studentRegForm.state || !studentRegForm.city) {
      if (!studentRegForm.nationality) setFormErrors({ nationality: ['Please select a country'] });
      if (!studentRegForm.state) setFormErrors({ state: ['Please select a state'] });
      if (!studentRegForm.city) setFormErrors({ city: ['Please select a city'] });
      return;
    }

    // Prepare registration data
    const formData = {
      first_name: studentRegForm.first_name,
      last_name: studentRegForm.last_name,
      email: studentRegForm.email,
      phone: studentRegForm.phone,
      password: studentRegForm.password,
      confirm_password: studentRegForm.confirm_password,
      nationality: studentRegForm.nationality,
      state: studentRegForm.state,
      city: studentRegForm.city,
      program_type: studentRegForm.program_type,
      gender: studentRegForm.gender,
      agree: true,
      user_type: 'student'
    };

    setLoading(true);

    try {
      // Call your registration API endpoint
      const response = await fetch('/api/frontend/register/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      const data = await response.json();

      if (!response.ok) {
        if (data.message && typeof data.message === 'object') {
          setFormErrors(data.message);
        } else if (data.message) {
          setFormErrors({ general: [data.message] });
        } else {
          setFormErrors({ general: ['Registration failed. Please try again.'] });
        }
        return;
      }

      // Registration successful
      setRegistrationSuccess(true);
      
      // Reset form
      setStudentRegForm({
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        password: '',
        confirm_password: '',
        nationality: '',
        state: '',
        city: '',
        program_type: '',
        gender: ''
      });
      setAgreeTerms(false);
      
      // Auto-switch to login tab after 2 seconds
      setTimeout(() => {
        setActiveTab('login');
        // Pre-fill email in login form
        setLoginForm(prev => ({ ...prev, email: studentRegForm.email }));
      }, 2000);
      
    } catch (error: any) {
      console.error('Registration error:', error);
      setFormErrors({ general: ['Registration failed. Please try again.'] });
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm">
      <div className="relative w-full max-w-4xl max-h-[90vh] overflow-y-auto bg-white rounded-2xl shadow-2xl border border-gray-200">
        {/* Header */}
        <div className="sticky top-0 z-10 flex items-center justify-between p-6 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white rounded-t-2xl">
          <div>
            <h2 className="text-2xl font-bold">
              {activeTab === 'login' ? 'Welcome Back' : 'Join UniversitiesPage'}
            </h2>
            <p className="text-blue-100 text-sm mt-1">
              {activeTab === 'login' 
                ? 'Sign in to unlock all embassy interview questions' 
                : 'Create an account to access premium features'}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-full hover:bg-white/20 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        <div className="p-6">
          {/* Tabs */}
          <div className="flex bg-gray-100 rounded-xl p-1 mb-6">
            <button
              onClick={() => setActiveTab('login')}
              className={`flex-1 py-3 text-center font-medium rounded-lg transition-all ${
                activeTab === 'login'
                  ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              Sign In
            </button>
            <button
              onClick={() => setActiveTab('register')}
              className={`flex-1 py-3 text-center font-medium rounded-lg transition-all ${
                activeTab === 'register'
                  ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              Create Account
            </button>
          </div>

          {/* Registration Success Message */}
          {registrationSuccess && (
            <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-xl animate-fadeIn">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-green-600 rounded-lg">
                  <Check className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-green-800 font-semibold">Registration Successful!</p>
                  <p className="text-green-700 text-sm">Your account has been created. Switching to login...</p>
                </div>
              </div>
            </div>
          )}

          {/* General Error Display */}
          {formErrors.general && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl">
              <div className="flex items-center gap-3">
                <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0" />
                <div>
                  <p className="text-red-700 font-medium">Error</p>
                  <p className="text-red-600 text-sm">{formErrors.general[0]}</p>
                </div>
              </div>
            </div>
          )}

          {/* Forms */}
          <div className="mt-6">
            {activeTab === 'login' ? (
              <form onSubmit={handleLogin} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Email Address *
                  </label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type="email"
                      value={loginForm.email}
                      onChange={(e) => setLoginForm({...loginForm, email: e.target.value})}
                      className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                      placeholder="your@email.com"
                      required
                    />
                  </div>
                  {displayErrors('email')}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Password *
                  </label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type={showPassword ? 'text' : 'password'}
                      value={loginForm.password}
                      onChange={(e) => setLoginForm({...loginForm, password: e.target.value})}
                      className="w-full pl-10 pr-12 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                      placeholder="••••••••"
                      required
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                    </button>
                  </div>
                  {displayErrors('password')}
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full py-3.5 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white font-semibold rounded-xl hover:opacity-90 transition-all disabled:opacity-50 flex items-center justify-center gap-2 shadow-lg hover:shadow-xl"
                >
                  {loading ? (
                    <>
                      <Loader2 className="w-5 h-5 animate-spin" />
                      Signing in...
                    </>
                  ) : (
                    'Sign In & Unlock All Questions'
                  )}
                </button>
              </form>
            ) : (
              <div className="max-h-[50vh] overflow-y-auto pr-2">
                                <form onSubmit={handleStudentRegister} className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        First Name *
                      </label>
                      <div className="relative">
                        <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <input
                          type="text"
                          value={studentRegForm.first_name}
                          onChange={(e) => setStudentRegForm({...studentRegForm, first_name: e.target.value})}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                          placeholder="John"
                          required
                        />
                      </div>
                      {displayErrors('first_name')}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Last Name *
                      </label>
                      <div className="relative">
                        <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <input
                          type="text"
                          value={studentRegForm.last_name}
                          onChange={(e) => setStudentRegForm({...studentRegForm, last_name: e.target.value})}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                          placeholder="Doe"
                          required
                        />
                      </div>
                      {displayErrors('last_name')}
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Email *
                      </label>
                      <div className="relative">
                        <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <input
                          type="email"
                          value={studentRegForm.email}
                          onChange={(e) => setStudentRegForm({...studentRegForm, email: e.target.value})}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                          placeholder="john@example.com"
                          required
                        />
                      </div>
                      {displayErrors('email')}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Phone *
                      </label>
                      <div className="relative">
                        <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <input
                          type="tel"
                          value={studentRegForm.phone}
                          onChange={(e) => setStudentRegForm({...studentRegForm, phone: e.target.value})}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                          placeholder="+92 300 1234567"
                          required
                        />
                      </div>
                      {displayErrors('phone')}
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Password *
                      </label>
                      <div className="relative">
                        <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <input
                          type={showPassword ? 'text' : 'password'}
                          value={studentRegForm.password}
                          onChange={(e) => setStudentRegForm({...studentRegForm, password: e.target.value})}
                          className="w-full pl-10 pr-12 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                          placeholder="••••••••"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword(!showPassword)}
                          className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        >
                          {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                        </button>
                      </div>
                      {displayErrors('password')}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Confirm Password *
                      </label>
                      <div className="relative">
                        <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <input
                          type={showConfirmPassword ? 'text' : 'password'}
                          value={studentRegForm.confirm_password}
                          onChange={(e) => setStudentRegForm({...studentRegForm, confirm_password: e.target.value})}
                          className="w-full pl-10 pr-12 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all"
                          placeholder="••••••••"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                          className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        >
                          {showConfirmPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                        </button>
                      </div>
                      {displayErrors('confirm_password')}
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Country *
                      </label>
                      <div className="relative">
                        <Globe className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <select
                          value={studentRegForm.nationality}
                          onChange={(e) => handleCountryChange(e.target.value)}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all appearance-none bg-white"
                          required
                          disabled={loadingCountries}
                        >
                          <option value="">{loadingCountries ? 'Loading...' : 'Select Country'}</option>
                          {countries.map(country => (
                            <option key={country.id} value={String(country.id)}>
                              {country.name}
                            </option>
                          ))}
                        </select>
                      </div>
                      {displayErrors('nationality')}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        State *
                      </label>
                      <div className="relative">
                        <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <select
                          value={studentRegForm.state}
                          onChange={(e) => handleStateChange(e.target.value)}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all appearance-none bg-white"
                          required
                          disabled={!studentRegForm.nationality || loadingStates}
                        >
                          <option value="">
                            {loadingStates ? 'Loading...' : 
                             !studentRegForm.nationality ? 'Select Country first' : 
                             'Select State'}
                          </option>
                          {states.map(state => (
                            <option key={state.id} value={String(state.id)}>
                              {state.name}
                            </option>
                          ))}
                        </select>
                      </div>
                      {displayErrors('state')}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        City *
                      </label>
                      <div className="relative">
                        <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <select
                          value={studentRegForm.city}
                          onChange={(e) => handleCityChange(e.target.value)}
                          className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all appearance-none bg-white"
                          required
                          disabled={!studentRegForm.state || loadingCities}
                        >
                          <option value="">
                            {loadingCities ? 'Loading...' : 
                             !studentRegForm.state ? 'Select State first' : 
                             'Select City'}
                          </option>
                          {cities.map(city => (
                            <option key={city.id} value={String(city.id)}>
                              {city.name}
                            </option>
                          ))}
                        </select>
                      </div>
                      {displayErrors('city')}
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Program Type *
                      </label>
                      <select
                        value={studentRegForm.program_type}
                        onChange={(e) => setStudentRegForm({...studentRegForm, program_type: e.target.value})}
                        className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all appearance-none bg-white"
                        required
                      >
                        <option value="">Select Program</option>
                        <option value="Undergraduate">Undergraduate</option>
                        <option value="Graduate">Graduate</option>
                        <option value="PhD">PhD</option>
                        <option value="Diploma">Diploma</option>
                      </select>
                      {displayErrors('program_type')}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Gender *
                      </label>
                      <select
                        value={studentRegForm.gender}
                        onChange={(e) => setStudentRegForm({...studentRegForm, gender: e.target.value})}
                        className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-[#0B6F78] transition-all appearance-none bg-white"
                        required
                      >
                        <option value="">Select Gender</option>
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                        <option value="Other">Other</option>
                      </select>
                      {displayErrors('gender')}
                    </div>
                  </div>

                  {/* Selected Location Display */}
{(studentRegForm.nationality || studentRegForm.state || studentRegForm.city) && (
  <div className="p-3 bg-gradient-to-r from-[#0B6F78]/5 to-[#0a306b]/5 rounded-xl border border-[#0B6F78]/20">
    <p className="text-sm text-gray-700">
      Selected Location: 
      {studentRegForm.nationality && (
        <span className="font-medium text-[#0a306b] ml-2">
          {countries.find(c => String(c.id) === studentRegForm.nationality)?.name || 'Selecting...'}
        </span>
      )}
      {studentRegForm.state && (
        <span className="font-medium text-[#0a306b] ml-2">
          → {states.find(s => String(s.id) === studentRegForm.state)?.name || 'Selecting...'}
        </span>
      )}
      {studentRegForm.city && (
        <span className="font-medium text-[#0a306b] ml-2">
          → {cities.find(c => String(c.id) === studentRegForm.city)?.name || 'Selecting...'}
        </span>
      )}
    </p>
  </div>
)}

                  {/* Terms and Conditions */}
                  <div className="flex items-start space-x-3 p-4 bg-gray-50 rounded-xl">
                    <input
                      type="checkbox"
                      id="agree-terms-student"
                      checked={agreeTerms}
                      onChange={(e) => {
                        setAgreeTerms(e.target.checked);
                        if (formErrors.agree) {
                          setFormErrors(prev => {
                            const newErrors = { ...prev };
                            delete newErrors.agree;
                            return newErrors;
                          });
                        }
                      }}
                      className="mt-1 w-5 h-5 text-[#0B6F78] border-gray-300 rounded focus:ring-[#0B6F78] focus:ring-2"
                      required
                    />
                    <label htmlFor="agree-terms-student" className="text-sm text-gray-700">
                      I agree to the{' '}
                        Terms and Conditions{' '}
                      and{' '}
                        Privacy Policy
                    </label>
                  </div>
                  {displayErrors('agree')}

                  <button
                    type="submit"
                    disabled={loading}
                    className="w-full py-3.5 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white font-semibold rounded-xl hover:opacity-90 transition-all disabled:opacity-50 flex items-center justify-center gap-2 shadow-lg hover:shadow-xl"
                  >
                    {loading ? (
                      <>
                        <Loader2 className="w-5 h-5 animate-spin" />
                        Creating Account...
                      </>
                    ) : (
                      'Register as Student'
                    )}
                  </button>
                </form>

              </div>
            )}
          </div>

          {/* Benefits Card */}
          <div className="mt-6 p-5 bg-gradient-to-r from-[#0B6F78]/10 to-[#0a306b]/10 rounded-2xl border border-[#0B6F78]/20">
            <div className="flex items-center gap-3 mb-3">
              <div className="p-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-lg">
                <CheckCircle className="w-5 h-5 text-white" />
              </div>
              <h3 className="font-semibold text-gray-900">Unlock Premium Embassy Interview Features</h3>
            </div>
            <ul className="text-sm text-gray-700 space-y-2">
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-[#0B6F78] rounded-full"></div>
                <span>Full access to all 15+ predicted embassy questions</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-[#0B6F78] rounded-full"></div>
                <span>Detailed officer psychology analysis for each question</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-[#0B6F78] rounded-full"></div>
                <span>Personalized answer suggestions and common mistakes</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-[#0B6F78] rounded-full"></div>
                <span>Downloadable interview preparation sheet</span>
              </li>
            </ul>
          </div>

          <div className="mt-6 pt-6 border-t border-gray-200 text-center">
            <p className="text-sm text-gray-600">
              {activeTab === 'login' ? "Don't have an account?" : "Already have an account?"}{' '}
              <button
                type="button"
                onClick={() => {
                  setActiveTab(activeTab === 'login' ? 'register' : 'login');
                  setFormErrors({});
                  setRegistrationSuccess(false);
                }}
                className="text-[#0B6F78] hover:text-[#0a306b] font-semibold"
              >
                {activeTab === 'login' ? 'Create Account' : 'Sign In'}
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AuthModal;