import React from 'react'
import { useAuth } from '../context/AuthContext'

function Navbar() {
  const { isAuthenticated, currentUser, onLogout } = useAuth()

  // 导航链接点击处理
  const handleNavLinkClick = (path) => {
    window.history.pushState({}, '', path)
    // 触发页面重新渲染
    const event = new PopStateEvent('popstate')
    window.dispatchEvent(event)
  }

  return (
    <nav className="navbar">
      <div className="logo" onClick={() => handleNavLinkClick('/')}>VibeVault</div>
      
      <ul className="nav-links">
        <li>
          <a href="#" onClick={(e) => {
            e.preventDefault()
            handleNavLinkClick('/')
          }}>首页</a>
        </li>
        <li>
          <a href="#" onClick={(e) => {
            e.preventDefault()
            handleNavLinkClick('/playlists')
          }}>歌单</a>
        </li>
      </ul>
      
      <div className="auth-buttons">
        {isAuthenticated ? (
          <>
            <span>欢迎, {currentUser.username}</span>
            <button 
              className="btn btn-secondary" 
              onClick={onLogout}
            >
              登出
            </button>
          </>
        ) : (
          <>
            <button 
              className="btn btn-secondary" 
              onClick={() => handleNavLinkClick('/login')}
            >
              登录
            </button>
            <button 
              className="btn btn-primary" 
              onClick={() => handleNavLinkClick('/register')}
            >
              注册
            </button>
          </>
        )}
      </div>
    </nav>
  )
}

export default Navbar