477 lines
17 KiB
TypeScript

'use client'
import { useState, useEffect, useRef } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet'
import { Menu, Search, StickyNote, Tag, Moon, Sun, X, Bell, Sparkles, Grid3x3, Settings, LogOut, User, Shield, Coffee } from 'lucide-react'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { cn } from '@/lib/utils'
import { useLabels } from '@/context/LabelContext'
import { LabelFilter } from './label-filter'
import { NotificationPanel } from './notification-panel'
import { updateTheme } from '@/app/actions/profile'
import { useDebounce } from '@/hooks/use-debounce'
import { useLanguage } from '@/lib/i18n'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useSession, signOut } from 'next-auth/react'
interface HeaderProps {
selectedLabels?: string[]
selectedColor?: string | null
onLabelFilterChange?: (labels: string[]) => void
onColorFilterChange?: (color: string | null) => void
user?: any
}
export function Header({
selectedLabels = [],
selectedColor = null,
onLabelFilterChange,
onColorFilterChange,
user
}: HeaderProps = {}) {
const [searchQuery, setSearchQuery] = useState('')
const [theme, setTheme] = useState<'light' | 'dark'>('light')
const [isSidebarOpen, setIsSidebarOpen] = useState(false)
const [isSemanticSearching, setIsSemanticSearching] = useState(false)
const pathname = usePathname()
const router = useRouter()
const searchParams = useSearchParams()
const { labels, setNotebookId } = useLabels()
const { t } = useLanguage()
const { data: session } = useSession()
// Track last pushed search to avoid infinite loops
const lastPushedSearch = useRef<string | null>(null)
const currentLabels = searchParams.get('labels')?.split(',').filter(Boolean) || []
const currentSearch = searchParams.get('search') || ''
const currentColor = searchParams.get('color') || ''
const currentUser = user || session?.user
// Initialize search query from URL ONLY on mount
useEffect(() => {
setSearchQuery(currentSearch)
lastPushedSearch.current = currentSearch
}, []) // Run only once on mount
// Sync LabelContext notebookId with URL notebook parameter
const currentNotebook = searchParams.get('notebook')
useEffect(() => {
setNotebookId(currentNotebook || null)
}, [currentNotebook, setNotebookId])
// Prevent body scroll when mobile menu is open
useEffect(() => {
if (isSidebarOpen) {
document.body.style.overflow = 'hidden'
document.body.style.position = 'fixed'
document.body.style.width = '100%'
} else {
document.body.style.overflow = ''
document.body.style.position = ''
document.body.style.width = ''
}
return () => {
document.body.style.overflow = ''
document.body.style.position = ''
document.body.style.width = ''
}
}, [isSidebarOpen])
// Close mobile menu on Esc key press
useEffect(() => {
const handleEscapeKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isSidebarOpen) {
setIsSidebarOpen(false)
}
}
if (isSidebarOpen) {
document.addEventListener('keydown', handleEscapeKey)
}
return () => {
document.removeEventListener('keydown', handleEscapeKey)
}
}, [isSidebarOpen])
// Simple debounced search with URL update (150ms for more responsiveness)
const debouncedSearchQuery = useDebounce(searchQuery, 150)
useEffect(() => {
// Skip if search hasn't changed or if we already pushed this value
if (debouncedSearchQuery === lastPushedSearch.current) return
// Build new params preserving other filters
const params = new URLSearchParams(searchParams.toString())
if (debouncedSearchQuery.trim()) {
params.set('search', debouncedSearchQuery)
} else {
params.delete('search')
}
const newUrl = `/?${params.toString()}`
// Mark as pushed before calling router.push to prevent loops
lastPushedSearch.current = debouncedSearchQuery
router.push(newUrl)
}, [debouncedSearchQuery])
// Handle semantic search button click
const handleSemanticSearch = () => {
if (!searchQuery.trim()) return
// Add semantic flag to URL
const params = new URLSearchParams(searchParams.toString())
params.set('search', searchQuery)
params.set('semantic', 'true')
router.push(`/?${params.toString()}`)
// Show loading state briefly
setIsSemanticSearching(true)
setTimeout(() => setIsSemanticSearching(false), 1500)
}
useEffect(() => {
const savedTheme = currentUser?.theme || localStorage.getItem('theme') || 'light'
// Don't persist on initial load to avoid unnecessary DB calls
applyTheme(savedTheme, false)
}, [currentUser])
const applyTheme = async (newTheme: string, persist = true) => {
setTheme(newTheme as any)
localStorage.setItem('theme', newTheme)
// Remove all theme classes first
document.documentElement.classList.remove('dark')
document.documentElement.removeAttribute('data-theme')
if (newTheme === 'dark') {
document.documentElement.classList.add('dark')
} else if (newTheme !== 'light') {
document.documentElement.setAttribute('data-theme', newTheme)
if (newTheme === 'midnight') {
document.documentElement.classList.add('dark')
}
}
if (persist && currentUser) {
await updateTheme(newTheme)
}
}
const handleSearch = (query: string) => {
setSearchQuery(query)
// URL update is now handled by the debounced useEffect
}
const removeLabelFilter = (labelToRemove: string) => {
const newLabels = currentLabels.filter(l => l !== labelToRemove)
const params = new URLSearchParams(searchParams.toString())
if (newLabels.length > 0) {
params.set('labels', newLabels.join(','))
} else {
params.delete('labels')
}
router.push(`/?${params.toString()}`)
}
const removeColorFilter = () => {
const params = new URLSearchParams(searchParams.toString())
params.delete('color')
router.push(`/?${params.toString()}`)
}
const clearAllFilters = () => {
// Clear only label and color filters, keep search
const params = new URLSearchParams(searchParams.toString())
params.delete('labels')
params.delete('color')
router.push(`/?${params.toString()}`)
}
const handleFilterChange = (newLabels: string[]) => {
const params = new URLSearchParams(searchParams.toString())
if (newLabels.length > 0) {
params.set('labels', newLabels.join(','))
} else {
params.delete('labels')
}
router.push(`/?${params.toString()}`)
}
const handleColorChange = (newColor: string | null) => {
const params = new URLSearchParams(searchParams.toString())
if (newColor) {
params.set('color', newColor)
} else {
params.delete('color')
}
router.push(`/?${params.toString()}`)
}
const toggleLabelFilter = (labelName: string) => {
const newLabels = currentLabels.includes(labelName)
? currentLabels.filter(l => l !== labelName)
: [...currentLabels, labelName]
const params = new URLSearchParams(searchParams.toString())
if (newLabels.length > 0) {
params.set('labels', newLabels.join(','))
} else {
params.delete('labels')
}
router.push(`/?${params.toString()}`)
}
const NavItem = ({ href, icon: Icon, label, active, onClick }: any) => {
const content = (
<>
<Icon className={cn("h-5 w-5", active && "fill-current text-amber-900")} />
{label}
</>
)
if (onClick) {
return (
<button
onClick={onClick}
className={cn(
"w-full flex items-center gap-3 px-4 py-3 rounded-r-full text-sm font-medium transition-colors mr-2 text-left",
active
? "bg-[#EFB162] text-amber-900"
: "hover:bg-gray-100 dark:hover:bg-zinc-800 text-gray-700 dark:text-gray-300"
)}
style={{ minHeight: '44px' }}
aria-pressed={active}
>
{content}
</button>
)
}
return (
<Link
href={href}
onClick={() => setIsSidebarOpen(false)}
className={cn(
"flex items-center gap-3 px-4 py-3 rounded-r-full text-sm font-medium transition-colors mr-2",
active
? "bg-[#EFB162] text-amber-900"
: "hover:bg-gray-100 dark:hover:bg-zinc-800 text-gray-700 dark:text-gray-300"
)}
style={{ minHeight: '44px' }}
aria-current={active ? 'page' : undefined}
>
{content}
</Link>
)
}
const hasActiveFilters = currentLabels.length > 0 || !!currentColor
return (
<>
<header className="h-20 bg-background/90 backdrop-blur-sm border-b border-transparent flex items-center justify-between px-6 lg:px-12 flex-shrink-0 z-30 sticky top-0">
{/* Mobile Menu Button */}
<Sheet open={isSidebarOpen} onOpenChange={setIsSidebarOpen}>
<SheetTrigger asChild>
<Button
variant="ghost"
size="icon"
className="lg:hidden mr-4 text-muted-foreground"
aria-label="Open menu"
aria-expanded={isSidebarOpen}
>
<Menu className="h-6 w-6" />
</Button>
</SheetTrigger>
<SheetContent side="left" className="w-[280px] sm:w-[320px] p-0 pt-4">
<SheetHeader className="px-4 mb-4 flex items-center justify-between">
<SheetTitle className="flex items-center gap-2 text-xl font-normal">
<StickyNote className="h-6 w-6 text-primary" />
{t('nav.workspace')}
</SheetTitle>
<Button
variant="ghost"
size="icon"
onClick={() => setIsSidebarOpen(false)}
className="text-muted-foreground hover:text-foreground"
aria-label="Close menu"
style={{ width: '44px', height: '44px' }}
>
<X className="h-5 w-5" />
</Button>
</SheetHeader>
<div className="flex flex-col gap-1 py-2">
<NavItem
href="/"
icon={StickyNote}
label={t('nav.notes')}
active={pathname === '/' && !hasActiveFilters}
/>
<NavItem
href="/reminders"
icon={Bell}
label={t('reminder.title')}
active={pathname === '/reminders'}
/>
<div className="my-2 px-4 flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">{t('labels.title')}</span>
</div>
{labels.map(label => (
<NavItem
key={label.id}
icon={Tag}
label={label.name}
active={currentLabels.includes(label.name)}
onClick={() => toggleLabelFilter(label.name)}
/>
))}
<div className="my-2 border-t border-gray-200 dark:border-zinc-800" />
<NavItem
href="/archive"
icon={Settings}
label={t('nav.archive')}
active={pathname === '/archive'}
/>
<NavItem
href="/trash"
icon={Tag}
label={t('nav.trash')}
active={pathname === '/trash'}
/>
</div>
</SheetContent>
</Sheet>
{/* Search Bar */}
<div className="flex-1 max-w-2xl flex items-center bg-card rounded-lg px-4 py-3 shadow-sm border border-transparent focus-within:border-primary/50 focus-within:ring-2 focus-within:ring-primary/10 transition-all">
<Search className="text-muted-foreground text-xl" />
<input
className="bg-transparent border-none outline-none focus:ring-0 w-full text-sm text-foreground ml-3 placeholder-muted-foreground"
placeholder={t('search.placeholder') || "Search notes, tags, or notebooks..."}
type="text"
value={searchQuery}
onChange={(e) => handleSearch(e.target.value)}
/>
{/* IA Search Button */}
<button
onClick={handleSemanticSearch}
disabled={!searchQuery.trim() || isSemanticSearching}
className={cn(
"flex items-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-colors min-h-[36px]",
"hover:bg-accent",
searchParams.get('semantic') === 'true'
? "bg-primary/20 text-primary"
: "text-muted-foreground hover:text-primary",
"disabled:opacity-50 disabled:cursor-not-allowed"
)}
title={t('search.semanticTooltip')}
>
<Sparkles className={cn("h-3.5 w-3.5", isSemanticSearching && "animate-spin")} />
</button>
{searchQuery && (
<button
onClick={() => handleSearch('')}
className="ml-2 text-muted-foreground hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{/* Right Side Actions */}
<div className="flex items-center space-x-3 ml-6">
{/* Label Filter */}
<LabelFilter
selectedLabels={currentLabels}
onFilterChange={handleFilterChange}
/>
{/* Grid View Button */}
<button className="p-2.5 text-muted-foreground hover:bg-accent rounded-lg transition-colors duration-200 min-h-[44px] min-w-[44px]">
<Grid3x3 className="text-xl" />
</button>
{/* Theme Toggle */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="p-2.5 text-muted-foreground hover:bg-accent rounded-lg transition-colors duration-200 min-h-[44px] min-w-[44px]">
{theme === 'light' ? <Sun className="text-xl" /> : <Moon className="text-xl" />}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => applyTheme('light')}>{t('settings.themeLight')}</DropdownMenuItem>
<DropdownMenuItem onClick={() => applyTheme('dark')}>{t('settings.themeDark')}</DropdownMenuItem>
<DropdownMenuItem onClick={() => applyTheme('midnight')}>Midnight</DropdownMenuItem>
<DropdownMenuItem onClick={() => applyTheme('sepia')}>Sepia</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Notifications */}
<NotificationPanel />
</div>
</header>
{/* Active Filters Bar */}
{hasActiveFilters && (
<div className="px-6 lg:px-12 pb-3 flex items-center gap-2 overflow-x-auto border-t border-border pt-2 bg-background/50 backdrop-blur-sm animate-in slide-in-from-top-2">
{currentColor && (
<Badge variant="secondary" className="flex items-center gap-1 h-7 whitespace-nowrap pl-2 pr-1">
<div className={cn("w-3 h-3 rounded-full border border-black/10", `bg-${currentColor}-500`)} />
{t('notes.color')}: {currentColor}
<button onClick={removeColorFilter} className="ml-1 hover:bg-black/10 dark:hover:bg-white/10 rounded-full p-0.5 min-h-[24px] min-w-[24px]">
<X className="h-3 w-3" />
</button>
</Badge>
)}
{currentLabels.map(label => (
<Badge key={label} variant="secondary" className="flex items-center gap-1 h-7 whitespace-nowrap pl-2 pr-1">
<Tag className="h-3 w-3" />
{label}
<button onClick={() => removeLabelFilter(label)} className="ml-1 hover:bg-black/10 dark:hover:bg-white/10 rounded-full p-0.5">
<X className="h-3 w-3" />
</button>
</Badge>
))}
{(currentLabels.length > 0 || currentColor) && (
<Button
variant="ghost"
size="sm"
onClick={clearAllFilters}
className="h-7 text-xs text-primary hover:text-primary hover:bg-accent whitespace-nowrap ml-auto"
>
{t('labels.clearAll')}
</Button>
)}
</div>
)}
</>
)
}