/**
 * Auth Modal Component
 * 
 * Email login/registration via magic links
 */

const { useState } = React;

function Auth({ onLogin, onClose }) {
    const [email, setEmail] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState(false);
    const [debugLink, setDebugLink] = useState(null);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        setSuccess(false);
        setDebugLink(null);

        try {
            const response = await fetch('/api/auth/send-magic-link', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email })
            });

            const data = await response.json();

            if (data.status === 'success') {
                setSuccess(true);
                if (data.debugLink) {
                    setDebugLink(data.debugLink);
                } else {
                    // In production, show message about checking email
                    setSuccessMessage('登入連結已發送到你的郵箱！');
                }
            } else {
                setError(data.message || '發送失敗');
            }
        } catch (err) {
            setError('網絡錯誤，請重試');
        } finally {
            setLoading(false);
        }
    };

    const setSuccessMessage = (msg) => {
        // Show success state
        setSuccess(true);
    };

    return React.createElement('div', {
        className: 'fixed inset-0 bg-black/50 flex items-center justify-center z-50',
        onClick: onClose
    },
        React.createElement('div', {
            className: 'glass rounded-xl p-6 w-full max-w-md mx-4',
            onClick: (e) => e.stopPropagation()
        },
            React.createElement('div', { className: 'flex justify-between items-center mb-6' },
                React.createElement('h2', { className: 'text-xl font-bold text-white' }, '登入 / 註冊'),
                React.createElement('button', {
                    className: 'text-gray-400 hover:text-white',
                    onClick: onClose
                }, '✕')
            ),

            !success ? React.createElement('form', { onSubmit: handleSubmit },
                React.createElement('p', { className: 'text-gray-400 mb-4' }, 
                    '輸入你的電郵地址，我們會發送登入連結給你。'
                ),
                React.createElement('input', {
                    type: 'email',
                    value: email,
                    onChange: (e) => setEmail(e.target.value),
                    placeholder: '你的電郵地址',
                    className: 'w-full bg-gray-800/50 border border-gray-700 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-blue-500 mb-4',
                    required: true
                }),
                error && React.createElement('p', { className: 'text-red-400 text-sm mb-4' }, error),
                React.createElement('button', {
                    type: 'submit',
                    disabled: loading,
                    className: 'w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800 text-white font-medium py-3 rounded-lg transition-colors'
                }, loading ? '發送中...' : '發送登入連結')
            ) : React.createElement('div', { className: 'text-center' },
                React.createElement('div', { className: 'text-4xl mb-4' }, '✅'),
                React.createElement('p', { className: 'text-white font-medium mb-2' }, '登入連結已發送！'),
                React.createElement('p', { className: 'text-gray-400 text-sm mb-4' }, 
                    `我們已發送登入連結到 ${email}`
                ),
                debugLink && React.createElement('div', { className: 'mt-4 p-4 bg-gray-800/50 rounded-lg' },
                    React.createElement('p', { className: 'text-yellow-400 text-xs mb-2' }, '【開發模式】直接點擊連結：'),
                    React.createElement('a', {
                        href: `/auth/verify?token=${debugLink.split('token=')[1]}`,
                        className: 'text-blue-400 text-sm break-all',
                        target: '_blank'
                    }, debugLink)
                ),
                React.createElement('p', { className: 'text-gray-500 text-xs mt-4' }, 
                    '如果找不到郵件，請檢查垃圾郵件匣。連結將在 15 分鐘後過期。'
                )
            )
        )
    );
}

function Profile({ user, onLogout, onClose, onGenerateTGBind }) {
    const [loading, setLoading] = useState(false);
    const [tgCode, setTgCode] = useState(null);
    const [tgStatus, setTgStatus] = useState(user?.tg_bound ? '已綁定' : '未綁定');
    const [userEmail, setUserEmail] = useState(user?.email || '');

    const handleGenerateTGBind = async () => {
        setLoading(true);
        try {
            const response = await fetch('/api/user/generate-tg-code', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ user_id: user?.id })
            });

            const data = await response.json();

            if (data.status === 'success') {
                setTgCode(data.code);
                setTgStatus('等待綁定中...');
            }
        } catch (err) {
            console.error('Error generating TG code:', err);
        } finally {
            setLoading(false);
        }
    };

    return React.createElement('div', {
        className: 'fixed inset-0 bg-black/50 flex items-center justify-center z-50',
        onClick: onClose
    },
        React.createElement('div', {
            className: 'glass rounded-xl p-6 w-full max-w-md mx-4',
            onClick: (e) => e.stopPropagation()
        },
            React.createElement('div', { className: 'flex justify-between items-center mb-6' },
                React.createElement('h2', { className: 'text-xl font-bold text-white' }, '個人檔案'),
                React.createElement('button', {
                    className: 'text-gray-400 hover:text-white',
                    onClick: onClose
                }, '✕')
            ),

            React.createElement('div', { className: 'space-y-4' },
                React.createElement('div', null,
                    React.createElement('label', { className: 'block text-gray-400 text-sm mb-1' }, '電郵地址'),
                    React.createElement('input', {
                        type: 'email',
                        value: userEmail,
                        disabled: true,
                        className: 'w-full bg-gray-800/30 border border-gray-700 rounded-lg px-4 py-3 text-gray-400'
                    })
                ),

                React.createElement('div', null,
                    React.createElement('label', { className: 'block text-gray-400 text-sm mb-1' }, 'Telegram 綁定'),
                    React.createElement('div', {
                        className: `flex items-center gap-2 ${user?.tg_bound ? 'text-green-400' : 'text-yellow-400'}`
                    },
                        React.createElement('span', null, user?.tg_bound ? '✅ 已綁定' : '❌ 未綁定')
                    ),
                    !user?.tg_bound && React.createElement('div', { className: 'mt-3' },
                        tgCode ? React.createElement('div', { className: 'bg-gray-800/50 rounded-lg p-4' },
                            React.createElement('p', { className: 'text-gray-400 text-sm mb-2' }, '將以下驗證碼發送給 Telegram Bot：'),
                            React.createElement('div', { className: 'text-3xl font-mono text-center text-yellow-400 mb-2' }, tgCode),
                            React.createElement('p', { className: 'text-gray-500 text-xs' }, '打開 Telegram，搜尋 @你的bot，然後發送：'),
                            React.createElement('p', { className: 'text-blue-400 text-sm font-mono mt-2' }, `/link ${tgCode}`),
                            React.createElement('p', { className: 'text-gray-500 text-xs mt-2' }, '驗證碼將在 15 分鐘後過期')
                        ) : React.createElement('button', {
                            onClick: handleGenerateTGBind,
                            disabled: loading,
                            className: 'bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800 text-white text-sm px-4 py-2 rounded-lg transition-colors'
                        }, loading ? '產生中...' : '產生驗證碼')
                    )
                ),

                React.createElement('hr', { className: 'border-gray-700 my-4' }),

                React.createElement('button', {
                    onClick: onLogout,
                    className: 'w-full bg-red-600/20 hover:bg-red-600/30 text-red-400 border border-red-600/50 py-2 rounded-lg transition-colors'
                }, '登出')
            )
        )
    );
}

window.Auth = Auth;
window.Profile = Profile;
