import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

type AuthStep = 'email' | 'otp' | 'password-fallback';

const ModernLogin: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const { inviteCode: routeInviteCode } = useParams<{ inviteCode: string }>();

    // Auth state
    const { signInWithGoogle, signInWithEmail, signUpWithEmail, user, loading, sendOTP: authSendOTP, verifyOTP: authVerifyOTP } = useAuth();

    // Form state
    const [step, setStep] = useState<AuthStep>('email');
    const [email, setEmail] = useState('');
    const [otp, setOtp] = useState(['', '', '', '', '', '']);
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [inviteCode, setInviteCode] = useState<string | null>(null);
    const [resendCooldown, setResendCooldown] = useState(0);
    const [demoOTP, setDemoOTP] = useState<string | null>(null);

    // Extract invite code from URL
    useEffect(() => {
        if (routeInviteCode) {
            setInviteCode(routeInviteCode);
        } else {
            const hashSearch = location.hash.includes('?') ? location.hash.split('?')[1] : '';
            const searchParams = new URLSearchParams(hashSearch);
            const queryInvite = searchParams.get('invite');
            if (queryInvite) {
                setInviteCode(queryInvite);
            }
        }
    }, [routeInviteCode, location]);

    // Handle successful authentication
    useEffect(() => {
        if (user && !loading) {
            if (inviteCode) {
                navigate(`/org-selection?invite=${inviteCode}`, { replace: true });
            } else {
                navigate('/org-selection', { replace: true });
            }
        }
    }, [user, loading, navigate, inviteCode]);

    // Resend cooldown timer
    useEffect(() => {
        if (resendCooldown > 0) {
            const timer = setTimeout(() => setResendCooldown(resendCooldown - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [resendCooldown]);

    const sendOTP = async (emailAddress: string) => {
        try {
            setIsLoading(true);
            setError('');
            setDemoOTP(null);

            // Call auth context method
            const response = await authSendOTP(emailAddress, inviteCode || undefined);

            // If OTP is returned in response (demo mode), display it
            if (response.otp) {
                setDemoOTP(response.otp);
            }

            setStep('otp');
            setResendCooldown(60); // 60 second cooldown

        } catch (err) {
            console.error('OTP send error:', err);
            setError(err instanceof Error ? err.message : 'Failed to send verification code. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    const verifyOTP = async () => {
        try {
            setIsLoading(true);
            setError('');

            const otpCode = otp.join('');
            if (otpCode.length !== 6) return;

            // Call auth context method
            await authVerifyOTP(email, otpCode, inviteCode || undefined);

            // Success - user will be set in auth context and useEffect will handle navigation

        } catch (err) {
            console.error('OTP verification error:', err);
            setError(err instanceof Error ? err.message : 'Invalid verification code. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    const handleOtpChange = (index: number, value: string) => {
        if (value.length <= 1 && /^\d*$/.test(value)) {
            const newOtp = [...otp];
            newOtp[index] = value;
            setOtp(newOtp);

            // Auto-focus next input
            if (value && index < 5) {
                const nextInput = document.getElementById(`otp-${index + 1}`);
                nextInput?.focus();
            }
        }
    };

    const handleOtpKeyDown = (index: number, e: React.KeyboardEvent) => {
        if (e.key === 'Backspace' && !otp[index] && index > 0) {
            const prevInput = document.getElementById(`otp-${index - 1}`);
            prevInput?.focus();
        }
    };

    const handleEmailSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!email.trim()) return;

        await sendOTP(email);
    };

    const handleOTPSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        const otpCode = otp.join('');
        if (otpCode.length !== 6) return;

        await verifyOTP();
    };

    const handlePasswordFallback = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!password.trim()) return;

        try {
            setIsLoading(true);
            setError('');

            // Try login first, then signup if user doesn't exist
            try {
                await signInWithEmail(email, password);
            } catch (loginError) {
                // If login fails, try creating account
                await signUpWithEmail(email, password, email.split('@')[0]);
            }
        } catch (err) {
            console.error('Password auth error:', err);
            setError(err instanceof Error ? err.message : 'Authentication failed');
        } finally {
            setIsLoading(false);
        }
    };

    const handleGoogleAuth = async () => {
        try {
            setIsLoading(true);
            setError('');
            await signInWithGoogle();
        } catch (err) {
            console.error('Google auth error:', err);
            setError('Google authentication failed. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    // Figma Email Login Step (Empty State)
    const renderEmailStep = () => {
        const hasEmail = email.trim().length > 0;

        return (
            <div className="w-[1440px] h-[810px] bg-[--Neutrals-NeutralSlate0] inline-flex justify-start items-end overflow-hidden">
                <div className="flex-1 self-stretch px-32 py-48 flex justify-center items-center gap-2.5 overflow-hidden">
                    <div className="flex-1 max-w-[464px] inline-flex flex-col justify-start items-start gap-6">
                        <div className="w-12 h-12 relative bg-[--Brand-Orange] rounded-xl outline outline-2 outline-offset-[-2px] outline-blue-400 overflow-hidden">
                            <div className="w-12 h-12 left-0 top-0 absolute bg-gradient-to-b from-white/0 to-white/10" />
                            <div data-svg-wrapper className="left-[12px] top-[9.33px] absolute">
                                <svg width="24" height="30" viewBox="0 0 24 30" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path opacity="0.5" fillRule="evenodd" clipRule="evenodd" d="M2.57425 17.8128C3.11852 18.3639 3.11851 19.2575 2.57423 19.8087L2.54635 19.8369C2.00207 20.3881 1.11963 20.3881 0.575357 19.8369C0.0310869 19.2857 0.0310953 18.3921 0.575376 17.841L0.603251 17.8128C1.14753 17.2616 2.02998 17.2616 2.57425 17.8128Z" fill="url(#paint0_linear_710_14140)" />
                                    <path opacity="0.7" fillRule="evenodd" clipRule="evenodd" d="M9.12599 18.2379C9.66928 18.7901 9.66769 19.6837 9.12243 20.2338L5.26187 24.1291C4.71661 24.6792 3.83416 24.6776 3.29087 24.1255C2.74758 23.5733 2.74918 22.6797 3.29444 22.1296L7.155 18.2343C7.70026 17.6842 8.5827 17.6858 9.12599 18.2379Z" fill="url(#paint1_linear_710_14140)" />
                                    <path opacity="0.5" fillRule="evenodd" clipRule="evenodd" d="M14.3654 24.9431C14.7924 24.2945 15.6577 24.1193 16.2981 24.5516L16.3817 24.6081C17.0222 25.0404 17.1953 25.9167 16.7683 26.5652C16.3413 27.2138 15.476 27.389 14.8356 26.9567L14.7519 26.9002C14.1115 26.4678 13.9384 25.5916 14.3654 24.9431Z" fill="url(#paint2_linear_710_14140)" />
                                    <path opacity="0.7" fillRule="evenodd" clipRule="evenodd" d="M23.5637 17.7278C24.108 18.279 24.108 19.1726 23.5637 19.7237L21.6683 21.6431C21.124 22.1943 20.2415 22.1943 19.6973 21.6431C19.153 21.092 19.153 20.1984 19.6973 19.6472L21.5927 17.7278C22.137 17.1767 23.0194 17.1767 23.5637 17.7278Z" fill="url(#paint3_linear_710_14140)" />
                                    <path fillRule="evenodd" clipRule="evenodd" d="M23.5922 10.6292C24.1364 11.1803 24.1364 12.0739 23.5922 12.6251L9.58543 26.8089C9.04115 27.36 8.15871 27.36 7.61443 26.8089C7.07015 26.2577 7.07015 25.3641 7.61443 24.8129L21.6212 10.6292C22.1654 10.078 23.0479 10.078 23.5922 10.6292Z" fill="url(#paint4_linear_710_14140)" />
                                    <path fillRule="evenodd" clipRule="evenodd" d="M20.9426 6.26835C21.4869 6.8195 21.4869 7.7131 20.9426 8.26425L12.887 16.4217C12.3427 16.9728 11.4603 16.9728 10.916 16.4217C10.3717 15.8705 10.3717 14.9769 10.916 14.4258L18.9716 6.26835C19.5159 5.71719 20.3984 5.71719 20.9426 6.26835Z" fill="url(#paint5_linear_710_14140)" />
                                    <path fillRule="evenodd" clipRule="evenodd" d="M16.6916 3.50156C17.2363 4.05235 17.2368 4.94594 16.6929 5.49747L6.33771 15.9977C5.7938 16.5492 4.91135 16.5498 4.36671 15.999C3.82207 15.4482 3.82147 14.5546 4.36538 14.0031L14.7206 3.5029C15.2645 2.95138 16.147 2.95078 16.6916 3.50156Z" fill="url(#paint6_linear_710_14140)" />
                                    <path opacity="0.7" fillRule="evenodd" clipRule="evenodd" d="M6.43658 6.86284C6.97992 7.41494 6.9784 8.30854 6.43319 8.85874L2.37751 12.9516C1.83229 13.5018 0.94985 13.5002 0.406512 12.9481C-0.136826 12.396 -0.135307 11.5024 0.409905 10.9522L4.46559 6.8594C5.0108 6.3092 5.89324 6.31074 6.43658 6.86284Z" fill="url(#paint7_linear_710_14140)" />
                                    <path opacity="0.5" fillRule="evenodd" clipRule="evenodd" d="M8.92024 2.77832C9.68996 2.77832 10.3139 3.41019 10.3139 4.18964V4.33077C10.3139 5.11022 9.68996 5.74209 8.92024 5.74209C8.15052 5.74209 7.52654 5.11022 7.52654 4.33077V4.18964C7.52654 3.41019 8.15052 2.77832 8.92024 2.77832Z" fill="url(#paint8_linear_710_14140)" />
                                    <defs>
                                        <linearGradient id="paint0_linear_710_14140" x1="1.5748" y1="17.3994" x2="1.5748" y2="20.2503" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint1_linear_710_14140" x1="6.20843" y1="17.8228" x2="6.20843" y2="24.5406" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint2_linear_710_14140" x1="15.5668" y1="24.3145" x2="15.5668" y2="27.1938" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint3_linear_710_14140" x1="21.6305" y1="17.3145" x2="21.6305" y2="22.0565" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint4_linear_710_14140" x1="15.6033" y1="10.2158" x2="15.6033" y2="27.2222" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint5_linear_710_14140" x1="15.9293" y1="5.85498" x2="15.9293" y2="16.835" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint6_linear_710_14140" x1="10.5292" y1="3.08887" x2="10.5292" y2="16.4117" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint7_linear_710_14140" x1="3.42155" y1="6.44775" x2="3.42155" y2="13.3632" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                        <linearGradient id="paint8_linear_710_14140" x1="8.92024" y1="2.77832" x2="8.92024" y2="5.74209" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                    </defs>
                                </svg>
                            </div>
                        </div>
                        <div className="self-stretch flex flex-col justify-start items-center gap-9">
                            <div className="self-stretch flex flex-col justify-start items-start gap-4">
                                <div className="self-stretch flex flex-col justify-start items-start gap-2">
                                    <div className="self-stretch justify-start text-[--Neutrals-NeutralSlate800] text-2xl font-medium font-['Neue_Montreal'] leading-normal">Welcome to Auditly.</div>
                                    <div className="self-stretch justify-start text-[--Neutrals-NeutralSlate400] text-2xl font-medium font-['Neue_Montreal'] leading-normal">The company intelligence tool.</div>
                                </div>
                                <div className="self-stretch justify-center text-[--Neutrals-NeutralSlate500] text-base font-normal font-['Inter'] leading-normal">Log in or create an account.</div>
                            </div>
                            <form onSubmit={handleEmailSubmit} className="self-stretch flex flex-col justify-start items-start gap-4">
                                <div className={`self-stretch px-4 py-3.5 ${hasEmail ? 'bg-[--Neutrals-NeutralSlate50]' : 'bg-[--Neutrals-NeutralSlate100]'} rounded-[999px] inline-flex justify-center items-center gap-2 overflow-hidden`}>
                                    <div data-svg-wrapper className="relative">
                                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <g clipPath="url(#clip0_733_12018)">
                                                <path d="M19.8052 10.2302C19.8052 9.55044 19.7501 8.86699 19.6325 8.19824H10.2002V12.0491H15.6016C15.3775 13.291 14.6573 14.3897 13.6027 15.0878V17.5864H16.8252C18.7176 15.8448 19.8052 13.2726 19.8052 10.2302Z" fill="#4285F4" />
                                                <path d="M10.2 20.0008C12.897 20.0008 15.1715 19.1152 16.8287 17.5867L13.6062 15.088C12.7096 15.698 11.5522 16.0434 10.2037 16.0434C7.5948 16.0434 5.38279 14.2833 4.58911 11.917H1.26373V14.4928C2.96133 17.8696 6.41898 20.0008 10.2 20.0008Z" fill="#34A853" />
                                                <path d="M4.58564 11.9168C4.16676 10.6748 4.16676 9.32995 4.58564 8.08799V5.51221H1.26395C-0.154389 8.33785 -0.154389 11.6669 1.26395 14.4925L4.58564 11.9168Z" fill="#FBBC04" />
                                                <path d="M10.2 3.95805C11.6257 3.936 13.0036 4.47247 14.0361 5.45722L16.8911 2.60218C15.0833 0.904587 12.6839 -0.0287217 10.2 0.000673888C6.41898 0.000673888 2.96133 2.13185 1.26373 5.51234L4.58543 8.08813C5.37544 5.71811 7.59113 3.95805 10.2 3.95805Z" fill="#EA4335" />
                                            </g>
                                            <defs>
                                                <clipPath id="clip0_733_12018">
                                                    <rect width="20" height="20" fill="white" />
                                                </clipPath>
                                            </defs>
                                        </svg>
                                    </div>
                                    <div className="justify-center text-[--Neutrals-NeutralSlate800] text-sm font-medium font-['Inter'] leading-tight cursor-pointer" onClick={handleGoogleAuth}>Continue with Google</div>
                                </div>
                                <div className="self-stretch inline-flex justify-center items-center gap-3">
                                    <div className="flex-1 h-0 outline outline-1 outline-offset-[-0.50px] outline-[--$1]"></div>
                                    <div className="justify-start text-[--Neutrals-NeutralSlate400] text-sm font-normal font-['Inter'] leading-tight">or</div>
                                    <div className="flex-1 h-0 outline outline-1 outline-offset-[-0.50px] outline-[--$1]"></div>
                                </div>
                                <div className="self-stretch flex flex-col justify-center items-end gap-2">
                                    <div className="self-stretch inline-flex justify-end items-end gap-2">
                                        <div data-property-1="Default" data-show-hint="false" data-show-icon-left="true" data-show-icon-right="false" data-show-label="true" data-show-mandatory="false" className="flex-1 inline-flex flex-col justify-start items-start gap-2">
                                            <div className="self-stretch inline-flex justify-start items-center gap-0.5">
                                                <div className="justify-start text-[--Neutrals-NeutralSlate900] text-sm font-normal font-['Inter'] leading-tight">Email</div>
                                            </div>
                                            <div className="self-stretch flex flex-col justify-start items-start gap-1">
                                                <div className="self-stretch px-4 py-3.5 bg-[--Neutrals-NeutralSlate100] rounded-[999px] inline-flex justify-start items-center gap-2 overflow-hidden">
                                                    <div data-svg-wrapper className="relative">
                                                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <path d="M1.66667 5.8335L8.47077 10.5964C9.02175 10.982 9.29724 11.1749 9.59689 11.2496C9.86158 11.3156 10.1384 11.3156 10.4031 11.2496C10.7028 11.1749 10.9783 10.982 11.5292 10.5964L18.3333 5.8335M5.66667 16.6668H14.3333C15.7335 16.6668 16.4335 16.6668 16.9683 16.3943C17.4387 16.1547 17.8212 15.7722 18.0609 15.3018C18.3333 14.767 18.3333 14.067 18.3333 12.6668V7.3335C18.3333 5.93336 18.3333 5.2333 18.0609 4.69852C17.8212 4.22811 17.4387 3.84566 16.9683 3.60598C16.4335 3.3335 15.7335 3.3335 14.3333 3.3335H5.66667C4.26654 3.3335 3.56647 3.3335 3.0317 3.60598C2.56129 3.84566 2.17884 4.22811 1.93916 4.69852C1.66667 5.2333 1.66667 5.93336 1.66667 7.3335V12.6668C1.66667 14.067 1.66667 14.767 1.93916 15.3018C2.17884 15.7722 2.56129 16.1547 3.0317 16.3943C3.56647 16.6668 4.26654 16.6668 5.66667 16.6668Z" stroke={hasEmail ? "var(--Brand-Orange, #3399FF)" : "var(--Neutrals-NeutralSlate500, #717680)"} strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round" />
                                                        </svg>
                                                    </div>
                                                    <input
                                                        type="email"
                                                        value={email}
                                                        onChange={(e) => setEmail(e.target.value)}
                                                        placeholder="Enter your email"
                                                        className={`flex-1 justify-start text-sm font-normal font-['Inter'] leading-tight bg-transparent outline-none ${hasEmail ? 'text-[--Neutrals-NeutralSlate950]' : 'text-[--Neutrals-NeutralSlate500]'}`}
                                                        required
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                        <button
                                            type="submit"
                                            disabled={isLoading || !email.trim()}
                                            className={`${hasEmail && !isLoading ?
                                                'w-32 px-4 py-3.5 bg-[--Brand-Orange] rounded-[999px] outline outline-2 outline-offset-[-2px] outline-blue-400 flex justify-center items-center gap-1 overflow-hidden' :
                                                'px-7 py-3.5 bg-[--Neutrals-NeutralSlate100] rounded-[999px] flex justify-center items-center gap-1 overflow-hidden'
                                                } transition-all duration-200`}
                                        >
                                            <div className="px-1 flex justify-center items-center">
                                                <div className={`justify-center text-sm font-medium font-['Inter'] leading-tight ${hasEmail && !isLoading ? 'text-white' : 'text-[--Neutrals-NeutralSlate500]'}`}>
                                                    {isLoading ? 'Sending...' : 'Continue'}
                                                </div>
                                            </div>
                                        </button>
                                    </div>
                                </div>

                                {error && (
                                    <div className="self-stretch text-red-600 text-sm bg-red-50 border border-red-200 p-3 rounded-lg">
                                        {error}
                                    </div>
                                )}

                                {/* Password fallback link */}
                                <div className="self-stretch text-center">
                                    <button
                                        type="button"
                                        onClick={() => setStep('password-fallback')}
                                        className="text-sm text-[--Neutrals-NeutralSlate500] hover:text-[--Neutrals-NeutralSlate700] transition-colors"
                                    >
                                        Use password instead
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div className="flex-1 self-stretch px-20 py-16 flex justify-center items-center gap-2.5 overflow-hidden">
                    <img className="flex-1 self-stretch rounded-3xl" src="/image/login-robot.png" alt="Login illustration" />
                </div>
            </div>
        );
    };

    // Figma OTP Verification Step
    const renderOTPStep = () => {
        const allOtpFilled = otp.every(digit => digit !== '');

        return (
            <div className="w-[1440px] h-[810px] bg-[--Neutrals-NeutralSlate0] inline-flex justify-start items-end overflow-hidden">
                <div className="flex-1 self-stretch px-32 py-48 flex justify-center items-center gap-2.5 overflow-hidden">
                    <div className="flex-1 max-w-[464px] inline-flex flex-col justify-start items-start gap-6">
                        <div className="w-12 h-12 relative bg-[--Brand-Orange] rounded-xl outline outline-2 outline-offset-[-2px] outline-blue-400 overflow-hidden">
                            <div className="w-12 h-12 left-0 top-0 absolute bg-gradient-to-b from-white/0 to-white/10" />
                            <div data-svg-wrapper className="left-[12px] top-[12px] absolute">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M2 7L10.1649 12.7154C10.8261 13.1783 11.1567 13.4097 11.5163 13.4993C11.8339 13.5785 12.1661 13.5785 12.4837 13.4993C12.8433 13.4097 13.1739 13.1783 13.8351 12.7154L22 7M6.8 20H17.2C18.8802 20 19.7202 20 20.362 19.673C20.9265 19.3854 21.3854 18.9265 21.673 18.362C22 17.7202 22 16.8802 22 15.2V8.8C22 7.11984 22 6.27976 21.673 5.63803C21.3854 5.07354 20.9265 4.6146 20.362 4.32698C19.7202 4 18.8802 4 17.2 4H6.8C5.11984 4 4.27976 4 3.63803 4.32698C3.07354 4.6146 2.6146 5.07354 2.32698 5.63803C2 6.27976 2 7.11984 2 8.8V15.2C2 16.8802 2 17.7202 2.32698 18.362C2.6146 18.9265 3.07354 19.3854 3.63803 19.673C4.27976 20 5.11984 20 6.8 20Z" stroke="url(#paint0_linear_733_12987)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                    <defs>
                                        <linearGradient id="paint0_linear_733_12987" x1="12" y1="4" x2="12" y2="20" gradientUnits="userSpaceOnUse">
                                            <stop stopColor="white" stopOpacity="0.8" />
                                            <stop offset="1" stopColor="white" stopOpacity="0.5" />
                                        </linearGradient>
                                    </defs>
                                </svg>
                            </div>
                        </div>
                        <div className="self-stretch flex flex-col justify-center items-start gap-6">
                            <div className="self-stretch flex flex-col justify-start items-start gap-4">
                                <div className="self-stretch flex flex-col justify-start items-start gap-2">
                                    <div className="self-stretch justify-start text-[--Neutrals-NeutralSlate800] text-2xl font-medium font-['Neue_Montreal'] leading-normal">Check your email.</div>
                                    <div className="self-stretch justify-start text-[--Neutrals-NeutralSlate400] text-2xl font-medium font-['Neue_Montreal'] leading-normal">We've sent you a code.</div>
                                </div>
                                <div className="self-stretch justify-center">
                                    <span className="text-[--Neutrals-NeutralSlate500] text-base font-normal font-['Inter'] leading-normal">Didn't receive code? </span>
                                    <button
                                        onClick={() => sendOTP(email)}
                                        disabled={resendCooldown > 0 || isLoading}
                                        className="text-[--Neutrals-NeutralSlate500] text-base font-medium font-['Inter'] leading-normal hover:text-[--Neutrals-NeutralSlate700] transition-colors disabled:opacity-50"
                                    >
                                        {resendCooldown > 0 ? `Resend in ${resendCooldown}s` : 'Resend'}
                                    </button>
                                    <span className="text-[--Neutrals-NeutralSlate500] text-base font-normal font-['Inter'] leading-normal">.</span>
                                </div>
                            </div>
                            <form onSubmit={handleOTPSubmit} className="self-stretch flex flex-col gap-6">
                                <div className="self-stretch inline-flex justify-start items-start gap-3">
                                    {otp.map((digit, index) => (
                                        <div key={index} data-pin-state="Default" className="flex-1 px-2 py-3.5 bg-[--Neutrals-NeutralSlate100] rounded-[999px] shadow-[0px_1px_2px_0px_rgba(10,13,20,0.03)] flex justify-center items-center gap-2 overflow-hidden">
                                            <input
                                                id={`otp-${index}`}
                                                type="text"
                                                value={digit}
                                                onChange={(e) => handleOtpChange(index, e.target.value)}
                                                onKeyDown={(e) => handleOtpKeyDown(index, e)}
                                                className={`flex-1 text-center justify-start text-sm font-medium font-['Inter'] leading-tight bg-transparent outline-none ${digit ? 'text-[--Neutrals-NeutralSlate800]' : 'text-[--Neutrals-NeutralSlate500]'}`}
                                                maxLength={1}
                                            />
                                        </div>
                                    ))}
                                </div>

                                {demoOTP && (
                                    <div className="bg-[--Neutrals-NeutralSlate50] border border-[--Brand-Orange] rounded-xl p-4">
                                        <div className="text-yellow-800 text-sm text-center">
                                            <div className="flex items-center justify-center mb-2">
                                                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                                                </svg>
                                                <strong>Demo Mode</strong>
                                            </div>
                                            Your verification code is <strong className="text-2xl font-mono bg-yellow-100 px-2 py-1 rounded">{demoOTP}</strong>
                                        </div>
                                    </div>
                                )}

                                {error && (
                                    <div className="text-red-600 text-sm bg-red-50 border border-red-200 p-3 rounded-lg">
                                        {error}
                                    </div>
                                )}

                                <button
                                    type="submit"
                                    disabled={isLoading || !allOtpFilled}
                                    className={`self-stretch px-7 py-3.5 rounded-[999px] inline-flex justify-center items-center gap-1 overflow-hidden transition-all duration-200 ${allOtpFilled && !isLoading ?
                                        'bg-[--Brand-Orange] outline outline-2 outline-offset-[-2px] outline-blue-400' :
                                        'bg-[--Neutrals-NeutralSlate100]'
                                        }`}
                                >
                                    <div className="px-1 flex justify-center items-center">
                                        <div className={`justify-center text-sm font-medium font-['Inter'] leading-tight ${allOtpFilled && !isLoading ? 'text-white' : 'text-[--Neutrals-NeutralSlate500]'
                                            }`}>
                                            {isLoading ? 'Verifying...' : 'Continue'}
                                        </div>
                                    </div>
                                </button>

                                <div className="self-stretch text-center">
                                    <button
                                        type="button"
                                        onClick={() => { setStep('email'); setError(''); setOtp(['', '', '', '', '', '']); }}
                                        className="text-sm text-[--Neutrals-NeutralSlate500] hover:text-[--Neutrals-NeutralSlate700] transition-colors"
                                    >
                                        ← Change email address
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div className="flex-1 self-stretch px-20 py-16 flex justify-center items-center gap-2.5 overflow-hidden">
                    <img className="w-[560px] self-stretch rounded-3xl" src="/image/login-robot.png" alt="Login illustration" />
                </div>
            </div>
        );
    };

    // Password Fallback Step
    const renderPasswordStep = () => (
        <div className="w-[1440px] h-[810px] bg-[--Neutrals-NeutralSlate0] inline-flex justify-start items-end overflow-hidden">
            <div className="flex-1 self-stretch px-32 py-48 flex justify-center items-center gap-2.5 overflow-hidden">
                <div className="flex-1 max-w-[464px] inline-flex flex-col justify-start items-start gap-6">
                    <div className="w-12 h-12 relative bg-[--Brand-Orange] rounded-xl outline outline-2 outline-offset-[-2px] outline-blue-400 overflow-hidden">
                        <div className="w-12 h-12 left-0 top-0 absolute bg-gradient-to-b from-white/0 to-white/10" />
                        <div data-svg-wrapper className="left-[12px] top-[12px] absolute">
                            <svg className="w-6 h-6 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>
                    </div>
                    <div className="self-stretch flex flex-col justify-start items-center gap-9">
                        <div className="self-stretch flex flex-col justify-start items-start gap-4">
                            <div className="self-stretch flex flex-col justify-start items-start gap-2">
                                <div className="self-stretch justify-start text-[--Neutrals-NeutralSlate800] text-2xl font-medium font-['Neue_Montreal'] leading-normal">Sign in with password.</div>
                                <div className="self-stretch justify-start text-[--Neutrals-NeutralSlate400] text-2xl font-medium font-['Neue_Montreal'] leading-normal">Enter your password for {email}.</div>
                            </div>
                        </div>
                        <form onSubmit={handlePasswordFallback} className="self-stretch flex flex-col justify-start items-start gap-4">
                            <div className="self-stretch flex flex-col justify-center items-end gap-2">
                                <div className="self-stretch inline-flex justify-end items-end gap-2">
                                    <div className="flex-1 inline-flex flex-col justify-start items-start gap-2">
                                        <div className="self-stretch inline-flex justify-start items-center gap-0.5">
                                            <div className="justify-start text-[--Neutrals-NeutralSlate900] text-sm font-normal font-['Inter'] leading-tight">Password</div>
                                        </div>
                                        <div className="self-stretch flex flex-col justify-start items-start gap-1">
                                            <div className="self-stretch px-4 py-3.5 bg-[--Neutrals-NeutralSlate100] rounded-[999px] inline-flex justify-start items-center gap-2 overflow-hidden">
                                                <input
                                                    type="password"
                                                    value={password}
                                                    onChange={(e) => setPassword(e.target.value)}
                                                    placeholder="Enter your password"
                                                    className="flex-1 justify-start text-[--Neutrals-NeutralSlate950] text-sm font-normal font-['Inter'] leading-tight bg-transparent outline-none"
                                                    required
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <button
                                        type="submit"
                                        disabled={isLoading || !password.trim()}
                                        className={`px-7 py-3.5 rounded-[999px] flex justify-center items-center gap-1 overflow-hidden transition-all duration-200 ${password.trim() && !isLoading ?
                                            'bg-[--Brand-Orange] outline outline-2 outline-offset-[-2px] outline-blue-400' :
                                            'bg-[--Neutrals-NeutralSlate100]'
                                            }`}
                                    >
                                        <div className="px-1 flex justify-center items-center">
                                            <div className={`justify-center text-sm font-medium font-['Inter'] leading-tight ${password.trim() && !isLoading ? 'text-white' : 'text-[--Neutrals-NeutralSlate500]'
                                                }`}>
                                                {isLoading ? 'Signing in...' : 'Sign In'}
                                            </div>
                                        </div>
                                    </button>
                                </div>
                            </div>

                            {error && (
                                <div className="self-stretch text-red-600 text-sm bg-red-50 border border-red-200 p-3 rounded-lg">
                                    {error}
                                </div>
                            )}

                            <div className="self-stretch text-center">
                                <button
                                    type="button"
                                    onClick={() => { setStep('email'); setError(''); setPassword(''); }}
                                    className="text-sm text-[--Neutrals-NeutralSlate500] hover:text-[--Neutrals-NeutralSlate700] transition-colors"
                                >
                                    ← Back to email verification
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div className="flex-1 self-stretch px-20 py-16 flex justify-center items-center gap-2.5 overflow-hidden">
                <img className="flex-1 self-stretch rounded-3xl" src="/image/login-robot.png" alt="Login illustration" />
            </div>
        </div>
    );

    if (loading) {
        return (
            <div className="w-[1440px] h-[810px] bg-[--Neutrals-NeutralSlate0] flex items-center justify-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-Brand-Orange"></div>
            </div>
        );
    }

    return (
        <div className="flex justify-center items-center min-h-screen bg-[--Neutrals-NeutralSlate0]">
            {step === 'email' && renderEmailStep()}
            {step === 'otp' && renderOTPStep()}
            {step === 'password-fallback' && renderPasswordStep()}
        </div>
    );
};

export default ModernLogin;