// frontend/js/auth-react.jsx
// 全局共享的 React 鉴权与档案同步模块
// NOTE: 不在顶层解构 React hooks，避免与页面脚本冲突

/**
 * 核心 Auth Hook
 * 用于检查登录状态、获取档案数据、处理登录注册登出
 */
function useAuth() {
    const { useState, useEffect } = React;
    const [user, setUser] = useState(null);
    const [profile, setProfile] = useState(null);
    const [loading, setLoading] = useState(true);

    const fetchProfile = async (token) => {
        try {
            const res = await fetch('/api/user/profile', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            if (res.ok) {
                const data = await res.json();
                setProfile(data.data);
                localStorage.setItem('mystic_profile', JSON.stringify(data.data));
            }
        } catch (e) {
            console.error("Profile fetch failed:", e);
        }
    };

    const checkLogin = async () => {
        setLoading(true);
        const token = localStorage.getItem('mystic_token');
        if (!token) {
            setUser(null);
            setProfile(null);
            setLoading(false);
            return;
        }

        try {
            const res = await fetch('/api/auth/me', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            if (res.ok) {
                const userData = await res.json();
                setUser(userData);
                await fetchProfile(token);
            } else {
                localStorage.removeItem('mystic_token');
                setUser(null);
            }
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        // 先尝试从本地读取
        const cachedProfile = localStorage.getItem('mystic_profile');
        if (cachedProfile) {
            try {
                setProfile(JSON.parse(cachedProfile));
            } catch (e) {}
        }
        checkLogin();
    }, []);

    const logout = async () => {
        const token = localStorage.getItem('mystic_token');
        if (token) {
            fetch('/api/auth/logout', { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } });
        }
        localStorage.removeItem('mystic_token');
        localStorage.removeItem('mystic_profile');
        setUser(null);
        setProfile(null);
    };

    const silentUpdateProfile = async (updateData) => {
        const token = localStorage.getItem('mystic_token');
        if (!token || !updateData) return;
        
        try {
            const res = await fetch('/api/user/profile', {
                method: 'POST',
                headers: { 
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updateData)
            });
            if (res.ok) {
                await fetchProfile(token);
            }
        } catch (e) {
            console.error("Silent sync failed", e);
        }
    };

    return { user, profile, loading, checkLogin, logout, silentUpdateProfile };
}

/**
 * 通用精美登录/注册弹窗组件
 */
function LoginModal({ isOpen, onClose, onSuccess }) {
    const { useState } = React;
    const [mode, setMode] = useState('login'); // 'login', 'register', or 'profile_setup'
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [nickname, setNickname] = useState('');
    
    // 完善档案表单状态
    const [profileForm, setProfileForm] = useState({
        nickname: '',
        real_name: '',
        gender: '女',
        birth_date: '',
        birth_time: '12:00',
        city_name: '北京',
        mbti: ''
    });

    const [error, setError] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);

    if (!isOpen) return null;

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        
        if (username.length < 2) return setError("用户名太短");
        if (password.length < 6) return setError("密码至少6位");

        setIsSubmitting(true);
        try {
            const endpoint = mode === 'login' ? '/api/auth/login' : '/api/auth/register';
            const res = await fetch(endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password, nickname })
            });
            const data = await res.json();
            
            if (!res.ok) {
                throw new Error(data.detail || data.message || '请求失败');
            }

            if (mode === 'register') {
                // 注册成功，自动登录
                const loginRes = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });
                const loginData = await loginRes.json();
                if (loginRes.ok) {
                    localStorage.setItem('mystic_token', loginData.token);
                    setProfileForm({...profileForm, nickname: nickname || ''});
                    setMode('profile_setup');
                } else {
                    setMode('login');
                    setError('注册成功，请重新登录');
                }
            } else if (mode === 'login') {
                localStorage.setItem('mystic_token', data.token);
                // 检查档案是否已填写
                const profileRes = await fetch('/api/user/profile', {
                    headers: { 'Authorization': `Bearer ${data.token}` }
                });
                let needsSetup = false;
                if (profileRes.ok) {
                    const profileData = await profileRes.json();
                    if (!profileData.data.birth_date) {
                        needsSetup = true;
                        setProfileForm({...profileForm, nickname: profileData.data.nickname || ''});
                    }
                }
                
                if (needsSetup) {
                    setMode('profile_setup');
                } else {
                    if (onSuccess) await onSuccess();
                    onClose();
                }
            }
        } catch (err) {
            setError(err.message);
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleProfileSubmit = async (e) => {
        e.preventDefault();
        setError('');
        
        if (!profileForm.birth_date) return setError("请选择出生日期");

        setIsSubmitting(true);
        try {
            const token = localStorage.getItem('mystic_token');
            const res = await fetch('/api/user/profile', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(profileForm)
            });
            
            if (!res.ok) {
                throw new Error('档案保存失败');
            }
            
            if (onSuccess) await onSuccess();
            onClose();
        } catch (err) {
            setError(err.message);
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleSkip = async () => {
        if (onSuccess) await onSuccess();
        onClose();
    };

    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm transition-all">
            <div className="bg-white rounded-3xl p-8 w-[90%] max-w-sm relative shadow-[0_20px_50px_rgba(0,0,0,0.3)] animate-[scaleIn_0.3s_ease-out]">
                {/* Close Button */}
                <button onClick={onClose} className="absolute top-4 right-4 w-8 h-8 flex items-center justify-center rounded-full bg-slate-100 text-slate-500 hover:bg-slate-200 transition-colors">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>

                {mode === 'profile_setup' ? (
                    <div className="flex flex-col">
                        <div className="text-center mb-6">
                            <h2 className="text-xl font-black text-rose-950 tracking-wider">完善个人档案</h2>
                            <p className="text-[11px] text-rose-500/80 tracking-wide mt-2 font-bold">一次填写，全站所有测算通用</p>
                        </div>
                        
                        <form onSubmit={handleProfileSubmit} className="flex flex-col gap-3">
                            <input type="text" value={profileForm.nickname} onChange={e => setProfileForm({...profileForm, nickname: e.target.value})} placeholder="您的称呼 (昵称)" required className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                            
                            <div>
                                <input type="text" value={profileForm.real_name} onChange={e => setProfileForm({...profileForm, real_name: e.target.value})} placeholder="真实姓名 (可选)" className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                                <p className="text-[10px] text-rose-500/80 ml-2 mt-1">💡 真实姓名会算的准</p>
                            </div>

                            <div className="flex gap-6 px-2 py-1">
                                <label className="flex items-center gap-2 text-sm text-slate-600 cursor-pointer font-bold">
                                    <input type="radio" checked={profileForm.gender === '男'} onChange={() => setProfileForm({...profileForm, gender: '男'})} className="accent-rose-500 w-4 h-4" /> 男
                                </label>
                                <label className="flex items-center gap-2 text-sm text-slate-600 cursor-pointer font-bold">
                                    <input type="radio" checked={profileForm.gender === '女'} onChange={() => setProfileForm({...profileForm, gender: '女'})} className="accent-rose-500 w-4 h-4" /> 女
                                </label>
                            </div>

                            <div className="flex gap-2">
                                <div className="flex-1">
                                    <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">出生日期 <span className="text-rose-400 ml-1">(请填写公历生日)</span></label>
                                    <input type="date" value={profileForm.birth_date} onChange={e => setProfileForm({...profileForm, birth_date: e.target.value})} required className="w-full bg-slate-50 px-4 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all text-slate-700" />
                                </div>
                                <div className="w-[100px]">
                                    <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">出生时间</label>
                                    <input type="time" value={profileForm.birth_time} onChange={e => setProfileForm({...profileForm, birth_time: e.target.value})} className="w-full bg-slate-50 px-4 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all text-slate-700" />
                                </div>
                            </div>

                            <div>
                                <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">出生城市</label>
                                <input type="text" value={profileForm.city_name} onChange={e => setProfileForm({...profileForm, city_name: e.target.value})} placeholder="如: 北京" className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                            </div>

                            <div>
                                <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">MBTI (16型人格)</label>
                                <select value={profileForm.mbti} onChange={e => setProfileForm({...profileForm, mbti: e.target.value})} className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all text-slate-700 appearance-none">
                                    <option value="">不确定 / 暂不填写</option>
                                    <option value="INTJ">INTJ 建筑师</option>
                                    <option value="INTP">INTP 逻辑学家</option>
                                    <option value="ENTJ">ENTJ 指挥官</option>
                                    <option value="ENTP">ENTP 辩论家</option>
                                    <option value="INFJ">INFJ 提倡者</option>
                                    <option value="INFP">INFP 调停者</option>
                                    <option value="ENFJ">ENFJ 主人公</option>
                                    <option value="ENFP">ENFP 竞选者</option>
                                    <option value="ISTJ">ISTJ 物流师</option>
                                    <option value="ISFJ">ISFJ 守卫者</option>
                                    <option value="ESTJ">ESTJ 总经理</option>
                                    <option value="ESFJ">ESFJ 执政官</option>
                                    <option value="ISTP">ISTP 鉴赏家</option>
                                    <option value="ISFP">ISFP 探险家</option>
                                    <option value="ESTP">ESTP 企业家</option>
                                    <option value="ESFP">ESFP 表演者</option>
                                </select>
                            </div>
                            
                            {error && <p className="text-xs text-center font-medium text-rose-500 mt-1">{error}</p>}

                            <button disabled={isSubmitting} type="submit" className="w-full bg-gradient-to-r from-rose-400 to-pink-500 hover:from-rose-500 hover:to-pink-600 text-white font-bold text-sm py-3.5 rounded-xl mt-3 transition-all shadow-lg shadow-rose-200/50 active:scale-95 disabled:opacity-70">
                                {isSubmitting ? '保存中...' : '保存并进入 ➔'}
                            </button>
                            <button type="button" onClick={handleSkip} className="w-full text-[11px] text-slate-400 font-medium py-1.5 hover:text-slate-600 transition-colors">
                                跳过，以后再填
                            </button>
                        </form>
                    </div>
                ) : (
                    <>
                        <div className="text-center mb-8">
                            <h2 className="text-2xl font-black text-rose-950 tracking-wider font-['Cinzel']">MYSTIC</h2>
                            <p className="text-xs text-rose-500/70 tracking-[0.2em] mt-1 font-bold">连接您的命运星轨</p>
                        </div>
                        <div className="flex bg-slate-100 rounded-full p-1 mb-6">
                            <button 
                                type="button"
                                onClick={() => setMode('login')} 
                                className={`flex-1 py-2 text-sm font-bold rounded-full transition-all ${mode === 'login' ? 'bg-white text-rose-900 shadow-sm' : 'text-slate-500 hover:text-rose-700'}`}
                            >登录</button>
                            <button 
                                type="button"
                                onClick={() => setMode('register')} 
                                className={`flex-1 py-2 text-sm font-bold rounded-full transition-all ${mode === 'register' ? 'bg-white text-rose-900 shadow-sm' : 'text-slate-500 hover:text-rose-700'}`}
                            >注册</button>
                        </div>

                        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
                            {mode === 'register' && (
                                <div className="relative">
                                    <input type="text" value={nickname} onChange={e => setNickname(e.target.value)} placeholder="您的称呼 (选填)" className="w-full bg-slate-50 px-5 py-3.5 rounded-2xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                                </div>
                            )}
                            <div className="relative">
                                <input type="text" value={username} onChange={e => setUsername(e.target.value)} placeholder="账号 (用于登录)" required className="w-full bg-slate-50 px-5 py-3.5 rounded-2xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                            </div>
                            <div className="relative">
                                <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="密码 (不少于6位)" required className="w-full bg-slate-50 px-5 py-3.5 rounded-2xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                            </div>

                            {error && (
                                <p className={`text-xs text-center font-medium ${error.includes('成功') ? 'text-green-500' : 'text-rose-500'}`}>{error}</p>
                            )}

                            <button disabled={isSubmitting} type="submit" className="w-full bg-gradient-to-r from-rose-400 to-pink-500 hover:from-rose-500 hover:to-pink-600 text-white font-bold text-sm py-4 rounded-2xl mt-2 transition-all shadow-lg shadow-rose-200/50 active:scale-95 disabled:opacity-70">
                                {isSubmitting ? '请稍候...' : (mode === 'login' ? '立即登录' : '注册并登录')}
                            </button>
                        </form>
                    </>
                )}
            </div>
            <style dangerouslySetInnerHTML={{__html: `
                @keyframes scaleIn { from { opacity: 0; transform: scale(0.95) translateY(10px); } to { opacity: 1; transform: scale(1) translateY(0); } }
            `}} />
        </div>
    );
}

