import { API_BASE_URL } from '../lib/config';
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '../context/AuthContext';
import { cn } from '../lib/utils';
import ritLogo from '../assets/images/college-logo.png';
import { Mail, Lock, LogIn, AlertCircle, X, ArrowLeft, Shield } from 'lucide-react';
import { signInWithPopup } from 'firebase/auth';
import { auth, googleProvider } from '../lib/firebaseBackend';

const DEPARTMENTS = ['AIDS', 'CSBS', 'CSE', 'CCE', 'MECH', 'VLSI', 'BIO-TECH', 'AIML', 'ECE', 'H&S'];
const EXTERNAL_DEPARTMENTS = [
  ...DEPARTMENTS,
  'Information Technology (IT)',
  'Electrical & Electronics Engineering (EEE)',
  'Civil Engineering',
  'Biomedical Engineering',
  'Chemical Engineering',
  'Aeronautical / Aerospace Engineering',
  'Mechatronics Engineering',
  'Others'
];
const SECTIONS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
const YEARS = ['1st Year', '2nd Year', '3rd Year', '4th Year', '5th Year'];

const GoogleIcon = () => (
  <svg className="w-5 h-5 mr-3" viewBox="0 0 24 24" width="24" height="24" xmlns="http://www.w3.org/2000/svg">
    <g transform="matrix(1, 0, 0, 1, 0, 0)">
      <path d="M21.35,11.1H12v2.7h5.38c-0.24,1.28 -0.96,2.37 -2.04,3.1v2.58h3.3c1.93,-1.78 3.04,-4.4 3.04,-7.48C21.68,11.96 21.56,11.49 21.35,11.1z" fill="#4285F4" />
      <path d="M12,20.58c2.43,0 4.47,-0.8 5.96,-2.2l-2.58,-2c-0.72,0.48 -1.64,0.77 -2.58,0.77 -2.37,0 -4.38,-1.6 -5.1,-3.75H4.31v2.1a8.4,8.4 0 0,0 7.69,5.08z" fill="#34A853" />
      <path d="M6.9,13.4c-0.18,-0.54 -0.29,-1.11 -0.29,-1.7 0,-0.59 0.11,-1.16 0.29,-1.7V7.9H4.31A8.4,8.4 0 0,0 3.3,11.7c0,1.38 0.33,2.69 1.01,3.8l2.59,-2.1z" fill="#FBBC05" />
      <path d="M12,6.85c1.32,0 2.5,0.45 3.44,1.35l2.58,-2.58C16.46,4.1 14.43,3.32 12,3.32c-4.79,0 -8.7,2.82 -10.39,6.9l2.59,2.1c0.72,-2.15 2.73,-3.75 5.1,-3.75z" fill="#EA4335" />
    </g>
  </svg>
);

