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, 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 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 {
            await fetch('/api/auth/history', {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            alert('历史记录已删除');
        } catch (err) {
            alert('操作失败');
        }
    };

    const handleDeleteAccount = async () => {
        if (!confirm('确认注销账户并删除全部个人资料与测算历史吗？此操作不可恢复。')) return;
        const token = localStorage.getItem('mystic_token');
        try {
            await fetch('/api/auth/account', {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            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 text-rose-950 tracking-[0.05em] leading-none drop-shadow-md"
                    style={{ fontFamily: "'ZCOOL KuaiLe', sans-serif" }}
                >
                    知了
                </span>
                <span className="text-[9px] font-bold text-rose-950/60 tracking-[0.2em] mt-1 whitespace-nowrap pl-0.5">知天命 · 了心事</span>
            </div>
            
            <div className="flex items-center gap-3">
                {/* 更多功能 Dropdown */}
                <div className="relative" ref={menuRef}>
                    <button 
                        onClick={() => setShowMoreMenu(!showMoreMenu)}
                        className="px-3 py-1.5 rounded-full text-[12px] font-black transition-all duration-300 bg-white/40 backdrop-blur-md text-rose-950 border border-white/60 shadow-sm flex items-center gap-1 hover:bg-white/60"
                    >
                        更多功能
                        <svg className={`w-3 h-3 transition-transform duration-300 ${showMoreMenu ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M19 9l-7 7-7-7"></path></svg>
                    </button>
                    
                    {showMoreMenu && (
                        <div className="absolute right-0 top-[115%] mt-1 w-[104px] 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">
                            {Object.keys(pathMap).map((item, idx) => (
                                <button 
                                    key={idx} 
                                    className="px-3 py-2.5 text-center text-[11px] font-bold text-rose-950/80 hover:bg-rose-50 hover:text-rose-950 transition-colors w-full border-b border-rose-50/5 last:border-0"
                                    onClick={() => handleNavigation(pathMap[item])}
                                >
                                    {item}
                                </button>
                            ))}
                        </div>
                    )}
                </div>
                
                {/* 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-rose-950 text-white flex items-center justify-center font-bold text-sm shadow-md hover:scale-105 transition-transform overflow-hidden"
                        >
                            {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); 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}
                />
            )}
        </div>
    );
}

window.Navbar = Navbar;
