'use client';

import { useState, useEffect } from "react";
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Ship, InfoIcon, GlobeIcon, ChevronDownIcon, ArrowLeft } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem } from "@/components/ui/dropdown-menu"
import { useTranslation } from '@/i18n/client'
import { useRouter, useParams, usePathname, useSearchParams } from 'next/navigation';
import { signIn, useSession } from 'next-auth/react';
import { buttonVariants } from "@/components/ui/button"
import Link from "next/link"
import Image from 'next/image';
import { useFormState } from 'react-dom';
import {
    InputOTP,
    InputOTPGroup,
    InputOTPSlot,
} from "@/components/ui/input-otp"
import { requestPasswordResetAction } from "@/lib/users/auth/partners-auth";
import Loading from "../common/loading/loading";

type LoginMethod = 'username' | 'sgips';

export function LoginForm() {
    const params = useParams() || {};
    const pathname = usePathname() || '';
    const router = useRouter();
    const searchParams = useSearchParams();

    const lng = params.lng as string;
    const { t, i18n } = useTranslation(lng, 'login');
    const { toast } = useToast();
    const { data: session, status } = useSession();

    // 상태 관리
    const [loginMethod, setLoginMethod] = useState<LoginMethod>('username');
    const [isFirstAuthLoading, setIsFirstAuthLoading] = useState(false);
    const [showForgotPassword, setShowForgotPassword] = useState(false);

    // MFA 관련 상태
    const [showMfaForm, setShowMfaForm] = useState(false);
    const [mfaToken, setMfaToken] = useState('');
    const [tempAuthKey, setTempAuthKey] = useState('');
    const [mfaUserId, setMfaUserId] = useState(null);
    const [mfaUserEmail, setMfaUserEmail] = useState('');
    const [mfaCountdown, setMfaCountdown] = useState(0);

    // 일반 로그인 폼 데이터
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    // S-Gips 로그인 폼 데이터  
    const [sgipsUsername, setSgipsUsername] = useState('');
    const [sgipsPassword, setSgipsPassword] = useState('');

    const [isMfaLoading, setIsMfaLoading] = useState(false);
    const [isSmsLoading, setIsSmsLoading] = useState(false);

    // 서버 액션 상태
    const [passwordResetState, passwordResetAction] = useFormState(requestPasswordResetAction, {
        success: false,
        error: undefined,
        message: undefined,
    });

    // // 영문 페이지에서 S-Gips 로그인 비활성화 시 기본 로그인 방법 설정
    // useEffect(() => {
    //     if (lng === 'en' && loginMethod === 'sgips') {
    //         setLoginMethod('username');
    //     }
    // }, [lng, loginMethod]);

    // 이미 로그인된 사용자 리다이렉트 처리
    useEffect(() => {
        if (status === 'authenticated' && session?.user) {
            const callbackUrlParam = searchParams?.get('callbackUrl');
            
            if (callbackUrlParam) {
                try {
                    // URL 객체로 파싱
                    const callbackUrl = new URL(callbackUrlParam);
                    
                    // pathname + search만 사용 (호스트 제거)
                    const relativeUrl = callbackUrl.pathname + callbackUrl.search;
                    router.push(relativeUrl);
                } catch {
                    // 유효하지 않은 URL이면 그대로 사용 (이미 상대 경로일 수 있음)
                    router.push(callbackUrlParam);
                }
            } else {
                // callbackUrl이 없으면 기본 대시보드로 리다이렉트
                router.push(`/${lng}/partners/dashboard`);
            }
        }
    }, [status, session, router, lng, searchParams]);

    const handleChangeLanguage = (lang: string) => {
        const segments = pathname.split('/');
        segments[1] = lang;
        router.push(segments.join('/'));
    };

    const currentLanguageText = i18n.language === 'ko' ? t('languages.korean') : t('languages.english');

    // 세분화된 에러 메시지 처리 함수
    const getErrorMessage = (error: { errorCode?: string; message?: string }, provider: 'email' | 'sgips') => {
        const errorCode = error.errorCode;
        
        if (!errorCode) {
            return error.message || t('authenticationFailed');
        }

        switch (errorCode) {
            case 'INVALID_CREDENTIALS':
                return provider === 'sgips' ? t('sgipsInvalidCredentials') : t('invalidCredentials');
            case 'ACCOUNT_LOCKED':
                return t('accountLocked');
            case 'ACCOUNT_DEACTIVATED':
                return t('accountDeactivated');
            case 'RATE_LIMITED':
                return t('rateLimited');
            case 'VENDOR_NOT_FOUND':
                return t('vendorNotFound');
            case 'SYSTEM_ERROR':
                return t('systemError');
            default:
                return error.message || t('authenticationFailed');
        }
    };

    const goToVendorRegistration = () => {
        router.push(`/${lng}/partners/repository`);
    };

    // MFA 카운트다운 효과
    useEffect(() => {
        if (mfaCountdown > 0) {
            const timer = setTimeout(() => setMfaCountdown(mfaCountdown - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [mfaCountdown]);

    // 서버 액션 결과 처리
    useEffect(() => {
        if (passwordResetState.success && passwordResetState.message) {
            toast({
                title: t('resetLinkSent'),
                description: passwordResetState.message,
            });
            setShowForgotPassword(false);
        } else if (passwordResetState.error) {
            toast({
                title: t('errorTitle'),
                description: passwordResetState.error,
                variant: 'destructive',
            });
        }
    }, [passwordResetState, toast, t]);

    // 1차 인증 수행 (공통 함수)
    const performFirstAuth = async (username: string, password: string, provider: 'email' | 'sgips') => {
        try {
            const response = await fetch('/api/auth/first-auth', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    username,
                    password,
                    provider
                }),
            });

            const result = await response.json();

            if (!response.ok) {
                // 세분화된 에러 메시지 처리
                const error = new Error(result.error || t('authenticationFailed')) as Error & { errorCode?: string };
                error.errorCode = result.errorCode;
                throw error;
            }

            return result;
        } catch (error) {
            console.error('First auth error:', error);
            throw error;
        }
    };

    // SMS 토큰 전송 (userId 파라미터 추가)
    const handleSendSms = async (userIdParam?: number) => {
        const targetUserId = userIdParam || mfaUserId;
        if (!targetUserId || mfaCountdown > 0) return;

        setIsSmsLoading(true);
        try {
            const response = await fetch('/api/auth/send-sms', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ userId: targetUserId }),
            });

            if (response.ok) {
                setMfaCountdown(60);
                toast({
                    title: t('smsSent'),
                    description: t('smsCodeSent'),
                });
            } else {
                const errorData = await response.json();
                toast({
                    title: t('errorTitle'),
                    description: errorData.message || t('smsFailure'),
                    variant: 'destructive',
                });
            }
        } catch (error) {
            console.error('SMS send error:', error);
            toast({
                title: t('errorTitle'),
                description: t('smsError'),
                variant: 'destructive',
            });
        } finally {
            setIsSmsLoading(false);
        }
    };

    // MFA 토큰 검증 및 최종 로그인
    const handleMfaSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!mfaToken || mfaToken.length !== 6) {
            toast({
                title: t('errorTitle'),
                description: t('enterSixDigitCode'),
                variant: 'destructive',
            });
            return;
        }

        if (!tempAuthKey) {
            toast({
                title: t('errorTitle'),
                description: t('authSessionExpired'),
                variant: 'destructive',
            });
            setShowMfaForm(false);
            return;
        }

        setIsMfaLoading(true);

        try {
            // NextAuth의 credentials-mfa 프로바이더로 최종 인증
            const result = await signIn('credentials-mfa', {
                userId: mfaUserId,
                smsToken: mfaToken,
                tempAuthKey: tempAuthKey,
                redirect: false,
            });

            if (result?.ok) {
                toast({
                    title: t('authenticationComplete'),
                    description: t('loginCompleted'),
                });

                // 콜백 URL 처리
                const callbackUrlParam = searchParams?.get('callbackUrl');
                if (callbackUrlParam) {
                    try {
                        const callbackUrl = new URL(callbackUrlParam);
                        const relativeUrl = callbackUrl.pathname + callbackUrl.search;
                        router.push(relativeUrl);
                    } catch {
                        router.push(callbackUrlParam);
                    }
                } else {
                    router.push(`/${lng}/partners/dashboard`);
                }
            } else {
                let errorMessage = t('invalidAuthCode');
                
                if (result?.error) {
                    switch (result.error) {
                        case 'CredentialsSignin':
                            errorMessage = t('authCodeExpired');
                            break;
                        case 'AccessDenied':
                            errorMessage = t('accessDenied');
                            break;
                        default:
                            errorMessage = t('mfaAuthFailed');
                    }
                }

                toast({
                    title: t('errorTitle'),
                    description: errorMessage,
                    variant: 'destructive',
                });
            }
        } catch (error) {
            console.error('MFA verification error:', error);
            toast({
                title: t('errorTitle'),
                description: t('mfaAuthError'),
                variant: 'destructive',
            });
        } finally {
            setIsMfaLoading(false);
        }
    };

    // 일반 사용자명/패스워드 1차 인증 처리
    const handleUsernameLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!username || !password) {
            toast({
                title: t('errorTitle'),
                description: t('credentialsRequired'),
                variant: 'destructive',
            });
            return;
        }

        setIsFirstAuthLoading(true);

        try {
            // 1차 인증만 수행 (세션 생성 안함)
            const authResult = await performFirstAuth(username, password, 'email');

            if (authResult.success) {
                toast({
                    title: t('firstAuthComplete'),
                    description: t('proceedingSmsAuth'),
                });

                // MFA 화면으로 전환
                setTempAuthKey(authResult.tempAuthKey);
                setMfaUserId(authResult.userId);
                setMfaUserEmail(authResult.email);
                setShowMfaForm(true);

                // 자동으로 SMS 전송 (userId 직접 전달)
                setTimeout(() => {
                    handleSendSms(authResult.userId);
                }, 500);

                toast({
                    title: t('smsAuthRequired'),
                    description: t('sendingCodeToPhone'),
                });
            }
        } catch (error: unknown) {
            console.error('Username login error:', error);
            
            const errorMessage = getErrorMessage(error as { errorCode?: string; message?: string }, 'email');

            toast({
                title: t('errorTitle'),
                description: errorMessage,
                variant: 'destructive',
            });
        } finally {
            setIsFirstAuthLoading(false);
        }
    };

    // S-Gips 1차 인증 처리
    const handleSgipsLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!sgipsUsername || !sgipsPassword) {
            toast({
                title: t('errorTitle'),
                description: t('credentialsRequired'),
                variant: 'destructive',
            });
            return;
        }

        setIsFirstAuthLoading(true);

        try {
            // S-Gips 1차 인증만 수행 (세션 생성 안함)
            const authResult = await performFirstAuth(sgipsUsername, sgipsPassword, 'sgips');

            if (authResult.success) {
                toast({
                    title: t('sgipsAuthComplete'),
                    description: t('proceedingSmsAuth'),
                });

                // MFA 화면으로 전환
                setTempAuthKey(authResult.tempAuthKey);
                setMfaUserId(authResult.userId);
                setMfaUserEmail(authResult.email);
                setShowMfaForm(true);

                // 자동으로 SMS 전송 (userId 직접 전달)
                setTimeout(() => {
                    handleSendSms(authResult.userId);
                }, 500);

                toast({
                    title: t('smsAuthStarted'),
                    description: t('sendingCodeToSgipsPhone'),
                });
            }
        } catch (error: unknown) {
            console.error('S-Gips login error:', error);
            
            const errorMessage = getErrorMessage(error as { errorCode?: string; message?: string }, 'sgips');

            toast({
                title: t('errorTitle'),
                description: errorMessage,
                variant: 'destructive',
            });
        } finally {
            setIsFirstAuthLoading(false);
        }
    };

    // MFA 화면에서 뒤로 가기
    const handleBackToLogin = () => {
        setShowMfaForm(false);
        setMfaToken('');
        setTempAuthKey('');
        setMfaUserId(null);
        setMfaUserEmail('');
        setMfaCountdown(0);
    };

    // 세션 로딩 중이거나 이미 인증된 상태에서는 로딩 표시
    if (status === 'loading') {
        return (
            <Loading message={t('loading')} />
        );
    }

    // 이미 인증된 상태에서는 빈 화면 (리다이렉트 중)
    if (status === 'authenticated' && session?.user) {
        return (
            <Loading message={t('redirecting')} />
        );
    }

    return (
        <div className="container relative flex h-screen flex-col items-center justify-center md:grid lg:max-w-none lg:grid-cols-2 lg:px-0">
            {/* Left Content */}
            <div className="flex flex-col w-full h-screen lg:p-2">
                {/* Top bar with Logo + eVCP (left) and "Request Vendor Repository" (right) */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                        <Ship className="w-4 h-4" />
                        <span className="text-md font-bold">eVCP</span>
                    </div>
                    <Link
                        href="/partners/repository"
                        className={cn(buttonVariants({ variant: "ghost" }))}
                    >
                        <InfoIcon className="w-4 h-4 mr-1" />
                        {t('registerVendor')}
                    </Link>
                </div>

                {/* Content section that occupies remaining space, centered vertically */}
                <div className="flex-1 flex items-center justify-center">
                    <div className="mx-auto w-full flex flex-col space-y-6 sm:w-[350px]">
                        <div className="p-6 md:p-8">
                            <div className="flex flex-col gap-6">
                                {/* Header */}
                                <div className="flex flex-col items-center text-center">
                                    {!showMfaForm ? (
                                        <>
                                            <h1 className="text-2xl font-bold">{t('loginMessage')}</h1>
                                            <p className="text-xs text-muted-foreground mt-2">
                                                {t('loginDescription')}
                                            </p>
                                        </>
                                    ) : (
                                        <>
                                            <div className="flex items-center justify-center w-12 h-12 rounded-full bg-blue-100 mb-4">
                                                🔐
                                            </div>
                                            <h1 className="text-2xl font-bold">{t('smsVerification')}</h1>
                                            <p className="text-sm text-muted-foreground mt-2">
                                                {t('firstAuthCompleteFor', { email: mfaUserEmail })}
                                            </p>
                                            <p className="text-xs text-muted-foreground mt-1">
                                                {t('enterSixDigitCodeInstructions')}
                                            </p>
                                        </>
                                    )}
                                </div>

                                {/* 로그인 폼 또는 MFA 폼 */}
                                {!showMfaForm ? (
                                    <>
                                        {/* Login Method Tabs */}
                                        <div className="flex rounded-lg bg-muted p-1">
                                            <button
                                                type="button"
                                                onClick={() => setLoginMethod('username')}
                                                className={cn(
                                                    "flex-1 rounded-md px-3 py-2 text-sm font-medium transition-all",
                                                    loginMethod === 'username'
                                                        ? "bg-background text-foreground shadow-sm"
                                                        : "text-muted-foreground hover:text-foreground"
                                                )}
                                            >
                                                {t('generalLogin')}
                                            </button>
                                            {/* S-Gips 로그인은 영문 페이지에서 비활성화 0925 구매 요청사항*/}
                                            {lng !== 'en' && (
                                                <button
                                                    type="button"
                                                    onClick={() => setLoginMethod('sgips')}
                                                    className={cn(
                                                        "flex-1 rounded-md px-3 py-2 text-sm font-medium transition-all",
                                                        loginMethod === 'sgips'
                                                            ? "bg-background text-foreground shadow-sm"
                                                            : "text-muted-foreground hover:text-foreground"
                                                    )}
                                                >
                                                    {t('sgipsLogin')}
                                                </button>
                                            )}
                                        </div>

                                        {/* Username Login Form */}
                                        {loginMethod === 'username' && (
                                            <form onSubmit={handleUsernameLogin} className="grid gap-4">
                                                <div className="grid gap-2">
                                                    <Input
                                                        id="username"
                                                        type="text"
                                                        placeholder={t('emailPlaceholder')}
                                                        required
                                                        className="h-10"
                                                        value={username}
                                                        onChange={(e) => setUsername(e.target.value)}
                                                        disabled={isFirstAuthLoading}
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <Input
                                                        id="password"
                                                        type="password"
                                                        placeholder={t('password')}
                                                        required
                                                        className="h-10"
                                                        value={password}
                                                        onChange={(e) => setPassword(e.target.value)}
                                                        disabled={isFirstAuthLoading}
                                                    />
                                                </div>
                                                <Button
                                                    type="submit"
                                                    className="w-full"
                                                    variant="samsung"
                                                    disabled={isFirstAuthLoading || !username || !password}
                                                >
                                                    {isFirstAuthLoading ? t('authenticating') : t('login')}
                                                </Button>
                                            </form>
                                        )}

                                        {/* S-Gips Login Form - 영문 페이지에서 비활성화 0925 구매 요청사항*/}
                                        {loginMethod === 'sgips' && lng !== 'en' && (
                                            <form onSubmit={handleSgipsLogin} className="grid gap-4">
                                                <div className="grid gap-2">
                                                    <Input
                                                        id="sgipsUsername"
                                                        type="text"
                                                        placeholder={t('sgipsId')}
                                                        required
                                                        className="h-10"
                                                        value={sgipsUsername}
                                                        onChange={(e) => setSgipsUsername(e.target.value)}
                                                        disabled={isFirstAuthLoading}
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <Input
                                                        id="sgipsPassword"
                                                        type="password"
                                                        placeholder={t('sgipsPassword')}
                                                        required
                                                        className="h-10"
                                                        value={sgipsPassword}
                                                        onChange={(e) => setSgipsPassword(e.target.value)}
                                                        disabled={isFirstAuthLoading}
                                                    />
                                                </div>
                                                <Button
                                                    type="submit"
                                                    className="w-full"
                                                    variant="default"
                                                    disabled={isFirstAuthLoading || !sgipsUsername || !sgipsPassword}
                                                >
                                                    {isFirstAuthLoading ? t('sgipsAuthenticating') : t('sgipsLogin')}
                                                </Button>
                                                <p className="text-xs text-muted-foreground text-center">
                                                    {t('sgipsAutoSms')}
                                                </p>
                                            </form>
                                        )}

                                        {/* Additional Links */}
                                        <div className="flex flex-col gap-2 text-center">
                                            <Button
                                                type="button"
                                                variant="link"
                                                className="text-blue-600 hover:text-blue-800 text-sm"
                                                onClick={goToVendorRegistration}
                                            >
                                                {t('newVendor')}
                                            </Button>

                                            {loginMethod === 'username' && (
                                                <Button
                                                    type="button"
                                                    variant="link"
                                                    className="text-blue-600 hover:text-blue-800 text-sm"
                                                    onClick={() => setShowForgotPassword(true)}
                                                >
                                                    {t('forgotPassword')}
                                                </Button>
                                            )}
                                        </div>
                                    </>
                                ) : (
                                    /* MFA 입력 폼 */
                                    <div className="space-y-6">
                                        {/* 뒤로 가기 버튼 */}
                                        <div className="flex items-center justify-start">
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                size="sm"
                                                onClick={handleBackToLogin}
                                                className="text-blue-600 hover:text-blue-800"
                                            >
                                                <ArrowLeft className="w-4 h-4 mr-1" />
                                                {t('backToLogin')}
                                            </Button>
                                        </div>

                                        {/* SMS 재전송 섹션 */}
                                        <div className="bg-gray-50 p-4 rounded-lg">
                                            <h3 className="text-sm font-medium text-gray-900 mb-2">
                                                {t('resendCode')}
                                            </h3>
                                            <p className="text-xs text-gray-600 mb-3">
                                                {t('didNotReceiveCode')}
                                            </p>
                                            <Button
                                                onClick={() => handleSendSms()}
                                                disabled={isSmsLoading || mfaCountdown > 0}
                                                variant="outline"
                                                size="sm"
                                                className="w-full"
                                                type="button"
                                            >
                                                {isSmsLoading ? (
                                                    t('sending')
                                                ) : mfaCountdown > 0 ? (
                                                    t('resendAvailable', { seconds: mfaCountdown })
                                                ) : (
                                                    t('resendCode')
                                                )}
                                            </Button>
                                        </div>

                                        {/* SMS 토큰 입력 폼 */}
                                        <form onSubmit={handleMfaSubmit} className="space-y-6">
                                            <div className="space-y-4">
                                                <div className="text-center">
                                                    <label className="block text-sm font-medium text-gray-700 mb-3">
                                                        {t('enterSixDigitCode')}
                                                    </label>
                                                    <div className="flex justify-center">
                                                        <InputOTP
                                                            maxLength={6}
                                                            value={mfaToken}
                                                            onChange={(value) => setMfaToken(value)}
                                                        >
                                                            <InputOTPGroup>
                                                                <InputOTPSlot index={0} />
                                                                <InputOTPSlot index={1} />
                                                                <InputOTPSlot index={2} />
                                                                <InputOTPSlot index={3} />
                                                                <InputOTPSlot index={4} />
                                                                <InputOTPSlot index={5} />
                                                            </InputOTPGroup>
                                                        </InputOTP>
                                                    </div>
                                                </div>
                                            </div>

                                            <Button
                                                type="submit"
                                                className="w-full"
                                                variant="samsung"
                                                disabled={isMfaLoading || mfaToken.length !== 6}
                                            >
                                                {isMfaLoading ? t('authenticating') : t('authenticationComplete')}
                                            </Button>
                                        </form>

                                        {/* 도움말 */}
                                        <div className="bg-yellow-50 p-3 rounded-lg border border-yellow-200">
                                            <div className="flex">
                                                <div className="flex-shrink-0">
                                                    ⚠️
                                                </div>
                                                <div className="ml-2">
                                                    <h4 className="text-xs font-medium text-yellow-800">
                                                        {t('didNotReceiveCode')}
                                                    </h4>
                                                    <div className="mt-1 text-xs text-yellow-700">
                                                        <ul className="list-disc list-inside space-y-1">
                                                            <li>{t('checkPhoneNumber')}</li>
                                                            <li>{t('checkSpamFolder')}</li>
                                                            <li>{t('useResendButton')}</li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* 비밀번호 재설정 다이얼로그 */}
                                {showForgotPassword && !showMfaForm && (
                                    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                                        <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
                                            <div className="flex justify-between items-center mb-4">
                                                <h3 className="text-lg font-semibold">{t('resetPassword')}</h3>
                                                <button
                                                    onClick={() => {
                                                        setShowForgotPassword(false);
                                                    }}
                                                    className="text-gray-400 hover:text-gray-600"
                                                >
                                                    ✕
                                                </button>
                                            </div>
                                            <form action={passwordResetAction} className="space-y-4">
                                                <div>
                                                    <p className="text-sm text-gray-600 mb-3">
                                                        {t('resetDescription')}
                                                    </p>
                                                    <Input
                                                        name="email"
                                                        type="email"
                                                        placeholder={t('emailAddress')}
                                                        required
                                                    />
                                                </div>
                                                <div className="flex gap-2">
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        className="flex-1"
                                                        onClick={() => {
                                                            setShowForgotPassword(false);
                                                        }}
                                                    >
                                                        {t('cancel')}
                                                    </Button>
                                                    <Button
                                                        type="submit"
                                                        className="flex-1"
                                                    >
                                                        {t('sendResetLink')}
                                                    </Button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                )}

                                {/* Language Selector - MFA 화면에서는 숨김 */}
                                {!showMfaForm && (
                                    <div className="text-center text-sm mx-auto">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" className="flex items-center gap-2">
                                                    <GlobeIcon className="h-4 w-4" />
                                                    <span>{currentLanguageText}</span>
                                                    <ChevronDownIcon className="h-4 w-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuRadioGroup
                                                    value={i18n.language}
                                                    onValueChange={(value) => handleChangeLanguage(value)}
                                                >
                                                    <DropdownMenuRadioItem value="en">
                                                        {t('languages.english')}
                                                    </DropdownMenuRadioItem>
                                                    <DropdownMenuRadioItem value="ko">
                                                        {t('languages.korean')}
                                                    </DropdownMenuRadioItem>
                                                </DropdownMenuRadioGroup>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Terms - MFA 화면에서는 숨김 */}
                        {!showMfaForm && (
                            <div className="text-balance text-center text-xs text-muted-foreground [&_a]:underline [&_a]:underline-offset-4 hover:[&_a]:text-primary">
                                {t("agreement")}{" "}
                                <Link
                                    href={`/${lng}/privacy`}
                                    className="underline underline-offset-4 hover:text-primary"
                                >
                                    {t("privacyPolicy")}
                                </Link>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Right BG 이미지 영역 */}
            <div className="relative hidden h-full flex-col p-10 text-white dark:border-r md:flex">
                <div className="absolute inset-0">
                    <Image
                        src="/images/02.jpg"
                        alt="Background image"
                        fill
                        priority
                        sizes="(max-width: 1024px) 100vw, 50vw"
                        className="object-cover"
                    />
                </div>
                <div className="relative z-10 mt-auto">
                    <blockquote className="space-y-2">
                        <p className="text-sm">&ldquo;{t("blockquote")}&rdquo;</p>
                    </blockquote>
                </div>
            </div>
        </div>
    )
}