const { useState, useRef, useEffect } = React;

function Navbar({ currentPath }) {
    const { useAuth } = window.AuthComponents || {};
    // Fallback if useAuth is not loaded for some reason
    const auth = useAuth ? useAuth() : { user: null, loading: false };
    const { user, profile, loading, logout, checkLogin } = auth;
    
    const [showMoreMenu, setShowMoreMenu] = useState(false);
    const [showUserMenu, setShowUserMenu] = useState(false);
    const [showLoginModal, setShowLoginModal] = useState(false);
    const [showProfileModal, setShowProfileModal] = useState(false);
    const [showPasswordModal, setShowPasswordModal] = useState(false);
    const lightHeaderPages = ['history.html', 'profile.html', 'divination.html', 'relationship.html', 'community.html'];
    const useDarkBrand = lightHeaderPages.includes(currentPath);
    const useHomeAvatar = currentPath === 'dial.html';
    
    const menuRef = useRef(null);
    const userMenuRef = useRef(null);

    // Close menus when clicking outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (menuRef.current && !menuRef.current.contains(event.target)) {
                setShowMoreMenu(false);
            }
            if (userMenuRef.current && !userMenuRef.current.contains(event.target)) {
                setShowUserMenu(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [menuRef, userMenuRef]);
    
    const pathMap = {
        '缘分测试': 'compatibility.html',
        '星座运势': 'horoscope.html',
        '塔罗占卜': 'index.html',
        '八字命理': 'bazi.html',
        '寻找宿命': 'destiny.html',
        '依恋测试': 'attachment.html'
    };
    
    const handleNavigation = (target) => {
        if (target) {
            window.location.href = window.location.protocol === 'file:' ? target : '/' + target;
        } else {
            alert('该功能正在开发中，敬请期待！');
        }
    };

    const handleDeleteHistory = async () => {
        if (!confirm('确认删除你的全部测算历史吗？此操作不可恢复。')) return;
        const token = localStorage.getItem('mystic_token');
        try {
            const response = await fetch('/api/auth/history', {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            if (!response.ok) throw new Error('删除失败');
            alert('历史记录已删除');
        } catch (err) {
            alert('操作失败');
        }
    };

    const handleDeleteAccount = async () => {
        if (!confirm('确认注销账户并删除全部个人资料与测算历史吗？此操作不可恢复。')) return;
        const token = localStorage.getItem('mystic_token');
        try {
            const response = await fetch('/api/auth/account', {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            if (!response.ok) throw new Error('注销失败');
            localStorage.removeItem('mystic_token');
            localStorage.removeItem('mystic_profile');
            window.location.href = '/';
        } catch (err) {
            alert('操作失败');
        }
    };

    return (
        <div className="w-full px-4 pt-6 pb-2 flex items-center justify-between relative z-[100]">
            {/* Logo Section */}
            <div className="flex flex-col cursor-pointer hover:opacity-80 transition-opacity" onClick={() => window.location.href = '/'}>
                <span 
                    className={`text-[28px] font-black tracking-[0.05em] leading-none ${useDarkBrand ? 'text-[#403454]' : 'text-white drop-shadow-md'}`}
                    style={{ fontFamily: "'ZCOOL KuaiLe', sans-serif" }}
                >
                    知了
                </span>
                <span className={`text-[9px] font-bold tracking-[0.2em] mt-1 whitespace-nowrap pl-0.5 ${useDarkBrand ? 'text-[#756b8d]' : 'text-white/70'}`}>知天命 · 了心事</span>
            </div>
            
            <div className="flex items-center gap-3">

                
                {/* User Auth Dropdown */}
                <div className="relative" ref={userMenuRef}>
                    {loading ? (
                        <div className="w-8 h-8 rounded-full bg-white/40 animate-pulse"></div>
                    ) : user ? (
                        <button 
                            onClick={() => setShowUserMenu(!showUserMenu)}
                            className="w-8 h-8 rounded-full bg-white/35 backdrop-blur-md text-white border border-white/60 flex items-center justify-center font-bold text-sm shadow-[0_7px_18px_rgba(74,55,108,.16)] hover:scale-105 transition-transform overflow-hidden"
                            aria-label="打开个人菜单"
                        >
                            {useHomeAvatar ? (
                                <img
                                    src={`https://api.dicebear.com/7.x/notionists/svg?seed=${encodeURIComponent(profile?.avatar_seed || user.avatar_seed || profile?.public_id || user.public_id || user.username || 'guest')}&backgroundColor=f5f5f5`}
                                    alt=""
                                    className="w-full h-full object-cover"
                                />
                            ) : (user.nickname ? user.nickname.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase())}
                        </button>
                    ) : (
                        <button 
                            onClick={() => setShowLoginModal(true)}
                            className="px-3 py-1.5 rounded-full text-[12px] font-bold bg-rose-500 text-white shadow-md hover:bg-rose-600 transition-colors"
                        >
                            登录
                        </button>
                    )}
                    
                    {showUserMenu && user && (
                        <div className="absolute right-0 top-[115%] mt-1 w-[140px] bg-white/95 backdrop-blur-xl border border-rose-100 shadow-xl rounded-2xl overflow-hidden flex flex-col z-50 animate-fade-in origin-top-right">
                            <button 
                                onClick={() => { setShowUserMenu(false); setShowProfileModal(true); }}
                                className="px-3 py-3 border-b border-rose-50 text-left hover:bg-rose-50 transition-colors w-full"
                            >
                                <div className="text-[10px] text-rose-400 font-bold">当前账户 (点击修改)</div>
                                <div className="text-sm font-black text-rose-950 truncate">{user.nickname || user.username}</div>
                            </button>
                            <button onClick={() => { setShowUserMenu(false); setShowPasswordModal(true); }} className="px-3 py-2.5 text-left text-[11px] font-bold text-slate-700 hover:bg-slate-50 transition-colors">修改密码</button>
                            <button onClick={() => { setShowUserMenu(false); handleDeleteHistory(); }} className="px-3 py-2.5 text-left text-[11px] font-bold text-slate-700 hover:bg-slate-50 transition-colors">删除测算历史</button>
                            <button onClick={() => { setShowUserMenu(false); logout(); }} className="px-3 py-2.5 text-left text-[11px] font-bold text-slate-700 hover:bg-slate-50 transition-colors">退出登录</button>
                            <button onClick={() => { setShowUserMenu(false); handleDeleteAccount(); }} className="px-3 py-2.5 text-left text-[11px] font-bold text-rose-600 hover:bg-rose-50 transition-colors">注销账户</button>
                        </div>
                    )}
                </div>
            </div>
            {showLoginModal && window.AuthComponents?.LoginModal && (
                <window.AuthComponents.LoginModal 
                    isOpen={showLoginModal} 
                    onClose={() => setShowLoginModal(false)}
                    onSuccess={checkLogin}
                />
            )}
            {showProfileModal && window.AuthComponents?.ProfileEditModal && (
                <window.AuthComponents.ProfileEditModal 
                    isOpen={showProfileModal} 
                    onClose={() => setShowProfileModal(false)}
                    onSuccess={checkLogin}
                />
            )}
            {showPasswordModal && window.AuthComponents?.PasswordChangeModal && (
                <window.AuthComponents.PasswordChangeModal
                    isOpen={showPasswordModal}
                    onClose={() => setShowPasswordModal(false)}
                />
            )}
        </div>
    );
}

window.Navbar = Navbar;
