'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { ArrowRight, CheckCircle2, Eye, EyeOff, KeyRound, Loader2, Mail, ShieldCheck, Sparkles, UsersRound } from 'lucide-react';
import { useGoogleLogin } from '@react-oauth/google';
import { dashboardApi } from '@/api/dashboardClient';
import { useAuth } from '@/lib/AuthContext';
import { CountryCodeDropdown } from '@/components/ui/CountryCodeDropdown';
import TurnstileWidget from '@/components/ui/TurnstileWidget';
import { getApiPath } from '@/lib/basePath';
import { getSafeInternalPath } from '@/lib/authNavigation';

const BRAND = '#4A1429';
const GOLD = '#D4B038';
const MUTED = '#6B5D52';
const BORDER = '#E5DDD5';
const CREAM = '#FAF5F0';
const PASSWORD_RULE_MESSAGE = 'Password must be at least 8 characters and include one uppercase letter, one number, and one special symbol.';

function GoogleIcon() {
  return (
    <svg className="h-4 w-4" viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
      <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
    </svg>
  );
}

async function readJsonSafely(response) {
  const text = await response.text();
  if (!text) return {};

  try {
    return JSON.parse(text);
  } catch {
    return {};
  }
}

function isStrongPassword(value) {
  return (
    String(value || '').length >= 8
    && /[A-Z]/.test(value)
    && /\d/.test(value)
    && /[^A-Za-z0-9\s]/.test(value)
  );
}

function getRegisterSource() {
  if (typeof window === 'undefined') return { page: '/register', path: '/register' };

  return {
    page: window.location.pathname || '/register',
    path: `${window.location.pathname || '/register'}${window.location.search || ''}`,
    pageUrl: window.location.href,
  };
}

