'use client'

import { createPortal } from 'react-dom'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BsXLg } from 'react-icons/bs'
import { FaEye, FaEyeSlash } from 'react-icons/fa'
import { FaXmark } from 'react-icons/fa6'

type TabKey = 'login' | 'register'

type Props = {
    open: boolean
    tab: TabKey
    onTabChange: (tab: TabKey) => void
    onClose: () => void
}

function cx(...classes: Array<string | false | null | undefined>) {
    return classes.filter(Boolean).join(' ')
}

function isValidUserId(id: string) {
    const s = id.trim()
    if (s.length < 6 || s.length > 12) return false
    return /^[A-Za-z0-9]+$/.test(s)
}

function isValidEmail(email: string) {
    const s = email.trim()
    if (!s.includes('@')) return false
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)
}

function countPasswordKinds(pw: string) {
    const hasLetter = /[A-Za-z]/.test(pw)
    const hasDigit = /\d/.test(pw)
    const hasSpecial = /[^A-Za-z0-9]/.test(pw)
    return Number(hasLetter) + Number(hasDigit) + Number(hasSpecial)
}

function hasTripleSame(pw: string) {
    return /(.)\1\1/.test(pw)
}

function hasSequentialRun(pw: string) {
    const s = pw
    for (let i = 0; i + 2 < s.length; i++) {
        const a = s.charCodeAt(i)
        const b = s.charCodeAt(i + 1)
        const c = s.charCodeAt(i + 2)
        if (b === a + 1 && c === b + 1) return true
        if (b === a - 1 && c === b - 1) return true
    }
    return false
}

function validatePassword(pw: string, userId: string) {
    const s = pw
    const lengthOk = s.length >= 10 && s.length <= 15
    const comboOk = countPasswordKinds(s) >= 2
    const noTriple = !hasTripleSame(s) && !hasSequentialRun(s)
    const noSpaceAmp = !/\s/.test(s) && !s.includes('&')
    const noId = userId.trim().length >= 3 ? !s.toLowerCase().includes(userId.trim().toLowerCase()) : true
    const ok = lengthOk && comboOk && noTriple && noSpaceAmp && noId
    return { ok, lengthOk, comboOk, noTriple, noSpaceAmp, noId }
}

const EMAIL_DOMAINS = [
    'gmail.com',
    'yahoo.com',
    'yahoo.com.tw',
    'hotmail.com',
    'outlook.com',
    'live.com',
    'icloud.com',
    'proton.me',
    'protonmail.com',
    'qq.com',
    '163.com',
    'mail.ru',
]

function CircleCloseButton({ onClick, ariaLabel }: { onClick: () => void; ariaLabel: string }) {
    return (
        <button
            type="button"
            className="w-9 h-9 rounded-full hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] flex items-center justify-center"
            onClick={onClick}
            aria-label={ariaLabel}
        >
            <BsXLg className="w-4 h-4 text-gray-700 dark:text-gray-200" />
        </button>
    )
}