/**
 * 独立资料修改弹窗组件 ProfileEditModal
 */
function ProfileEditModal({ isOpen, onClose, onSuccess }) {
    const { useState, useEffect } = React;
    const [profileForm, setProfileForm] = useState({
        nickname: '',
        real_name: '',
        gender: '女',
        birth_date: '',
        birth_time: '12:00',
        city_name: '北京',
        mbti: ''
    });
    const [error, setError] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        if (isOpen) {
            setIsLoading(true);
            const token = localStorage.getItem('mystic_token');
            fetch('/api/user/profile', {
                headers: { 'Authorization': `Bearer ${token}` }
            })
            .then(res => res.json())
            .then(data => {
                if (data.success && data.data) {
                    setProfileForm({
                        nickname: data.data.nickname || '',
                        real_name: data.data.real_name || '',
                        gender: data.data.gender || '女',
                        birth_date: data.data.birth_date || '',
                        birth_time: data.data.birth_time || '12:00',
                        city_name: data.data.city_name || '北京',
                        mbti: data.data.mbti || ''
                    });
                }
            })
            .catch(() => setError("获取档案失败"))
            .finally(() => setIsLoading(false));
        }
    }, [isOpen]);

    if (!isOpen) return null;

    const handleProfileSubmit = async (e) => {
        e.preventDefault();
        setError('');
        if (!profileForm.birth_date) return setError("请选择出生日期");

        setIsSubmitting(true);
        try {
            const token = localStorage.getItem('mystic_token');
            const res = await fetch('/api/user/profile', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(profileForm)
            });
            if (!res.ok) throw new Error('档案保存失败');
            if (onSuccess) await onSuccess();
            onClose();
        } catch (err) {
            setError(err.message);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm transition-all">
            <div className="bg-white rounded-3xl p-8 w-[90%] max-w-sm relative shadow-[0_20px_50px_rgba(0,0,0,0.3)] animate-[scaleIn_0.3s_ease-out]">
                <button onClick={onClose} className="absolute top-4 right-4 w-8 h-8 flex items-center justify-center rounded-full bg-slate-100 text-slate-500 hover:bg-slate-200 transition-colors">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>

                <div className="flex flex-col">
                    <div className="text-center mb-6">
                        <h2 className="text-xl font-black text-rose-950 tracking-wider">修改个人档案</h2>
                    </div>
                    
                    {isLoading ? (
                        <div className="flex justify-center py-10"><div className="w-6 h-6 border-2 border-rose-500 border-t-transparent rounded-full animate-spin"></div></div>
                    ) : (
                        <form onSubmit={handleProfileSubmit} className="flex flex-col gap-3">
                            <input type="text" value={profileForm.nickname} onChange={e => setProfileForm({...profileForm, nickname: e.target.value})} placeholder="您的称呼 (昵称)" required className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                            
                            <div>
                                <input type="text" value={profileForm.real_name} onChange={e => setProfileForm({...profileForm, real_name: e.target.value})} placeholder="真实姓名 (可选)" className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                                <p className="text-[10px] text-rose-500/80 ml-2 mt-1">💡 真实姓名会算的准</p>
                            </div>

                            <div className="flex gap-6 px-2 py-1">
                                <label className="flex items-center gap-2 text-sm text-slate-600 cursor-pointer font-bold">
                                    <input type="radio" checked={profileForm.gender === '男'} onChange={() => setProfileForm({...profileForm, gender: '男'})} className="accent-rose-500 w-4 h-4" /> 男
                                </label>
                                <label className="flex items-center gap-2 text-sm text-slate-600 cursor-pointer font-bold">
                                    <input type="radio" checked={profileForm.gender === '女'} onChange={() => setProfileForm({...profileForm, gender: '女'})} className="accent-rose-500 w-4 h-4" /> 女
                                </label>
                            </div>

                            <div className="flex gap-2">
                                <div className="flex-1">
                                    <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">出生日期 <span className="text-rose-400 ml-1">(请填写公历生日)</span></label>
                                    <input type="date" value={profileForm.birth_date} onChange={e => setProfileForm({...profileForm, birth_date: e.target.value})} required className="w-full bg-slate-50 px-4 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all text-slate-700" />
                                </div>
                                <div className="w-[100px]">
                                    <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">出生时间</label>
                                    <input type="time" value={profileForm.birth_time} onChange={e => setProfileForm({...profileForm, birth_time: e.target.value})} className="w-full bg-slate-50 px-4 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all text-slate-700" />
                                </div>
                            </div>

                            <div>
                                <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">出生城市</label>
                                <input type="text" value={profileForm.city_name} onChange={e => setProfileForm({...profileForm, city_name: e.target.value})} placeholder="如: 北京" className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all placeholder-slate-400" />
                            </div>

                            <div>
                                <label className="block text-[10px] text-slate-500 mb-1 ml-1 font-bold">MBTI (16型人格)</label>
                                <select value={profileForm.mbti} onChange={e => setProfileForm({...profileForm, mbti: e.target.value})} className="w-full bg-slate-50 px-5 py-3 rounded-xl border-none text-sm font-medium focus:ring-2 focus:ring-rose-200 focus:bg-white outline-none transition-all text-slate-700 appearance-none">
                                    <option value="">不确定 / 暂不填写</option>
                                    <option value="INTJ">INTJ 建筑师</option>
                                    <option value="INTP">INTP 逻辑学家</option>
                                    <option value="ENTJ">ENTJ 指挥官</option>
                                    <option value="ENTP">ENTP 辩论家</option>
                                    <option value="INFJ">INFJ 提倡者</option>
                                    <option value="INFP">INFP 调停者</option>
                                    <option value="ENFJ">ENFJ 主人公</option>
                                    <option value="ENFP">ENFP 竞选者</option>
                                    <option value="ISTJ">ISTJ 物流师</option>
                                    <option value="ISFJ">ISFJ 守卫者</option>
                                    <option value="ESTJ">ESTJ 总经理</option>
                                    <option value="ESFJ">ESFJ 执政官</option>
                                    <option value="ISTP">ISTP 鉴赏家</option>
                                    <option value="ISFP">ISFP 探险家</option>
                                    <option value="ESTP">ESTP 企业家</option>
                                    <option value="ESFP">ESFP 表演者</option>
                                </select>
                            </div>
                            
                            {error && <p className="text-xs text-center font-medium text-rose-500 mt-1">{error}</p>}

                            <button disabled={isSubmitting} type="submit" className="w-full bg-gradient-to-r from-rose-400 to-pink-500 hover:from-rose-500 hover:to-pink-600 text-white font-bold text-sm py-3.5 rounded-xl mt-3 transition-all shadow-lg shadow-rose-200/50 active:scale-95 disabled:opacity-70">
                                {isSubmitting ? '保存中...' : '保存修改'}
                            </button>
                        </form>
                    )}
                </div>
            </div>
        </div>
    );
}

window.AuthComponents = { useAuth, LoginModal, ProfileEditModal };