export default function LoginClient({
  mode = 'login',
  embedded = false,
  redirectTo = '/',
  showRegisterLink = true,
  showGoogle = true,
  redirectIfAuthenticated = false,
  honorRedirectParam = true,
  variant = 'default',
}) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const auth = useAuth();
  const [authView, setAuthView] = useState(mode);
  const isRegister = authView === 'register';
  const isAlgebra = variant === 'algebra';
  const redirectParam = searchParams.get('redirect');
  const initialEmail = String(searchParams.get('email') || '').trim().toLowerCase();
  const isEmbeddedRegistration = isRegister && searchParams.get('embed') === '1';
  const effectiveRedirectTo = honorRedirectParam
    ? getSafeInternalPath(redirectParam, redirectTo)
    : redirectTo;
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState(initialEmail);
  const [countryCode, setCountryCode] = useState(isAlgebra ? '+1' : '+91');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [error, setError] = useState('');
  const [notice, setNotice] = useState('');
  const [loading, setLoading] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);
  const [authMode, setAuthMode] = useState('password');
  const [otp, setOtp] = useState('');
  const [otpSent, setOtpSent] = useState(false);
  const [otpLoading, setOtpLoading] = useState(false);
  const [turnstileToken, setTurnstileToken] = useState('');
  const [turnstileResetKey, setTurnstileResetKey] = useState(0);
  const alternateAuthParams = new URLSearchParams();
  if (initialEmail) alternateAuthParams.set('email', initialEmail);
  if (effectiveRedirectTo !== '/') alternateAuthParams.set('redirect', effectiveRedirectTo);
  const alternateAuthHref = `${isRegister ? '/login' : '/register'}${alternateAuthParams.size ? `?${alternateAuthParams.toString()}` : ''}`;

  useEffect(() => {
    setAuthView(mode);
  }, [mode]);

  const setPhoneDigits = (event) => {
    setPhone(event.target.value.replace(/\D/g, '').slice(0, 14));
  };

  useEffect(() => {
    if (!isRegister && redirectIfAuthenticated && auth?.isAuthenticated) {
      router.replace(effectiveRedirectTo);
    }
  }, [auth?.isAuthenticated, effectiveRedirectTo, isRegister, redirectIfAuthenticated, router]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setError('');
    setLoading(true);
    let turnstileWasSubmitted = false;

    try {
      if (isRegister) {
        const phoneNumber = phone.trim();

        if (!firstName.trim() || !lastName.trim()) {
          throw new Error('First name and last name are required.');
        }

        if (!/^\d{6,14}$/.test(phoneNumber)) {
          throw new Error('Enter a valid phone number with country code.');
        }

        if (password !== confirmPassword) {
          throw new Error('Password and confirm password must match.');
        }

        if (!isStrongPassword(password)) {
          throw new Error(PASSWORD_RULE_MESSAGE);
        }

        if (!turnstileToken) {
          throw new Error('Please complete the security verification.');
        }
      }

      if (isRegister) {
        turnstileWasSubmitted = true;
        const response = await fetch(getApiPath('/api/auth/register'), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            firstName: firstName.trim(),
            lastName: lastName.trim(),
            email: email.trim(),
            countryCode,
            phoneNumber: phone.trim(),
            phone: `${countryCode} ${phone.trim()}`,
            password,
            turnstileToken,
            source: getRegisterSource(),
          }),
        });
        const data = await response.json().catch(() => ({}));

        if (!response.ok) {
          throw new Error(data?.message || data?.error || 'Could not create your account.');
        }

        if (data?.requiresEmailVerification) {
          if (typeof window !== 'undefined') {
            window.sessionStorage.setItem('register_otp_email', data.email || email.trim());
          }
          const verifyParams = new URLSearchParams({ email: data.email || email.trim() });
          if (effectiveRedirectTo !== '/') verifyParams.set('redirect', effectiveRedirectTo);
          if (isEmbeddedRegistration) verifyParams.set('embed', '1');
          router.push(`/register/verify?${verifyParams.toString()}`);
          return;
        }

        if (data?.user) {
          auth?.login?.(data.user);
          router.push(effectiveRedirectTo);
          router.refresh();
          return;
        }
      }

      const user = await dashboardApi.auth.login(email, password);
      if (user?.requiresTwoFactor) {
        setEmail(user.email || email.trim());
        setAuthMode('otp');
        setOtp('');
        setOtpSent(true);
        setNotice(user.message || 'Enter the verification code sent to your email.');
        return;
      }
      auth?.login?.(user);
      router.push(effectiveRedirectTo);
      router.refresh();
    } catch (err) {
      setError(err.message || (isRegister ? 'Could not create your account.' : 'Could not sign in. Please check your details.'));
    } finally {
      if (turnstileWasSubmitted) {
        setTurnstileToken('');
        setTurnstileResetKey((value) => value + 1);
      }
      setLoading(false);
    }
  };

  const requestLoginOtp = async () => {
    setError('');
    setNotice('');
    setOtpLoading(true);

    try {
      if (!email.trim()) {
        throw new Error('Enter your email address to receive a login code.');
      }

      const response = await fetch(getApiPath('/api/auth/request-login-otp'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
      const data = await readJsonSafely(response);

      if (!response.ok) {
        throw new Error(data?.message || 'Could not send login code.');
      }

      setOtpSent(true);
      setNotice(data?.message || 'Login code sent to your email.');
    } catch (err) {
      setError(err.message || 'Could not send login code.');
    } finally {
      setOtpLoading(false);
    }
  };

  const handleOtpSubmit = async (event) => {
    event.preventDefault();
    setError('');
    setNotice('');
    setOtpLoading(true);

    try {
      if (!email.trim()) {
        throw new Error('Email address is required.');
      }

      if (!/^\d{6}$/.test(otp.trim())) {
        throw new Error('Enter the 6-digit code from your email.');
      }

      const response = await fetch(getApiPath('/api/auth/verify-login-otp'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), otp: otp.trim() }),
      });
      const data = await readJsonSafely(response);

      if (!response.ok) {
        throw new Error(data?.message || 'Invalid login code.');
      }

      auth?.login?.(data.user);
      router.push(effectiveRedirectTo);
      router.refresh();
    } catch (err) {
      setError(err.message || 'Could not verify login code.');
    } finally {
      setOtpLoading(false);
    }
  };

  const handleGoogle = useGoogleLogin({
    flow: 'implicit',
    ux_mode: 'popup',
    onSuccess: async (tokenResponse) => {
      setGoogleLoading(true);
      setError('');
      try {
        const response = await fetch(getApiPath('/api/auth/google'), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            token: tokenResponse.access_token,
            source: getRegisterSource(),
          }),
        });
        const data = await readJsonSafely(response);

        if (!response.ok) {
          throw new Error(data?.message || 'Google login failed.');
        }

        if (data?.requiresTwoFactor) {
          setEmail(data.email || email.trim());
          setAuthMode('otp');
          setOtp('');
          setOtpSent(true);
          setNotice(data.message || 'Enter the verification code sent to your email.');
          return;
        }
        auth?.login?.(data.user);
        router.push(effectiveRedirectTo);
        router.refresh();
      } catch (err) {
        setError(err.message || 'Google login failed. Please try again.');
      } finally {
        setGoogleLoading(false);
      }
    },
    onError: () => {
      setError('Google login failed. Please try again.');
      setGoogleLoading(false);
    },
  });

  return (
    <div
      className={isAlgebra
        ? 'min-h-screen'
        : `${embedded ? 'px-4 py-10 sm:py-12' : 'min-h-screen px-4 py-10'}`}
      style={{
        backgroundColor: isAlgebra ? '#FAF6EF' : CREAM,
        fontFamily: isAlgebra ? 'ui-sans-serif, system-ui, sans-serif' : undefined,
      }}
    >
      <div className={isAlgebra
        ? 'mx-auto w-full max-w-2xl'
        : 'mx-auto grid w-full max-w-6xl gap-8 lg:grid-cols-[minmax(0,1fr)_440px] lg:items-center'}>
        {isAlgebra && !isRegister && (
          <header className="mb-8">
            <div className="mb-8 flex items-center gap-2.5">
              <div
                className="flex h-9 w-9 items-center justify-center rounded-lg text-[10px] font-extrabold"
                style={{ background: 'linear-gradient(135deg, #4A1429, #8B2252)', color: '#D4AF37' }}
              >
                CV
              </div>
              <div>
                <div
                  className="text-xs font-extrabold tracking-wide"
                  style={{ color: '#2D0A18', fontFamily: "'Fraunces', Georgia, serif" }}
                >
                  Cambridge Veritas
                </div>
                <div className="text-[9px] font-bold uppercase tracking-[0.18em]" style={{ color: '#B8912E' }}>
                  Algebra I &middot; Family access
                </div>
              </div>
            </div>

            <h1
              className="text-3xl font-extrabold leading-tight sm:text-4xl"
              style={{ color: '#2D0A18', fontFamily: "'Fraunces', Georgia, serif" }}
            >
              Welcome back to Algebra I.
            </h1>
            <p className="mt-4 max-w-xl text-sm font-medium leading-relaxed sm:text-base" style={{ color: '#4A3A30' }}>
              Sign in to view your child&apos;s lessons, practice, teacher feedback, notes, and parent reports.
            </p>
          </header>
        )}

        {!isRegister && !isAlgebra && (
          <section className="relative overflow-hidden rounded-[28px] border bg-[#4A1429] p-7 text-white shadow-xl sm:p-10">
            <div className="absolute right-8 top-8 h-24 w-24 rounded-full border border-[#D4B038]/30" />
            <div className="absolute bottom-8 right-20 h-12 w-12 animate-pulse rounded-full bg-[#D4B038]/25" />
            <div className="relative">
              <div className="inline-flex items-center gap-2 rounded-full border border-[#D4AF37]/35 bg-[#D4AF37]/8 px-4 py-2 text-xs font-black uppercase tracking-[0.18em] text-[#F6E6C3]">
                <Sparkles className="h-4 w-4" />
                Cambridge Veritas member access
              </div>
              <h1 className="mt-6 max-w-2xl text-4xl font-black leading-tight sm:text-5xl">
                Sign in to continue your professional English learning plan.
              </h1>
              <p className="mt-5 max-w-xl text-base leading-7 text-[#F6E6C3]/85">
                Access structured spoken English lessons, business communication resources, IELTS practice, class materials, and learner progress tools from one secure account.
              </p>

              <div className="mt-8 grid gap-3 sm:grid-cols-3">
                {[
                  ['35+', 'career-focused English courses'],
                  ['1000+', 'teacher network and mentors'],
                  ['5 star', 'learner review experience'],
                ].map((item, index) => (
                  <div
                    key={item[0]}
                    className="rounded-2xl border border-white/15 bg-white/10 p-4 backdrop-blur"
                    style={{ animation: `floatCard 4s ease-in-out ${index * 0.4}s infinite` }}
                  >
                    <p className="text-2xl font-black text-white">{item[0]}</p>
                    <p className="mt-1 text-xs font-bold uppercase leading-5 tracking-wider text-[#F6E6C3]/75">{item[1]}</p>
                  </div>
                ))}
              </div>

              <div className="mt-8 grid gap-4 text-sm font-semibold text-[#F6E6C3]/90 sm:grid-cols-2">
                <div className="flex items-start gap-3">
                  <ShieldCheck className="mt-0.5 h-5 w-5 text-[#D4B038]" />
                  Secure login for class resources, progress tracking, and certificates.
                </div>
                <div className="flex items-start gap-3">
                  <UsersRound className="mt-0.5 h-5 w-5 text-[#D4B038]" />
                  Built for students, working professionals, and global teams.
                </div>
              </div>
            </div>
            <style jsx>{`
              @keyframes floatCard {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(-8px); }
              }
            `}</style>
          </section>
        )}

        <section className={`w-full ${isRegister ? 'mx-auto max-w-2xl lg:col-span-2' : isAlgebra ? '' : 'lg:justify-self-end'}`}>
          <div
            className={isAlgebra
              ? 'rounded-3xl border bg-white p-6 shadow-xl sm:p-8'
              : 'rounded-[28px] border bg-white p-5 shadow-xl sm:p-7'}
            style={{ borderColor: isAlgebra ? 'rgba(212,175,56,0.5)' : BORDER }}
          >
            {!embedded && !isRegister && (
              <div className="mb-6 flex items-center gap-3">
                <div className="flex h-11 w-11 items-center justify-center rounded-xl font-black" style={{ backgroundColor: GOLD, color: BRAND }}>
                  CV
                </div>
                <div>
                  <div className="text-lg font-black" style={{ color: BRAND }}>Cambridge Veritas</div>
                  <div className="text-[11px] font-bold uppercase tracking-widest" style={{ color: MUTED }}>Business Academy</div>
                </div>
              </div>
            )}

            {isAlgebra && !isRegister && (
              <p className="mb-3 text-[10px] font-bold uppercase tracking-[0.22em]" style={{ color: '#B8912E' }}>
                Parent account sign in
              </p>
            )}
            <h2
              className={isAlgebra ? 'text-2xl font-extrabold sm:text-3xl' : 'text-3xl font-black'}
              style={{ color: isAlgebra ? '#B8912E' : BRAND, fontFamily: isAlgebra ? "'Fraunces', Georgia, serif" : undefined }}
            >
              {isRegister ? 'Create account' : isAlgebra ? 'Open your family dashboard' : 'Welcome back'}
            </h2>
            <p className="mt-2 text-sm font-medium" style={{ color: isAlgebra ? '#B8912E' : MUTED }}>
              {isRegister ? 'Start your learning journey.' : isAlgebra ? 'Use Google, your password, or a one-time email code.' : 'Choose Google, password, or a one-time email code.'}
            </p>

            {error && (
              <div
                className="mt-5 rounded-xl border px-4 py-3 text-sm font-medium"
                style={{ backgroundColor: 'rgba(220,38,38,0.06)', borderColor: 'rgba(220,38,38,0.20)', color: '#b91c1c' }}
              >
                {error}
              </div>
            )}

            {notice && (
              <div
                className="mt-5 flex gap-2 rounded-xl border px-4 py-3 text-sm font-medium"
                style={{ backgroundColor: 'rgba(22,163,74,0.06)', borderColor: 'rgba(22,163,74,0.20)', color: '#15803d' }}
              >
                <CheckCircle2 className="mt-0.5 h-4 w-4 flex-shrink-0" />
                {notice}
              </div>
            )}

            {!isRegister && showGoogle && (
              <button
                type="button"
                onClick={() => handleGoogle()}
                disabled={googleLoading || loading || otpLoading}
                className="mt-6 flex w-full items-center justify-center gap-3 rounded-xl border px-4 py-3 text-sm font-black transition-all hover:bg-[#FAF5F0] disabled:opacity-50"
                style={{ borderColor: BORDER, color: BRAND }}
              >
                {googleLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <GoogleIcon />}
                Continue with Google
              </button>
            )}

            {!isRegister && (
              <div className="mt-5 grid grid-cols-2 rounded-xl bg-[#FAF5F0] p-1">
                <button
                  type="button"
                  onClick={() => { setAuthMode('password'); setError(''); setNotice(''); }}
                  className={`flex items-center justify-center gap-2 rounded-lg px-3 py-2.5 text-sm font-black transition ${authMode === 'password' ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: BRAND }}
                >
                  <KeyRound className="h-4 w-4" />
                  Password
                </button>
                <button
                  type="button"
                  onClick={() => { setAuthMode('otp'); setError(''); setNotice(''); }}
                  className={`flex items-center justify-center gap-2 rounded-lg px-3 py-2.5 text-sm font-black transition ${authMode === 'otp' ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: BRAND }}
                >
                  <Mail className="h-4 w-4" />
                  Email OTP
                </button>
              </div>
            )}

            <div className="my-5 flex items-center gap-3">
              <div className="h-px flex-1" style={{ backgroundColor: BORDER }} />
              <span className="text-xs font-bold" style={{ color: MUTED }}>{isRegister ? 'account details' : 'or sign in with'}</span>
              <div className="h-px flex-1" style={{ backgroundColor: BORDER }} />
            </div>

            {authMode === 'otp' && !isRegister ? (
              <form onSubmit={handleOtpSubmit} className="space-y-4">
                <div>
                  <label className="mb-1.5 block text-xs font-bold uppercase tracking-wider" style={{ color: MUTED }}>Email Address</label>
                  <input
                    type="email"
                    value={email}
                    onChange={(event) => setEmail(event.target.value)}
                    required
                    autoComplete="email"
                    className="w-full rounded-xl border px-4 py-3 text-sm focus:outline-none"
                    style={{ borderColor: BORDER, color: BRAND }}
                  />
                </div>

                {otpSent && (
                  <div>
                    <label className="mb-1.5 block text-xs font-bold uppercase tracking-wider" style={{ color: MUTED }}>6-digit code</label>
                    <input
                      type="text"
                      value={otp}
                      onChange={(event) => setOtp(event.target.value.replace(/\D/g, '').slice(0, 6))}
                      required
                      inputMode="numeric"
                      maxLength={6}
                      className="w-full rounded-xl border px-4 py-3 text-center text-lg font-black tracking-[0.4em] focus:outline-none"
                      style={{ borderColor: BORDER, color: BRAND }}
                    />
                  </div>
                )}

                <button
                  type={otpSent ? 'submit' : 'button'}
                  onClick={otpSent ? undefined : requestLoginOtp}
                  disabled={otpLoading || googleLoading}
                  className="flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-black text-white transition-all disabled:opacity-50"
                  style={{ backgroundColor: BRAND }}
                >
                  {otpLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                  {otpSent ? 'Verify Code & Sign In' : 'Send Login Code'}
                  {!otpLoading && <ArrowRight className="h-4 w-4" />}
                </button>

                {otpSent && (
                  <button
                    type="button"
                    onClick={requestLoginOtp}
                    disabled={otpLoading}
                    className="w-full text-center text-xs font-bold hover:opacity-70"
                    style={{ color: BRAND }}
                  >
                    Resend code
                  </button>
                )}
              </form>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                {isRegister && (
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: MUTED }}>First Name</label>
                      <input
                        type="text"
                        value={firstName}
                        onChange={(event) => setFirstName(event.target.value)}
                        required
                        autoComplete="given-name"
                        className="w-full rounded-xl px-4 py-3 text-sm border focus:outline-none"
                        style={{ borderColor: BORDER, color: BRAND }}
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: MUTED }}>Last Name</label>
                      <input
                        type="text"
                        value={lastName}
                        onChange={(event) => setLastName(event.target.value)}
                        required
                        autoComplete="family-name"
                        className="w-full rounded-xl px-4 py-3 text-sm border focus:outline-none"
                        style={{ borderColor: BORDER, color: BRAND }}
                      />
                    </div>
                  </div>
                )}

                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: MUTED }}>Email Address</label>
                  <input
                    type="email"
                    value={email}
                    onChange={(event) => setEmail(event.target.value)}
                    required
                    autoComplete="email"
                    className="w-full rounded-xl px-4 py-3 text-sm border focus:outline-none"
                    style={{ borderColor: BORDER, color: BRAND }}
                  />
                </div>

                {isRegister && (
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: MUTED }}>Phone With Country Code</label>
                    <div
                      className="flex min-h-[48px] w-full items-stretch overflow-visible rounded-xl border bg-white focus-within:ring-2 focus-within:ring-[#D4B038]/20"
                      style={{ borderColor: BORDER }}
                    >
                      <CountryCodeDropdown value={countryCode} onChange={setCountryCode} />
                      <input
                        type="tel"
                        value={phone}
                        onChange={setPhoneDigits}
                        required
                        inputMode="numeric"
                        minLength={6}
                        maxLength={14}
                        pattern="\d{6,14}"
                        autoComplete="tel-national"
                        className="min-w-0 flex-1 rounded-r-xl px-4 py-3 text-sm focus:outline-none"
                        style={{ color: BRAND }}
                      />
                    </div>
                  </div>
                )}

                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: MUTED }}>Password</label>
                  <div className="relative">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(event) => setPassword(event.target.value)}
                      required
                      minLength={isRegister ? 8 : undefined}
                      autoComplete={isRegister ? 'new-password' : 'current-password'}
                      className="w-full rounded-xl px-4 py-3 pr-11 text-sm border focus:outline-none"
                      style={{ borderColor: BORDER, color: BRAND }}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword((value) => !value)}
                      className="password-toggle-button absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-md transition-opacity hover:opacity-70"
                      style={{ color: MUTED }}
                      aria-label={showPassword ? 'Hide password' : 'Show password'}
                    >
                      {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                    </button>
                  </div>
                  {!isRegister && (
                    <div className="mt-2 text-right">
                      <Link href="/forgot-password" className="text-xs font-bold hover:opacity-70" style={{ color: BRAND }}>
                        Forgot password?
                      </Link>
                    </div>
                  )}
                </div>

                {isRegister && (
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: MUTED }}>Confirm Password</label>
                    <div className="relative">
                      <input
                        type={showConfirmPassword ? 'text' : 'password'}
                        value={confirmPassword}
                        onChange={(event) => setConfirmPassword(event.target.value)}
                        required
                        minLength={8}
                        autoComplete="new-password"
                        className="w-full rounded-xl px-4 py-3 pr-11 text-sm border focus:outline-none"
                        style={{ borderColor: BORDER, color: BRAND }}
                      />
                      <button
                        type="button"
                        onClick={() => setShowConfirmPassword((value) => !value)}
                        className="password-toggle-button absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-md transition-opacity hover:opacity-70"
                        style={{ color: MUTED }}
                        aria-label={showConfirmPassword ? 'Hide confirm password' : 'Show confirm password'}
                      >
                        {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                      </button>
                    </div>
                  </div>
                )}

                {isRegister && (
                  <div
                    className="flex min-h-[72px] items-center rounded-xl border px-3 py-2"
                    style={{
                      borderColor: 'rgba(212,175,56,0.35)',
                      background: '#FFFFFF',
                    }}
                  >
                    <div className="flex w-full items-center gap-3">
                      <ShieldCheck
                        className="h-4 w-4 shrink-0"
                        style={{ color: '#731F32' }}
                      />

                      <div className="min-w-0 flex-1">
                        <p
                          className="mb-1 text-[10px] font-bold uppercase tracking-wide"
                          style={{ color: '#9A8A70' }}
                        >
                          Security check
                        </p>

                        <div className="turnstile-compact">
                          <TurnstileWidget
                            action="register"
                            resetKey={turnstileResetKey}
                            onVerify={(token) => {
                              setTurnstileToken(token);
                              setError('');
                            }}
                            onExpire={() => {
                              setTurnstileToken('');
                            }}
                            onError={() => {
                              setTurnstileToken('');
                              setError(
                                'Security verification could not load. Please refresh and try again.'
                              );
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full rounded-xl py-3.5 text-sm font-bold transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
                  style={{
                    backgroundColor: '#D4AF37',
                    color: '#2D0A18',
                  }}
                >
                  {loading
                    ? isRegister
                      ? 'Creating account...'
                      : 'Signing in...'
                    : isRegister
                      ? 'Create Account'
                      : 'Sign In'}
                </button>
              </form>
            )}

            {(isRegister || showRegisterLink) && (
              <p className="mt-6 text-center text-sm font-medium" style={{ color: MUTED }}>
                {isRegister ? 'Already registered?' : 'New here?'}{' '}
                {embedded ? (
                  <button
                    type="button"
                    onClick={() => {
                      setError('');
                      setNotice('');
                      setAuthMode('password');
                      setOtp('');
                      setOtpSent(false);
                      setAuthView(isRegister ? 'login' : 'register');
                    }}
                    className="font-bold hover:opacity-70"
                    style={{ color: BRAND }}
                  >
                    {isRegister ? 'Sign in' : 'Create account'}
                  </button>
                ) : (
                  <Link
                    href={alternateAuthHref}
                    className="font-bold hover:opacity-70"
                    style={{ color: BRAND }}
                  >
                    {isRegister ? 'Sign in' : 'Create account'}
                  </Link>
                )}
              </p>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}