export default function AuthModal({ open, tab, onTabChange, onClose }: Props) {
    const { t } = useTranslation()
    // Refs
    const closeTimerRef = useRef<number | null>(null)
    const prevOpenRef = useRef<boolean>(false)

    // States
    const [mounted, setMounted] = useState(false)
    const [closing, setClosing] = useState(false)
    const [loginUid, setLoginUid] = useState('')
    const [loginPw, setLoginPw] = useState('')
    const [loginPwShow, setLoginPwShow] = useState(false)
    const [loginUidTouched, setLoginUidTouched] = useState(false)
    const [loginPwTouched, setLoginPwTouched] = useState(false)
    const [uid, setUid] = useState('')
    const [pw, setPw] = useState('')
    const [pw2, setPw2] = useState('')
    const [pwShow, setPwShow] = useState(false)
    const [email, setEmail] = useState('')
    const emailInputRef = useRef<HTMLInputElement | null>(null)
    const [emailSuggestOpen, setEmailSuggestOpen] = useState(false)
    const [emailSuggestActive, setEmailSuggestActive] = useState(0)
    const emailBlurTimerRef = useRef<number | null>(null)
    const [agreeTerms, setAgreeTerms] = useState(false)
    const [uidTouched, setUidTouched] = useState(false)
    const [pwTouched, setPwTouched] = useState(false)
    const [pw2Touched, setPw2Touched] = useState(false)
    const [emailTouched, setEmailTouched] = useState(false)

    const clearCloseTimer = useCallback(() => {
        if (closeTimerRef.current !== null) {
            window.clearTimeout(closeTimerRef.current)
            closeTimerRef.current = null
        }
    }, [])

    const requestClose = useCallback(() => {
        if (closing) return
        setClosing(true)
        clearCloseTimer()
        closeTimerRef.current = window.setTimeout(() => {
            onClose()
            setClosing(false)
            closeTimerRef.current = null
        }, 200)
    }, [clearCloseTimer, closing, onClose])

    const loginUidOk = useMemo(() => isValidUserId(loginUid), [loginUid])
    const loginOk = loginUidOk && loginPw.trim().length > 0

    const pass = useMemo(() => validatePassword(pw, uid), [pw, uid])
    const uidOk = useMemo(() => isValidUserId(uid), [uid])
    const emailOk = useMemo(() => isValidEmail(email), [email])
    const pw2Ok = pw2.length > 0 && pw2 === pw
    const registerOk = uidOk && pass.ok && pw2Ok && emailOk && agreeTerms

    const emailParts = useMemo(() => {
        const raw = email
        const at = raw.indexOf('@')
        if (at < 0) return { hasAt: false, local: raw, domain: '' }
        return { hasAt: true, local: raw.slice(0, at), domain: raw.slice(at + 1) }
    }, [email])

    const emailDomainSuggestions = useMemo(() => {
        if (!emailParts.hasAt) return []
        const local = emailParts.local.trim()
        if (!local) return []
        const typed = emailParts.domain.trim().toLowerCase()
        const list = EMAIL_DOMAINS.filter((d) => d.startsWith(typed)).slice(0, 8)
        return list
    }, [emailParts.domain, emailParts.hasAt, emailParts.local])

    useEffect(() => setMounted(true), [])

    useEffect(() => {
        if (!emailSuggestOpen) return
        if (emailSuggestActive >= emailDomainSuggestions.length) setEmailSuggestActive(0)
    }, [emailDomainSuggestions.length, emailSuggestActive, emailSuggestOpen])

    useEffect(() => {
        if (!open) return
        setLoginUid('')
        setLoginPw('')
        setLoginPwShow(false)
        setLoginUidTouched(false)
        setLoginPwTouched(false)
        setUid('')
        setPw('')
        setPw2('')
        setPwShow(false)
        setEmail('')
        setEmailSuggestOpen(false)
        setEmailSuggestActive(0)
        setAgreeTerms(false)
        setUidTouched(false)
        setPwTouched(false)
        setPw2Touched(false)
        setEmailTouched(false)
        setClosing(false)
        clearCloseTimer()
        const onKey = (e: KeyboardEvent) => {
            if (e.key === 'Escape') requestClose()
        }
        document.addEventListener('keydown', onKey)
        const prevOverflow = document.body.style.overflow
        document.body.style.overflow = 'hidden'
        return () => {
            document.removeEventListener('keydown', onKey)
            document.body.style.overflow = prevOverflow
        }
    }, [clearCloseTimer, open, requestClose])

    useEffect(() => {
        const prev = prevOpenRef.current
        prevOpenRef.current = open
        if (prev && !open) {
            setClosing(true)
            clearCloseTimer()
            closeTimerRef.current = window.setTimeout(() => {
                setClosing(false)
                closeTimerRef.current = null
            }, 200)
        }
    }, [clearCloseTimer, open])

    useEffect(() => {
        return () => {
            clearCloseTimer()
            if (emailBlurTimerRef.current !== null) {
                window.clearTimeout(emailBlurTimerRef.current)
                emailBlurTimerRef.current = null
            }
        }
    }, [clearCloseTimer])

    const headerTabBtn = useCallback(
        (k: TabKey, labelKey: string) => {
            const active = tab === k
            return (
                <button
                    key={k}
                    type="button"
                    onClick={() => onTabChange(k)}
                    className={cx(
                        'relative h-10 px-2 text-sm font-semibold',
                        active ? 'text-blue-600 dark:text-blue-400' : 'text-[#525661] dark:text-gray-300'
                    )}
                >
                    <span>{t(labelKey)}</span>
                    <span
                        className={cx(
                            'absolute left-0 right-0 -bottom-px h-0.5 transition-opacity',
                            active ? 'bg-blue-600 dark:bg-blue-400 opacity-100' : 'opacity-0'
                        )}
                    />
                </button>
            )
        },
        [onTabChange, tab, t]
    )

    const visible = open || closing
    const modal = (
        <div className={cx('fixed inset-0 z-[9999]', visible ? 'block' : 'hidden')} aria-hidden={!visible}>
            <div
                className={cx(
                    'absolute inset-0 bg-black/50 transition-opacity duration-200',
                    open && !closing ? 'opacity-100' : 'opacity-0'
                )}
                onMouseDown={requestClose}
            />
            <div className="absolute inset-0 overflow-y-auto">
                <div className="min-h-screen supports-[height:100svh]:min-h-[100svh] flex items-center justify-center px-4 py-10">
                    <div
                        className={cx(
                            'w-full max-w-[560px] rounded-2xl bg-white dark:bg-[#0c0d0e] shadow-2xl',
                            'border border-gray-200 dark:border-gray-800',
                            'transform-gpu transition-[opacity,transform] duration-200 ease-[cubic-bezier(0.56,0.12,0.12,0.98)]',
                            open && !closing ? 'opacity-100 scale-100 translate-y-0' : 'opacity-0 scale-95 translate-y-2'
                        )}
                        role="dialog"
                        aria-modal="true"
                        aria-label={t('authModal.title')}
                        onMouseDown={(e) => e.stopPropagation()}
                    >
                        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800">
                            <div className="flex items-center gap-4">
                                <div className="text-lg font-semibold text-gray-900 dark:text-white">{t('authModal.account')}</div>
                                <div className="flex items-end gap-2">
                                    {headerTabBtn('login', 'authModal.login')}
                                    {headerTabBtn('register', 'authModal.register')}
                                </div>
                            </div>
                            <CircleCloseButton onClick={requestClose} ariaLabel={t('authModal.close')} />
                        </div>

                        <div className="px-6 py-5">
                            {tab === 'login' ? (
                                <form autoComplete="off" className="space-y-5" onSubmit={(e) => e.preventDefault()}>
                                    <div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400">{t('authModal.account')}</div>
                                        <div
                                            className={cx(
                                                'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                                loginUidTouched && !loginUidOk
                                                    ? 'border-[#ef565f]'
                                                    : 'border-[#d5d7dc] dark:border-gray-700',
                                                'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                            )}
                                        >
                                            <input
                                                value={loginUid}
                                                onChange={(e) => setLoginUid(e.target.value)}
                                                onBlur={() => setLoginUidTouched(true)}
                                                name="gp_login_uid"
                                                autoComplete="off"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                readOnly
                                                onFocus={(e) => {
                                                    e.currentTarget.readOnly = false
                                                }}
                                                placeholder={t('authModal.userIdPlaceholder')}
                                                className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                                maxLength={12}
                                                minLength={6}
                                            />
                                            {loginUid.length > 0 && (
                                                <button
                                                    type="button"
                                                    className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                    onClick={() => setLoginUid('')}
                                                    aria-label={t('authModal.clear')}
                                                >
                                                    <FaXmark className="w-3 h-3" />
                                                </button>
                                            )}
                                        </div>
                                        {loginUidTouched && !loginUidOk && (
                                            <div className="mt-2 text-sm text-[#ef565f]">{t('authModal.userIdError')}</div>
                                        )}
                                    </div>

                                    <div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400">{t('authModal.password')}</div>
                                        <div
                                            className={cx(
                                                'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                                loginPwTouched && loginPw.trim().length === 0
                                                    ? 'border-[#ef565f]'
                                                    : 'border-[#d5d7dc] dark:border-gray-700',
                                                'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                            )}
                                        >
                                            <input
                                                value={loginPw}
                                                onChange={(e) => setLoginPw(e.target.value)}
                                                onBlur={() => setLoginPwTouched(true)}
                                                name="gp_login_password"
                                                autoComplete="new-password"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                readOnly
                                                onFocus={(e) => {
                                                    e.currentTarget.readOnly = false
                                                }}
                                                placeholder={t('authModal.passwordPlaceholder')}
                                                type={loginPwShow ? 'text' : 'password'}
                                                className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                                maxLength={64}
                                            />
                                            {loginPw.length > 0 && (
                                                <button
                                                    type="button"
                                                    className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                    onClick={() => setLoginPw('')}
                                                    aria-label={t('authModal.clear')}
                                                >
                                                    <FaXmark className="w-3 h-3" />
                                                </button>
                                            )}
                                            <button
                                                type="button"
                                                className="ml-2 w-7 h-7 rounded-lg hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] flex items-center justify-center text-gray-700 dark:text-gray-200"
                                                onClick={() => setLoginPwShow((v) => !v)}
                                                aria-label={loginPwShow ? t('authModal.hidePassword') : t('authModal.showPassword')}
                                            >
                                                {loginPwShow ? <FaEye className="w-4 h-4" /> : <FaEyeSlash className="w-4 h-4" />}
                                            </button>
                                        </div>
                                        {loginPwTouched && loginPw.trim().length === 0 && (
                                            <div className="mt-2 text-sm text-[#ef565f]">{t('authModal.passwordRequired')}</div>
                                        )}
                                    </div>

                                    <div className="pt-2">
                                        <button
                                            type="button"
                                            disabled={!loginOk}
                                            className={cx(
                                                'w-full h-[52px] rounded-xl text-[16px] font-medium transition-colors',
                                                loginOk
                                                    ? 'border border-[#d5d7dc] dark:border-gray-700 hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] text-gray-900 dark:text-white'
                                                    : 'bg-[#f1f2f4] dark:bg-[#232529] text-[rgba(23,25,28,0.3)] dark:text-white/30 pointer-events-none'
                                            )}
                                            onClick={() => {
                                                window.alert('（Mock）登入資料已通過前端驗證')
                                            }}
                                        >
                                            {t('authModal.login')}
                                        </button>

                                        <button
                                            type="button"
                                            className="mt-3 w-full text-sm text-[#525661] dark:text-gray-300 hover:text-gray-900 dark:hover:text-white underline underline-offset-4"
                                            onClick={() => window.alert('（Mock）忘記密碼流程尚未串接')}
                                        >
                                            {t('authModal.forgotPassword')}
                                        </button>
                                    </div>
                                </form>
                            ) : (
                                <form autoComplete="off" className="space-y-5" onSubmit={(e) => e.preventDefault()}>
                                    <div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400">{t('authModal.account')}</div>
                                        <div
                                            className={cx(
                                                'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                                uidTouched && !uidOk
                                                    ? 'border-[#ef565f]'
                                                    : 'border-[#d5d7dc] dark:border-gray-700',
                                                'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                            )}
                                        >
                                            <input
                                                value={uid}
                                                onChange={(e) => setUid(e.target.value)}
                                                onBlur={() => setUidTouched(true)}
                                                name="gp_register_uid"
                                                autoComplete="off"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                readOnly
                                                onFocus={(e) => {
                                                    e.currentTarget.readOnly = false
                                                }}
                                                placeholder={t('authModal.userIdPlaceholder')}
                                                className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                                maxLength={12}
                                                minLength={6}
                                            />
                                            {uid.length > 0 && (
                                                <button
                                                    type="button"
                                                    className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                    onClick={() => setUid('')}
                                                    aria-label={t('authModal.clear')}
                                                >
                                                    <FaXmark className="w-3 h-3" />
                                                </button>
                                            )}
                                        </div>
                                        {uidTouched && !uidOk && (
                                            <div className="mt-2 text-sm text-[#ef565f]">{t('authModal.userIdError')}</div>
                                        )}
                                    </div>

                                    <div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400">{t('authModal.password')}</div>
                                        <div
                                            className={cx(
                                                'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                                pwTouched && !pass.ok
                                                    ? 'border-[#ef565f]'
                                                    : 'border-[#d5d7dc] dark:border-gray-700',
                                                'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                            )}
                                        >
                                            <input
                                                value={pw}
                                                onChange={(e) => setPw(e.target.value)}
                                                onBlur={() => setPwTouched(true)}
                                                name="gp_register_password"
                                                autoComplete="new-password"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                readOnly
                                                onFocus={(e) => {
                                                    e.currentTarget.readOnly = false
                                                }}
                                                placeholder={t('authModal.registerPasswordPlaceholder')}
                                                type={pwShow ? 'text' : 'password'}
                                                className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                                maxLength={15}
                                                minLength={10}
                                            />
                                            {pw.length > 0 && (
                                                <button
                                                    type="button"
                                                    className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                    onClick={() => setPw('')}
                                                    aria-label={t('authModal.clear')}
                                                >
                                                    <FaXmark className="w-3 h-3" />
                                                </button>
                                            )}
                                            <button
                                                type="button"
                                                className="ml-2 w-7 h-7 rounded-lg hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] flex items-center justify-center text-gray-700 dark:text-gray-200"
                                                onClick={() => setPwShow((v) => !v)}
                                                aria-label={pwShow ? t('authModal.hidePassword') : t('authModal.showPassword')}
                                            >
                                                {pwShow ? <FaEye className="w-4 h-4" /> : <FaEyeSlash className="w-4 h-4" />}
                                            </button>
                                        </div>
                                        {pwTouched && !pass.ok && (
                                            <div className="mt-2 text-sm text-[#ef565f]">
                                                {t('authModal.registerPasswordError')}
                                            </div>
                                        )}
                                    </div>

                                    <div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400">{t('authModal.confirmPassword')}</div>
                                        <div
                                            className={cx(
                                                'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                                pw2Touched && !pw2Ok
                                                    ? 'border-[#ef565f]'
                                                    : 'border-[#d5d7dc] dark:border-gray-700',
                                                'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                            )}
                                        >
                                            <input
                                                value={pw2}
                                                onChange={(e) => setPw2(e.target.value)}
                                                onBlur={() => setPw2Touched(true)}
                                                name="gp_register_password_confirm"
                                                autoComplete="new-password"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                readOnly
                                                onFocus={(e) => {
                                                    e.currentTarget.readOnly = false
                                                }}
                                                placeholder={t('authModal.confirmPasswordPlaceholder')}
                                                type={pwShow ? 'text' : 'password'}
                                                className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                                maxLength={15}
                                                minLength={10}
                                            />
                                            {pw2.length > 0 && (
                                                <button
                                                    type="button"
                                                    className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                    onClick={() => setPw2('')}
                                                    aria-label={t('authModal.clear')}
                                                >
                                                    <FaXmark className="w-3 h-3" />
                                                </button>
                                            )}
                                        </div>
                                        {pw2Touched && !pw2Ok && (
                                            <div className="mt-2 text-sm text-[#ef565f]">{t('authModal.passwordMismatch')}</div>
                                        )}
                                    </div>

                                    <div>
                                        <div className="text-sm text-gray-500 dark:text-gray-400">{t('authModal.email')}</div>
                                        <div className="relative">
                                            <div
                                                className={cx(
                                                    'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                                    emailTouched && !emailOk
                                                        ? 'border-[#ef565f]'
                                                        : 'border-[#d5d7dc] dark:border-gray-700',
                                                    'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                                )}
                                            >
                                                <input
                                                    ref={emailInputRef}
                                                    value={email}
                                                    onChange={(e) => {
                                                        const v = e.target.value
                                                        setEmail(v)
                                                        const at = v.indexOf('@')
                                                        const local = at >= 0 ? v.slice(0, at).trim() : ''
                                                        setEmailSuggestActive(0)
                                                        setEmailSuggestOpen(at >= 0 && Boolean(local))
                                                    }}
                                                    onBlur={() => {
                                                        setEmailTouched(true)
                                                        if (emailBlurTimerRef.current !== null) {
                                                            window.clearTimeout(emailBlurTimerRef.current)
                                                        }
                                                        emailBlurTimerRef.current = window.setTimeout(() => {
                                                            setEmailSuggestOpen(false)
                                                            emailBlurTimerRef.current = null
                                                        }, 120)
                                                    }}
                                                    onKeyDown={(e) => {
                                                        if (!emailSuggestOpen || emailDomainSuggestions.length === 0) return
                                                        if (e.key === 'ArrowDown') {
                                                            e.preventDefault()
                                                            setEmailSuggestActive((i) => Math.min(emailDomainSuggestions.length - 1, i + 1))
                                                        } else if (e.key === 'ArrowUp') {
                                                            e.preventDefault()
                                                            setEmailSuggestActive((i) => Math.max(0, i - 1))
                                                        } else if (e.key === 'Enter') {
                                                            e.preventDefault()
                                                            const dom = emailDomainSuggestions[emailSuggestActive]
                                                            if (!dom) return
                                                            const local = emailParts.local.trim()
                                                            if (!local) return
                                                            setEmail(`${local}@${dom}`)
                                                            setEmailSuggestOpen(false)
                                                            setEmailSuggestActive(0)
                                                        } else if (e.key === 'Escape') {
                                                            e.preventDefault()
                                                            setEmailSuggestOpen(false)
                                                        }
                                                    }}
                                                    name="gp_register_email"
                                                    autoComplete="off"
                                                    autoCapitalize="none"
                                                    autoCorrect="off"
                                                    spellCheck={false}
                                                    readOnly
                                                    onFocus={(e) => {
                                                        e.currentTarget.readOnly = false
                                                        if (emailBlurTimerRef.current !== null) {
                                                            window.clearTimeout(emailBlurTimerRef.current)
                                                            emailBlurTimerRef.current = null
                                                        }
                                                        if (emailParts.hasAt && emailParts.local.trim()) {
                                                            setEmailSuggestOpen(true)
                                                        }
                                                    }}
                                                    placeholder={t('authModal.emailPlaceholder')}
                                                    className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                                />
                                                {email.length > 0 && (
                                                    <button
                                                        type="button"
                                                        className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                        onClick={() => {
                                                            setEmail('')
                                                            setEmailSuggestOpen(false)
                                                            setEmailSuggestActive(0)
                                                        }}
                                                        aria-label={t('authModal.clear')}
                                                    >
                                                        <FaXmark className="w-3 h-3" />
                                                    </button>
                                                )}
                                            </div>

                                            {emailSuggestOpen && emailDomainSuggestions.length > 0 && (
                                                <div className="absolute left-0 right-0 top-full mt-2 z-[100] overflow-hidden rounded-lg border border-[#acb0b9] dark:border-gray-700 bg-white dark:bg-[#0c0d0e] shadow-lg">
                                                    <ul className="py-2 max-h-[244px] overflow-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
                                                        {emailDomainSuggestions.map((dom, idx) => {
                                                            const active = idx === emailSuggestActive
                                                            return (
                                                                <li key={dom} className="min-h-[48px]">
                                                                    <button
                                                                        type="button"
                                                                        onMouseDown={(e) => {
                                                                            e.preventDefault()
                                                                        }}
                                                                        onMouseEnter={() => setEmailSuggestActive(idx)}
                                                                        onClick={() => {
                                                                            const local = emailParts.local.trim()
                                                                            if (!local) return
                                                                            setEmail(`${local}@${dom}`)
                                                                            setEmailSuggestOpen(false)
                                                                            setEmailSuggestActive(0)
                                                                            window.requestAnimationFrame(() => emailInputRef.current?.focus())
                                                                        }}
                                                                        className={cx(
                                                                            'w-full min-h-[48px] px-4 text-left text-[16px] transition-colors',
                                                                            active
                                                                                ? 'bg-[#f6f6f9] dark:bg-[#1a1c21] text-gray-900 dark:text-white'
                                                                                : 'text-gray-900 dark:text-white hover:bg-[#f6f6f9] dark:hover:bg-[#1a1c21]'
                                                                        )}
                                                                    >
                                                                        {dom}
                                                                    </button>
                                                                </li>
                                                            )
                                                        })}
                                                    </ul>
                                                </div>
                                            )}
                                        </div>
                                        {emailTouched && !emailOk && (
                                            <div className="mt-2 text-sm text-[#ef565f]">{t('authModal.emailError')}</div>
                                        )}
                                    </div>

                                    <div className="pt-2">
                                        <div className="border-t border-gray-100 dark:border-gray-800 pt-4">
                                            <label className="relative flex items-center gap-3 cursor-pointer select-none">
                                                <input
                                                    type="checkbox"
                                                    checked={agreeTerms}
                                                    onChange={(e) => setAgreeTerms(e.target.checked)}
                                                    className="peer sr-only"
                                                />
                                                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 border-[#d5d7dc] dark:border-gray-600 transition-colors peer-checked:border-black peer-checked:bg-black dark:peer-checked:border-white dark:peer-checked:bg-white" />
                                                <span className="absolute left-0 flex h-5 w-5 items-center justify-center pointer-events-none opacity-0 transition-opacity peer-checked:opacity-100">
                                                    <svg className="h-3 w-3 text-white dark:text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                                                        <path d="M5 13l4 4L19 7" />
                                                    </svg>
                                                </span>
                                                <span className="text-sm text-gray-700 dark:text-gray-200 flex-1">
                                                    <span className="text-[#0182ff] mr-1">{t('authModal.required')}</span>
                                                    {t('authModal.agreeTerms')}
                                                </span>
                                                <button
                                                    type="button"
                                                    className="shrink-0 text-sm text-[#0182ff] hover:underline"
                                                    onClick={(e) => {
                                                        e.preventDefault()
                                                        e.stopPropagation()
                                                        window.alert('（示意）顯示服務條款內容')
                                                    }}
                                                >
                                                    {t('authModal.view')}
                                                </button>
                                            </label>
                                        </div>
                                    </div>

                                    <div className="pt-2">
                                        <button
                                            type="button"
                                            disabled={!registerOk}
                                            className={cx(
                                                'w-full h-[52px] rounded-xl text-[16px] font-medium transition-colors',
                                                registerOk
                                                    ? 'border border-[#d5d7dc] dark:border-gray-700 hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] text-gray-900 dark:text-white'
                                                    : 'bg-[#f1f2f4] dark:bg-[#232529] text-[rgba(23,25,28,0.3)] dark:text-white/30 pointer-events-none'
                                            )}
                                            onClick={() => {
                                                window.alert('（Mock）註冊資料已通過前端驗證')
                                            }}
                                        >
                                            {t('authModal.next')}
                                        </button>
                                    </div>
                                </form>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )

    if (!mounted) return null
    if (!visible) return null
    return createPortal(modal, document.body)
}