export const LoginPage: React.FC = () => {
  const { login } = useAuth();
  const [isSignUp, setIsSignUp] = useState(false);
  const [signUpType, setSignUpType] = useState<'INTERNAL' | 'EXTERNAL' | null>(null);
  const [splashState, setSplashState] = useState<'logo' | 'text' | 'fade-to-white' | 'done'>('logo');
  const [isMobile, setIsMobile] = useState(typeof window !== 'undefined' ? window.innerWidth < 1024 : false);

  useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth < 1024);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffect(() => {
    const timer1 = setTimeout(() => {
      setSplashState('text');
    }, 1500);

    const timer2 = setTimeout(() => {
      setSplashState('fade-to-white');
    }, 3000);

    const timer3 = setTimeout(() => {
      setSplashState('done');
    }, 4500);

    return () => {
      clearTimeout(timer1);
      clearTimeout(timer2);
      clearTimeout(timer3);
    };
  }, []);
  
  // Login credentials state
  const [emailInput, setEmailInput] = useState('');
  const [passwordInput, setPasswordInput] = useState('');

  // Register state (for other colleges / external students)
  const [formData, setFormData] = useState({
    email: '',
    phone: '',
    regNo: '',
    password: '',
    confirmPassword: '',
    name: '',
    collegeName: 'Rajalakshmi Institute of Technology',
    department: '',
    section: '',
    year: '',
    gender: '',
    collegeLocation: '',
  });

  const [showPassword, setShowPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  
  // Google sign in state
  const [showGoogleChooser, setShowGoogleChooser] = useState(false);
  const [customGoogleEmail, setCustomGoogleEmail] = useState('');

  const mockAccounts = [
    { email: "student.240007@cse.ritchennai.edu.in", name: "Abiram R (3rd Year CSE)", role: "Student (Auto-Reg)" },
    { email: "student.250012@aiml.ritchennai.edu.in", name: "John Doe (2nd Year AIML)", role: "Student (Auto-Reg)" },
    { email: "faculty@rit.edu", name: "Dr. Faculty Member", role: "Faculty" },
    { email: "hod@rit.edu", name: "Prof. Head of Dept", role: "HOD" },
    { email: "principal@rit.edu", name: "Dr. College Principal", role: "Principal" },
    { email: "admin@rit.edu", name: "System Administrator", role: "Admin" },
  ];

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleLoginSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);
    setIsSubmitting(true);

    try {
      const response = await fetch(API_BASE_URL + '/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: emailInput,
          password: passwordInput
        })
      });

      if (response.ok) {
        const userData = await response.json();
        login(userData);
      } else {
        const errData = await response.json();
        throw new Error(errData.message || "Invalid credentials.");
      }
    } catch (err: any) {
      setErrorMessage(err.message || "An error occurred during authentication.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleGoogleSignIn = async () => {
    setErrorMessage(null);
    setIsSubmitting(true);
    try {
      const result = await signInWithPopup(auth, googleProvider);
      const user = result.user;
      if (user && user.email) {
        const response = await fetch(API_BASE_URL + '/api/auth/google-login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: user.email,
            fullName: user.displayName || "RIT User"
          })
        });

        if (response.ok) {
          const userData = await response.json();
          login(userData);
        } else {
          const errData = await response.json();
          throw new Error(errData.message || "Failed to sync Google account with database.");
        }
      }
    } catch (err: any) {
      console.error("Google Auth Error:", err);
      if (err.code !== 'auth/popup-closed-by-user') {
        setErrorMessage(err.message || "Google Sign-In failed.");
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleGoogleLoginSubmit = async (email: string, name: string) => {
    if (!email) {
      alert("Please select or enter a Google account email.");
      return;
    }
    setErrorMessage(null);
    setIsSubmitting(true);
    setShowGoogleChooser(false);

    try {
      const response = await fetch(API_BASE_URL + '/api/auth/google-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email,
          fullName: name
        })
      });

      if (response.ok) {
        const userData = await response.json();
        login(userData);
      } else {
        const errData = await response.json();
        throw new Error(errData.message || "OAuth login failed.");
      }
    } catch (err: any) {
      setErrorMessage(err.message || "Google Sign-In failed.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleRegisterSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);
    setIsSubmitting(true);

    try {
      if (formData.password !== formData.confirmPassword) {
        throw new Error("Passwords do not match.");
      }

      const signupPayload = {
        email: formData.email,
        password: formData.password,
        fullName: formData.name,
        regNo: formData.regNo,
        phone: formData.phone,
        gender: formData.gender,
        collegeName: signUpType === 'EXTERNAL' ? formData.collegeName : 'Rajalakshmi Institute of Technology',
        department: formData.department,
        year: signUpType === 'EXTERNAL' ? 'N/A' : formData.year,
        section: signUpType === 'EXTERNAL' ? 'N/A' : formData.section,
        role: 'STUDENT'
      };

      const response = await fetch(API_BASE_URL + '/api/auth/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(signupPayload)
      });

      if (response.ok) {
        const userData = await response.json();
        alert("Account registered successfully!");
        login(userData);
      } else {
        const errData = await response.json();
        throw new Error(errData.message || "Registration failed.");
      }
    } catch (err: any) {
      setErrorMessage(err.message || "An error occurred.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const RIT_BLUE = 'bg-[#004a99]';
  const RIT_BLUE_TEXT = 'text-[#004a99]';
  const RIT_BLUE_HOVER = 'hover:bg-[#003366]';

  return (
    <div className="h-screen w-full bg-white flex font-sans overflow-y-auto lg:overflow-hidden relative">
      
      {/* Left Column: Branding (hidden on mobile, 55% width on desktop) */}
      <div className="hidden lg:flex lg:w-[55%] bg-gradient-to-br from-[#003B5C] via-[#004a99] to-[#001D3D] text-white flex-col justify-between p-16 relative overflow-hidden">
        {/* Abstract vector backgrounds for a premium institutional feel */}
        <div className="absolute inset-0 pointer-events-none opacity-20">
          <div className="absolute -top-[20%] -left-[10%] w-[700px] h-[700px] rounded-full border border-white/10" />
          <div className="absolute -bottom-[30%] -right-[10%] w-[800px] h-[800px] rounded-full border border-white/10" />
          <div className="absolute top-[20%] right-[10%] w-[300px] h-[300px] rounded-full bg-white/5 blur-[50px]" />
        </div>

        {/* Top: Brand Header */}
        <motion.div 
          initial={{ opacity: 0, y: -20 }}
          animate={splashState === 'fade-to-white' || splashState === 'done' ? { opacity: 1, y: 0 } : { opacity: 0, y: -20 }}
          transition={{ duration: 0.8, ease: "easeOut" }}
          className="flex items-center z-10"
        >
          <img src={ritLogo} alt="RIT Logo" className="h-20 w-auto object-contain bg-white/95 p-3 rounded-2xl shadow-sm hover:scale-105 transition-transform duration-300 cursor-pointer" />
        </motion.div>

        {/* Middle: Feature list / value proposition */}
        <motion.div 
          initial="hidden"
          animate={splashState === 'fade-to-white' || splashState === 'done' ? "visible" : "hidden"}
          variants={{
            hidden: { opacity: 0 },
            visible: {
              opacity: 1,
              transition: {
                staggerChildren: 0.15,
                delayChildren: 0.2
              }
            }
          }}
          className="space-y-8 z-10 my-auto"
        >
          <motion.div 
            variants={{
              hidden: { opacity: 0, x: -30 },
              visible: { opacity: 1, x: 0, transition: { type: "spring", stiffness: 100 } }
            }}
            className="space-y-4"
          >
            <span className="px-3 py-1 bg-white/10 rounded-full text-[9px] font-black uppercase tracking-widest text-slate-200">Centralized Portal</span>
            <h1 className="text-5xl font-black tracking-tight leading-tight uppercase">
              RIT EVENT HUB
            </h1>
            <p className="text-sm font-medium text-slate-200/80 max-w-lg leading-relaxed">
              Your central hub to discover, register, and track all institutional activities, workshops, seminars, and campus events at Rajalakshmi Institute of Technology.
            </p>
          </motion.div>

          <motion.div 
            variants={{
              hidden: { opacity: 0, y: 20 },
              visible: { opacity: 1, y: 0, transition: { duration: 0.5 } }
            }}
            className="space-y-4 pt-6 border-t border-white/10 max-w-md"
          >
            {[
              { title: "Campus Calendar", desc: "Discover upcoming workshops, technical symposiums, and cultural events easily." },
              { title: "Student Passports", desc: "Access your registrations, entry passes, and event certificates in one place." },
              { title: "Stay Connected", desc: "Get real-time announcements on departmental activities and club schedules." }
            ].map((f, i) => (
              <div key={i} className="flex gap-4 items-start hover:translate-x-1 transition-transform duration-200">
                <div className="w-6 h-6 rounded-lg bg-white/10 flex items-center justify-center text-xs font-black text-white shrink-0 mt-0.5">✓</div>
                <div>
                  <h4 className="text-xs font-black uppercase tracking-wider text-white">{f.title}</h4>
                  <p className="text-[11px] text-slate-300 font-medium mt-1 leading-relaxed">{f.desc}</p>
                </div>
              </div>
            ))}
          </motion.div>
        </motion.div>

        {/* Bottom: Institutional footer (Terms & Conditions removed) */}
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.8, duration: 0.5 }}
          className="z-10 flex items-center text-[10px] font-bold text-slate-400 uppercase tracking-widest"
        >
          <span>RIT Event Hub © {new Date().getFullYear()}</span>
        </motion.div>
      </div>

      {/* Right Column: Form (100% on mobile, 45% on desktop) */}
      <div className="w-full lg:w-[45%] flex items-center justify-center p-8 md:p-16 bg-white relative">
        {/* Light overlay grid pattern */}
        <div className="absolute inset-0 pointer-events-none opacity-[0.04]" style={{ backgroundImage: 'linear-gradient(to right, #004a99 1px, transparent 1px), linear-gradient(to bottom, #004a99 1px, transparent 1px)', backgroundSize: '48px 48px' }} />

        {/* Decorative radial accents on the white side to retain look */}
        <div className="absolute top-[10%] right-[10%] w-[300px] h-[300px] bg-brand-glow rounded-full blur-[100px] opacity-30 pointer-events-none" />
        <div className="absolute bottom-[10%] left-[10%] w-[300px] h-[300px] bg-indigo-50 rounded-full blur-[100px] opacity-30 pointer-events-none" />

        <div className="w-full max-w-sm z-10 flex flex-col justify-center min-h-[500px]">
          <AnimatePresence mode="wait">
            {!isSignUp ? (
              // ----------------------------------------------------
              // CENTRALIZED SIGN IN (NO CARD)
              // ----------------------------------------------------
              <motion.div
                key="login-pane"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
                className="space-y-8"
              >
                <div className="space-y-3">
                  {/* Logo only on mobile/tablet */}
                  <img src={ritLogo} alt="RIT Logo" className="h-10 w-auto object-contain mb-4 lg:hidden" />
                  <h2 className="text-3xl font-black text-slate-900 tracking-tight uppercase leading-none">
                    Welcome Back
                  </h2>
                  <p className="text-slate-400 text-xs font-bold uppercase tracking-widest">Sign in to your account</p>
                </div>

                <div className="space-y-6">
                  {/* Google Sign In Button */}
                  <button
                    onClick={handleGoogleSignIn}
                    onDoubleClick={() => setShowGoogleChooser(true)}
                    title="Double-click to open mock accounts for local testing"
                    className="w-full py-4 px-6 bg-white border border-slate-200 hover:border-slate-300 rounded-2xl flex items-center justify-center text-xs font-black text-slate-700 uppercase tracking-widest hover:bg-slate-50 transition-all hover:scale-[1.01] active:scale-[0.99] shadow-sm"
                  >
                    <GoogleIcon />
                    Sign in with Google
                  </button>

                  {/* Separator */}
                  <div className="flex items-center justify-center gap-4">
                    <div className="h-px bg-slate-100 flex-1" />
                    <span className="text-[9px] font-black text-slate-300 uppercase tracking-widest">or use credentials</span>
                    <div className="h-px bg-slate-100 flex-1" />
                  </div>

                  {/* Email & Password Form */}
                  <form onSubmit={handleLoginSubmit} className="space-y-4">
                    <div className="relative">
                      <Mail className="absolute left-5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                      <input
                        required
                        type="email"
                        placeholder="EMAIL ADDRESS"
                        value={emailInput}
                        onChange={(e) => setEmailInput(e.target.value)}
                        className="w-full bg-slate-50 border border-slate-100 focus:bg-white focus:border-brand-indigo/30 rounded-2xl pl-12 pr-6 py-4 text-xs font-bold outline-none transition-all"
                      />
                    </div>

                    <div className="relative">
                      <Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                      <input
                        required
                        type={showPassword ? 'text' : 'password'}
                        placeholder="PASSWORD"
                        value={passwordInput}
                        onChange={(e) => setPasswordInput(e.target.value)}
                        className="w-full bg-slate-50 border border-slate-100 focus:bg-white focus:border-brand-indigo/30 rounded-2xl pl-12 pr-12 py-4 text-xs font-bold outline-none transition-all"
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-5 top-1/2 -translate-y-1/2 text-slate-300 hover:text-brand-indigo transition-colors"
                      >
                        <i className={cn("fas", showPassword ? "fa-eye-slash" : "fa-eye")}></i>
                      </button>
                    </div>

                    {errorMessage && (
                      <div className="p-4 bg-red-50 text-red-600 rounded-2xl text-xs font-bold flex items-center gap-2 border border-red-100/50">
                        <AlertCircle className="w-4 h-4 shrink-0" />
                        <span>{errorMessage}</span>
                      </div>
                    )}

                    <button
                      type="submit"
                      disabled={isSubmitting}
                      className={cn(
                        "w-full py-4.5 text-white text-xs font-black rounded-2xl transition-all shadow-md hover:shadow-lg active:scale-[0.99] disabled:opacity-55 flex items-center justify-center gap-2 mt-4",
                        RIT_BLUE,
                        RIT_BLUE_HOVER
                      )}
                    >
                      <LogIn className="w-4 h-4" />
                      {isSubmitting ? 'Verifying...' : 'Sign in now...'}
                    </button>
                  </form>

                  <div className="text-center pt-2">
                    <button
                      type="button"
                      onClick={() => {
                        setIsSignUp(true);
                        setSignUpType('EXTERNAL');
                        setErrorMessage(null);
                      }}
                      className="text-xs font-black text-brand-indigo hover:underline transition-colors uppercase tracking-wider"
                    >
                      External Student ? Register here..
                    </button>
                  </div>
                </div>
              </motion.div>
            ) : (
              // ----------------------------------------------------
              // SIGN UP (Only for External Students - NO CARD)
              // ----------------------------------------------------
              <motion.div
                key="signup-pane"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
                className="space-y-6"
              >
                <div className="relative flex items-center justify-between pb-2">
                  <button
                    onClick={() => {
                      setIsSignUp(false);
                      setSignUpType(null);
                      setErrorMessage(null);
                    }}
                    className="w-8 h-8 bg-slate-50 hover:bg-slate-100 text-slate-500 rounded-full flex items-center justify-center transition-all border border-slate-100"
                    type="button"
                  >
                    <ArrowLeft className="w-3.5 h-3.5" />
                  </button>
                  <span className="text-[9px] font-black text-slate-300 uppercase tracking-widest">Other College Sign Up</span>
                </div>

                <div className="space-y-2">
                  <h2 className="text-2xl font-black text-slate-900 uppercase tracking-tight leading-none">
                    Create Account
                  </h2>
                  <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest">Register as external student</p>
                </div>

                <form onSubmit={handleRegisterSubmit} className="space-y-3.5 max-h-[420px] overflow-y-auto pr-2 py-1 scrollbar-hide">
                  <div className="grid grid-cols-2 gap-3">
                    <input required name="name" placeholder="FULL NAME" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.name} onChange={handleInputChange} />
                    <input required type="email" name="email" placeholder="EMAIL" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.email} onChange={handleInputChange} />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <input required name="regNo" placeholder="REG NO" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.regNo} onChange={handleInputChange} />
                    <input required name="phone" placeholder="PHONE NUMBER" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.phone} onChange={handleInputChange} />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <input required type="password" name="password" placeholder="PASSWORD" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.password} onChange={handleInputChange} />
                    <input required type="password" name="confirmPassword" placeholder="CONFIRM" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.confirmPassword} onChange={handleInputChange} />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <select required name="gender" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all cursor-pointer" value={formData.gender} onChange={handleInputChange}>
                      <option value="">GENDER</option>
                      <option value="Male">MALE</option>
                      <option value="Female">FEMALE</option>
                      <option value="Other">OTHER</option>
                    </select>
                    <input required name="collegeLocation" placeholder="LOCATION" className="bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.collegeLocation} onChange={handleInputChange} />
                  </div>

                  <input required name="collegeName" placeholder="COLLEGE NAME" className="w-full bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all" value={formData.collegeName} onChange={handleInputChange} />

                  <select required name="department" className="w-full bg-slate-50 border-slate-100 focus:bg-white focus:border-brand-indigo/30 border rounded-xl px-4 py-3 text-xs font-bold outline-none transition-all cursor-pointer" value={formData.department} onChange={handleInputChange}>
                    <option value="">SELECT DEPARTMENT</option>
                    {EXTERNAL_DEPARTMENTS.map(d => <option key={d} value={d}>{d}</option>)}
                  </select>

                  {errorMessage && (
                    <div className="p-4 bg-red-50 text-red-600 rounded-xl text-xs font-bold flex items-center gap-2 border border-red-100/50">
                      <AlertCircle className="w-4 h-4 shrink-0" />
                      <span>{errorMessage}</span>
                    </div>
                  )}

                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className={cn(
                      "w-full py-4.5 text-white text-xs font-black rounded-xl transition-all shadow-md hover:shadow-lg active:scale-[0.99] disabled:opacity-55 flex items-center justify-center gap-2",
                      RIT_BLUE,
                      RIT_BLUE_HOVER
                    )}
                  >
                    {isSubmitting ? 'Registering...' : 'Sign up now...'}
                  </button>
                </form>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>

      {/* ----------------------------------------------------
          MOCK GOOGLE ACCOUNT CHOOSER MODAL
          ---------------------------------------------------- */}
      <AnimatePresence>
        {showGoogleChooser && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setShowGoogleChooser(false)}
              className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-md bg-white rounded-[2.5rem] premium-shadow overflow-hidden"
            >
              <div className="p-8 space-y-4">
                <div className="flex items-center justify-between pb-4 border-b border-slate-100">
                  <div>
                    <h3 className="text-lg font-black text-brand-navy flex items-center gap-1.5 uppercase">
                      <Shield className="w-5 h-5 text-brand-indigo" />
                      Sign In with Google
                    </h3>
                    <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider mt-0.5">Mock OAuth Provider Account Chooser</p>
                  </div>
                  <button onClick={() => setShowGoogleChooser(false)} className="p-2 hover:bg-slate-50 rounded-xl text-slate-400 transition-all">
                    <X className="w-5 h-5" />
                  </button>
                </div>
                
                <div className="space-y-2 max-h-[300px] overflow-y-auto pr-1">
                  {mockAccounts.map((acc) => (
                    <button
                      key={acc.email}
                      onClick={() => handleGoogleLoginSubmit(acc.email, acc.name.split(' (')[0])}
                      className="w-full text-left p-3.5 bg-slate-50 hover:bg-brand-glow border border-slate-100 hover:border-brand-indigo/20 rounded-2xl flex items-center justify-between transition-all hover:scale-[1.01]"
                    >
                      <div>
                        <p className="text-xs font-black text-brand-navy leading-none">{acc.name}</p>
                        <p className="text-[10px] text-slate-400 font-medium mt-1">{acc.email}</p>
                      </div>
                      <span className="px-2 py-0.5 bg-white border border-slate-100 text-[8px] font-black uppercase tracking-widest text-brand-indigo rounded-md">{acc.role}</span>
                    </button>
                  ))}
                </div>
                
                <div className="border-t border-slate-100 pt-4 space-y-3">
                  <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Or enter a custom email</p>
                  <div className="flex gap-2">
                    <input
                      type="email"
                      placeholder="student.260099@cse.ritchennai.edu.in"
                      value={customGoogleEmail}
                      onChange={(e) => setCustomGoogleEmail(e.target.value)}
                      className="flex-1 bg-slate-50 border border-slate-100 rounded-xl px-4 py-2 text-xs font-semibold focus:outline-none focus:border-brand-indigo/30"
                    />
                    <button
                      onClick={() => handleGoogleLoginSubmit(customGoogleEmail, "Custom Google User")}
                      className="px-4 py-2.5 bg-brand-navy text-white font-black text-[9px] uppercase tracking-widest rounded-xl hover:scale-105 active:scale-95 transition-all shadow-sm"
                    >
                      OAuth Sign In
                    </button>
                  </div>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Splash Screen Overlay */}
      <AnimatePresence>
        {splashState !== 'done' && (
          <motion.div
            key="splash-overlay"
            initial={{ clipPath: "polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)" }}
            animate={{ 
              clipPath: splashState === 'fade-to-white'
                ? (isMobile ? "polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%)" : "polygon(0% 0%, 55% 0%, 55% 100%, 0% 100%)")
                : "polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)"
            }}
            transition={{ duration: 1.5, ease: [0.85, 0, 0.15, 1] }}
            className="fixed inset-0 z-[200] bg-gradient-to-br from-[#003B5C] via-[#004a99] to-[#001D3D] flex items-center justify-center overflow-hidden"
          >
            {/* Centered content overlay for Logo/Text */}
            <div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">
              <AnimatePresence mode="wait">
                {splashState === 'logo' && (
                  <motion.div
                    key="logo"
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 1.1 }}
                    transition={{ duration: 0.6, ease: "easeInOut" }}
                    className="flex flex-col items-center gap-4"
                  >
                    <img src={ritLogo} alt="RIT Logo" className="h-28 w-auto object-contain drop-shadow-[0_10px_20px_rgba(255,255,255,0.15)]" />
                  </motion.div>
                )}

                {splashState === 'text' && (
                  <motion.div
                    key="text"
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.6, ease: "easeInOut" }}
                    className="text-center"
                  >
                    <h1 className="text-4xl md:text-5xl font-black text-white tracking-widest uppercase">
                      RIT EVENT HUB
                    </h1>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

    </div>
  );
};
