91 lines
2.8 KiB
TypeScript
91 lines
2.8 KiB
TypeScript
'use client'
|
|||
|
|
|
||
|
|
import Link from 'next/link'
|
||
|
|
import { useState, useEffect } from 'react'
|
||
|
|
import { useRouter } from 'next/navigation'
|
||
|
|
|
||
|
|
export function Navbar() {
|
||
|
|
const [cartCount, setCartCount] = useState(0)
|
||
|
|
const [user, setUser] = useState<{ name?: string; email: string; role: string } | null>(null)
|
||
|
|
const router = useRouter()
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
|
||
|
|
const count = cart.reduce((sum: number, item: { quantity: number }) => sum + item.quantity, 0)
|
||
|
|
setCartCount(count)
|
||
|
|
|
||
|
|
const userData = localStorage.getItem('user')
|
||
|
|
if (userData) {
|
||
|
|
try {
|
||
|
|
setUser(JSON.parse(userData))
|
||
|
|
} catch {
|
||
|
|
// ignore
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}, [])
|
||
|
|
|
||
|
|
async function handleLogout() {
|
||
|
|
await fetch('/api/auth/logout', { method: 'POST' })
|
||
|
|
localStorage.removeItem('user')
|
||
|
|
setUser(null)
|
||
|
|
router.push('/')
|
||
|
|
router.refresh()
|
||
|
|
}
|
||
|
|
|
||
|
|
return (
|
||
|
|
<header className="bg-white border-b border-gray-200">
|
||
|
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||
|
|
<div className="flex items-center justify-between h-16">
|
||
|
|
<Link href="/" className="text-xl font-bold text-gray-900">
|
||
|
|
ShopX
|
||
|
|
</Link>
|
||
|
|
|
||
|
|
<nav className="flex items-center gap-6 text-sm">
|
||
|
|
<Link href="/products" className="text-gray-600 hover:text-gray-900">
|
||
|
|
Products
|
||
|
|
</Link>
|
||
|
|
<Link href="/cart" className="text-gray-600 hover:text-gray-900 relative">
|
||
|
|
Cart
|
||
|
|
{cartCount > 0 && (
|
||
|
|
<span className="ml-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded-full">
|
||
|
|
{cartCount}
|
||
|
|
</span>
|
||
|
|
)}
|
||
|
|
</Link>
|
||
|
|
{user ? (
|
||
|
|
<>
|
||
|
|
<Link href="/account" className="text-gray-600 hover:text-gray-900">
|
||
|
|
Account
|
||
|
|
</Link>
|
||
|
|
{(user.role === 'ADMIN' || user.role === 'OWNER') && (
|
||
|
|
<Link href="/admin" className="text-gray-600 hover:text-gray-900">
|
||
|
|
Admin
|
||
|
|
</Link>
|
||
|
|
)}
|
||
|
|
<button
|
||
|
|
onClick={handleLogout}
|
||
|
|
className="text-gray-600 hover:text-gray-900"
|
||
|
|
>
|
||
|
|
Logout
|
||
|
|
</button>
|
||
|
|
</>
|
||
|
|
) : (
|
||
|
|
<>
|
||
|
|
<Link href="/login" className="text-gray-600 hover:text-gray-900">
|
||
|
|
Login
|
||
|
|
</Link>
|
||
|
|
<Link
|
||
|
|
href="/register"
|
||
|
|
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition-colors"
|
||
|
|
>
|
||
|
|
Register
|
||
|
|
</Link>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
</nav>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
</header>
|
||
|
|
)
|
||
|
|
}
|