'use client';

// src/app/admin/login/page.tsx

import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { useUserStore } from '@/stores/admin-store';
import { Turnstile, TurnstileInstance } from '@marsidev/react-turnstile';

export default function AdminLogin() {
  const router = useRouter();
  const [formData, setFormData] = useState({ email: '', password: '' });
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [token, setToken] = useState<string | null>(null);
  const turnstileRef = useRef<TurnstileInstance>(null);

  // 2FA states
  const [requires2FA, setRequires2FA] = useState(false);
  const [twoFactorMethod, setTwoFactorMethod] = useState<'email' | 'totp'>('email');
  const [verificationCode, setVerificationCode] = useState('');
  const [tempUser, setTempUser] = useState<{ id: string; email: string; first_name: string } | null>(null);
  const [resendCooldown, setResendCooldown] = useState(0);
  const [remainingAttempts, setRemainingAttempts] = useState<number>(5);
  const [is2FALocked, setIs2FALocked] = useState(false);
  const [lockExpiry, setLockExpiry] = useState<Date | null>(null);
  const [showLockedScreen, setShowLockedScreen] = useState(false);

  // const [turnstileData, setTurnstileData] = useState<{ enableCaptcha: true; siteKey: string } | null>(null);
  // // FIX: turnstileError is now shown to the user
  // const [turnstileError, setTurnstileError] = useState(false);

  const { setUser } = useUserStore();

  // useEffect(() => {
  //   const fetchTurnstile = async () => {
  //     try {
  //       const response = await fetch('/api/backend/admin/auth/getturnstile', { method: 'POST' });
  //       if (!response.ok) throw new Error('Failed to fetch turnstile site key');
  //       const data = await response.json();
  //       setTurnstileData(data);
  //     } catch (error) {
  //       console.error('Error fetching turnstile site key:', error);
  //       setTurnstileData(null);
  //       setTurnstileError(true);
  //     }
  //   };
  //   fetchTurnstile();
  // }, []);

  useEffect(() => {
    if (resendCooldown > 0) {
      const timer = setTimeout(() => setResendCooldown(resendCooldown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [resendCooldown]);

  useEffect(() => {
    if (!lockExpiry || !is2FALocked) return;
    const interval = setInterval(() => {
      if (lockExpiry <= new Date()) {
        setIs2FALocked(false);
        setRemainingAttempts(5);
        setLockExpiry(null);
        clearInterval(interval);
      }
    }, 1000);
    return () => clearInterval(interval);
  }, [lockExpiry, is2FALocked]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    // if (turnstileData?.enableCaptcha && !token) {
    //   toast.error('Captcha verification required');
    //   setIsLoading(false);
    //   return;
    // }

    if (!formData.email || !formData.password) {
      toast.error('Please fill in all fields');
      setIsLoading(false);
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      toast.error('Please enter a valid email address');
      setIsLoading(false);
      return;
    }

    try {
      const result = await fetch('/api/backend/admin/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email:       formData.email,
          password:    formData.password,
          token,
          //captchStatus: turnstileData?.enableCaptcha ?? false,
        }),
      });

      const response = await result.json();

      if (response.success) {
        if (response.requires2FA) {
          setRequires2FA(true);
          setTwoFactorMethod(response.twoFactorMethod || 'email');
          setTempUser(response.user);
          if (response.twoFactorMethod === 'email') setResendCooldown(30);
          setRemainingAttempts(5);
          setIs2FALocked(false);
          setLockExpiry(null);
          setShowLockedScreen(false);

          if (response.twoFactorMethod === 'email') {
            toast.success('Verification code sent to your email');
          } else {
            toast.success('Enter your Google Authenticator code');
          }
        } else {
          // Tokens are in HTTP-only cookies set by the server — no localStorage needed.
          // We only store non-sensitive display data in the Zustand store (persisted to
          // localStorage by the persist middleware, which is fine).
          if (response.user) setUser(response.user);
          toast.success('Login successful! Redirecting...');
          setTimeout(() => router.push('/admin/dashboard'), 1000);
        }
      } else {
        toast.error(response.message || 'Login failed');
      }
    } catch (err) {
      console.error('Login error:', err);
      toast.error('An error occurred during login. Please try again.');
    } finally {
      setIsLoading(false);
      turnstileRef.current?.reset();
      setToken(null);
    }
  };

  const handle2FAVerification = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const result = await fetch('/api/backend/admin/auth/verify-2fa', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId:          tempUser?.id,
          code:            verificationCode,
          twoFactorMethod,
        }),
      });

      const response = await result.json();

      if (response.success) {
        // Tokens are in HTTP-only cookies — only store display data in Zustand.
        // FIX: removed localStorage.setItem call that was here previously.
        if (response.user) setUser(response.user);
        toast.success('Verification successful! Redirecting...');
        setTimeout(() => router.push('/admin/dashboard'), 1000);
      } else {
        toast.error(response.message);

        if (response.message?.includes('locked')) {
          setIs2FALocked(true);
          setRemainingAttempts(0);
          setShowLockedScreen(true);
          const match = response.message?.match(/locked for (\d+) minute/);
          if (match) {
            setLockExpiry(new Date(Date.now() + parseInt(match[1]) * 60 * 1000));
          }
        } else {
          const attemptsMatch = response.message?.match(/(\d+) attempt\(s\) remaining/);
          if (attemptsMatch) {
            const attempts = parseInt(attemptsMatch[1]);
            setRemainingAttempts(attempts);
            if (attempts <= 0) {
              setIs2FALocked(true);
              setShowLockedScreen(true);
            }
          }
        }
      }
    } catch (err) {
      console.error('2FA verification error:', err);
      toast.error('An error occurred during verification. Please try again.');
    } finally {
      setIsLoading(false);
      turnstileRef.current?.reset();
      setToken(null);
    }
  };

  const handleResendCode = async () => {
    if (resendCooldown > 0) return;
    setIsLoading(true);
    try {
      const result = await fetch('/api/backend/admin/auth/resend-2fa', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: tempUser?.id }),
      });
      const response = await result.json();
      if (response.success) {
        toast.success('New verification code sent!');
        setResendCooldown(30);
        setRemainingAttempts(5);
        setIs2FALocked(false);
        setLockExpiry(null);
        setShowLockedScreen(false);
      } else {
        toast.error(response.message || 'Failed to resend code');
      }
    } catch (err) {
      console.error('Resend code error:', err);
      toast.error('Failed to resend code. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleBackToLogin = () => {
    setRequires2FA(false);
    setVerificationCode('');
    setTempUser(null);
    setRemainingAttempts(5);
    setIs2FALocked(false);
    setLockExpiry(null);
    setShowLockedScreen(false);
    setTwoFactorMethod('email');
  };

  const formatTimeRemaining = () => {
    if (!lockExpiry) return '15 minutes';
    const diffMs   = Math.max(0, lockExpiry.getTime() - Date.now());
    const diffMins = Math.ceil(diffMs / 60_000);
    return `${diffMins} minute${diffMins !== 1 ? 's' : ''}`;
  };

  const get2FATitle = () =>
    twoFactorMethod === 'totp' ? 'Google Authenticator' : 'Two-Factor Authentication';

  // FIX: replaced dangerouslySetInnerHTML with safe JSX rendering
  const render2FADescription = () => {
    if (twoFactorMethod === 'email') {
      return (
        <p className="text-gray-300 text-sm">
          Enter the verification code sent to{' '}
          <strong className="text-white">{tempUser?.email}</strong>
        </p>
      );
    }
    return (
      <p className="text-gray-300 text-sm">
        Enter the 6-digit code from your Google Authenticator app
      </p>
    );
  };

  return (
    <div className="min-h-screen bg-linear-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center p-4">
      <Link href="/" className="absolute top-6 left-6 z-10 group">
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          className="flex items-center gap-2 text-white/80 hover:text-white transition-colors duration-300"
        >
          <svg className="w-5 h-5 group-hover:-translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          Back to Home
        </motion.div>
      </Link>

      <AnimatePresence mode="wait">
        {showLockedScreen ? (
          // ── Account Locked Screen ────────────────────────────────────────────
          <motion.div key="locked-screen" initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.9 }} className="relative w-full max-w-md">
            <div className="absolute -inset-4 bg-linear-to-r from-red-600 to-orange-600 rounded-2xl blur-lg opacity-20" />
            <div className="relative bg-white/10 backdrop-blur-xl rounded-2xl border border-white/20 shadow-2xl overflow-hidden">
              <div className="p-8">
                <div className="text-center mb-6">
                  <div className="w-20 h-20 bg-linear-to-r from-red-500 to-orange-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
                    <svg className="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                    </svg>
                  </div>
                  <h2 className="text-2xl font-bold bg-linear-to-r from-white to-gray-300 bg-clip-text text-transparent mb-2">Account Locked</h2>
                  <p className="text-gray-300 text-sm">Too many failed verification attempts</p>
                </div>
                <div className="bg-red-500/10 border border-red-500/20 rounded-xl p-4 mb-6">
                  <div className="flex items-center justify-center mb-2">
                    <svg className="w-5 h-5 text-red-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span className="text-red-300 font-medium">Locked for: {formatTimeRemaining()}</span>
                  </div>
                  <p className="text-gray-300 text-sm text-center">The account will automatically unlock after this period.</p>
                </div>
                <button type="button" onClick={handleBackToLogin} className="w-full py-3 px-4 bg-linear-to-r from-gray-600 to-gray-700 hover:from-gray-700 hover:to-gray-800 text-white font-medium rounded-xl shadow-lg transition-all duration-300 transform hover:scale-[1.02] focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 focus:ring-offset-transparent">
                  ← Return to Login
                </button>
              </div>
            </div>
          </motion.div>

        ) : requires2FA ? (
          // ── 2FA Verification Form ────────────────────────────────────────────
          <motion.div key="2fa-form" initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.9 }} className="relative w-full max-w-md">
            <div className={`absolute -inset-4 ${twoFactorMethod === 'email' ? 'bg-linear-to-r from-green-600 to-blue-600' : 'bg-linear-to-r from-orange-500 to-yellow-600'} rounded-2xl blur-lg opacity-20`} />
            <div className="relative bg-white/10 backdrop-blur-xl rounded-2xl border border-white/20 shadow-2xl overflow-hidden">
              <div className="p-8">
                <div className="text-center mb-6">
                  <div className={`w-16 h-16 ${twoFactorMethod === 'email' ? 'bg-linear-to-r from-green-500 to-blue-600' : 'bg-linear-to-r from-orange-500 to-yellow-600'} rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg`}>
                    {twoFactorMethod === 'email' ? (
                      <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                      </svg>
                    ) : (
                      <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
                      </svg>
                    )}
                  </div>
                  <h2 className="text-2xl font-bold bg-linear-to-r from-white to-gray-300 bg-clip-text text-transparent mb-2">
                    {get2FATitle()}
                  </h2>
                  {/* FIX: safe JSX rendering instead of dangerouslySetInnerHTML */}
                  {render2FADescription()}
                  {twoFactorMethod === 'email' && (
                    <div className="mt-2 text-xs text-blue-400">Code expires in 10 minutes</div>
                  )}
                </div>

                <form onSubmit={handle2FAVerification}>
                  <div className="space-y-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-3 text-center">
                        {twoFactorMethod === 'email' ? 'Verification Code' : 'Authenticator Code'}
                      </label>
                      <input
                        type="text"
                        value={verificationCode}
                        onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                        placeholder="000000"
                        maxLength={6}
                        className={`w-full px-4 py-4 bg-white/5 border rounded-xl text-white text-center text-2xl font-mono tracking-widest focus:outline-none focus:ring-2 focus:border-transparent transition-all duration-300 disabled:opacity-50 ${
                          is2FALocked
                            ? 'border-red-500/50 focus:ring-red-500'
                            : twoFactorMethod === 'email'
                            ? 'border-white/10 focus:ring-green-500'
                            : 'border-white/10 focus:ring-orange-500'
                        }`}
                        required
                        disabled={isLoading || is2FALocked}
                        autoFocus
                      />
                      <div className="mt-2 text-center">
                        {is2FALocked ? (
                          <div className="text-red-400 text-sm">
                            <div className="flex items-center justify-center gap-2">
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                              </svg>
                              <span>Account locked. Try again in {formatTimeRemaining()}.</span>
                            </div>
                            <button type="button" onClick={() => setShowLockedScreen(true)} className="text-red-300 hover:text-red-200 underline text-xs mt-1">
                              View lock details
                            </button>
                          </div>
                        ) : (
                          <p className="text-gray-400 text-sm">
                            {remainingAttempts} attempt{remainingAttempts !== 1 ? 's' : ''} remaining
                          </p>
                        )}
                        <p className="text-gray-400 text-sm text-center mt-2">
                          {twoFactorMethod === 'email'
                            ? 'Enter the 6-digit code from your email'
                            : 'Enter the 6-digit code from your authenticator app'}
                        </p>
                      </div>
                    </div>

                    {/* {turnstileData?.enableCaptcha && (
                      <Turnstile
                        ref={turnstileRef}
                        siteKey={turnstileData.siteKey || process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
                        onSuccess={(t: string | null) => setToken(t)}
                        onExpire={() => setToken(null)}
                      />
                    )} */}

                    <button
                      type="submit"
                      disabled={isLoading || verificationCode.length !== 6 || is2FALocked}
                      className={`w-full py-3 px-4 ${
                        twoFactorMethod === 'email'
                          ? 'bg-linear-to-r from-green-600 to-blue-600 hover:from-green-700 hover:to-blue-700'
                          : 'bg-linear-to-r from-orange-600 to-yellow-600 hover:from-orange-700 hover:to-yellow-700'
                      } text-white font-medium rounded-xl shadow-lg transition-all duration-300 transform hover:scale-[1.02] focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 focus:ring-offset-transparent disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100`}
                    >
                      {isLoading ? (
                        <div className="flex items-center justify-center">
                          <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                          </svg>
                          Verifying...
                        </div>
                      ) : (
                        'Verify & Continue'
                      )}
                    </button>

                    <div className="text-center space-y-3">
                      {twoFactorMethod === 'email' && (
                        <button
                          type="button"
                          onClick={handleResendCode}
                          disabled={resendCooldown > 0 || isLoading || is2FALocked}
                          className="text-blue-400 hover:text-blue-300 transition-colors duration-300 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                        >
                          {resendCooldown > 0 ? `Resend code in ${resendCooldown}s` : 'Resend verification code'}
                        </button>
                      )}
                      <div>
                        <button type="button" onClick={handleBackToLogin} className="text-gray-400 hover:text-white transition-colors duration-300 text-sm">
                          ← Back to Login
                        </button>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </motion.div>

        ) : (
          // ── Login Form ───────────────────────────────────────────────────────
          <motion.div key="login-form" initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} transition={{ duration: 0.5 }} className="relative w-full max-w-md">
            <div className="absolute -inset-4 bg-linear-to-r from-blue-600 to-purple-600 rounded-2xl blur-lg opacity-20" />
            <div className="relative bg-white/10 backdrop-blur-xl rounded-2xl border border-white/20 shadow-2xl overflow-hidden">
              <div className="p-8 pb-6">
                <motion.div initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} transition={{ delay: 0.1 }} className="text-center">
                  <div className="w-16 h-16 bg-linear-to-r from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
                    <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                    </svg>
                  </div>
                  <h1 className="text-3xl font-bold bg-linear-to-r from-white to-gray-300 bg-clip-text text-transparent mb-2">Admin Access</h1>
                  <p className="text-gray-300 text-sm">Enter your credentials to access the admin panel</p>
                </motion.div>
              </div>

              <form onSubmit={handleSubmit} className="p-8 pt-6">
                <div className="space-y-6">
                  {/* FIX: show turnstile load error to the user */}
                  {/* {turnstileError && (
                    <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-3 text-red-300 text-sm text-center">
                      CAPTCHA failed to load. Please refresh the page before signing in.
                    </div>
                  )} */}

                  <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.2 }}>
                    <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">Email Address</label>
                    <div className="relative">
                      <input
                        id="email" name="email" type="email" required
                        value={formData.email} onChange={handleChange} disabled={isLoading}
                        className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                        placeholder="admin@example.com"
                      />
                      <div className="absolute inset-y-0 right-0 pr-3 flex items-center">
                        <svg className="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
                        </svg>
                      </div>
                    </div>
                  </motion.div>

                  <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.3 }}>
                    <label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-2">Password</label>
                    <div className="relative">
                      <input
                        id="password" name="password" type={showPassword ? 'text' : 'password'} required
                        value={formData.password} onChange={handleChange} disabled={isLoading}
                        className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-300 pr-12 disabled:opacity-50 disabled:cursor-not-allowed"
                        placeholder="••••••••"
                      />
                      <div className="absolute inset-y-0 right-0 pr-3 flex items-center">
                        <button
                          type="button" onClick={() => setShowPassword(!showPassword)} disabled={isLoading}
                          className="text-gray-400 hover:text-gray-300 transition-colors duration-300 focus:outline-none rounded-lg p-1 disabled:opacity-50"
                          aria-label={showPassword ? 'Hide password' : 'Show password'}
                        >
                          {showPassword ? (
                            <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L6.59 6.59m9.02 9.02l3.83 3.83" />
                            </svg>
                          ) : (
                            <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                          )}
                        </button>
                      </div>
                    </div>
                  </motion.div>

                  {/* {turnstileData?.enableCaptcha && (
                    <Turnstile
                      ref={turnstileRef}
                      siteKey={turnstileData.siteKey || process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
                      onSuccess={(t: string | null) => setToken(t)}
                      onExpire={() => setToken(null)}
                    />
                  )} */}

                  <motion.button
                    initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5 }}
                    type="submit" disabled={isLoading}
                    className="w-full py-3 px-4 bg-linear-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-medium rounded-xl shadow-lg transition-all duration-300 transform hover:scale-[1.02] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-slate-900 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
                  >
                    {isLoading ? (
                      <div className="flex items-center justify-center">
                        <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                        </svg>
                        Signing in...
                      </div>
                    ) : (
                      'Sign in to Admin Panel'
                    )}
                  </motion.button>
                </div>
              </form>

              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.6 }} className="px-8 py-4 bg-black/20 border-t border-white/10">
                <p className="text-center text-xs text-gray-400">Secure access to administrative controls</p>
              </motion.div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      <div className="absolute top-1/4 left-1/4 w-32 h-32 bg-blue-500/10 rounded-full blur-xl" />
      <div className="absolute bottom-1/4 right-1/4 w-40 h-40 bg-purple-500/10 rounded-full blur-xl" />
    </div>
  );
}