'use client' import { useState, useEffect, useRef, useCallback, KeyboardEvent } from 'react' import Link from 'next/link' import Image from 'next/image' import { useQuery } from '@tanstack/react-query' import api from '@/services/api' interface UserSearchResult { id: string username: string displayName?: string avatar?: string } interface UserSearchApiResponse { users: UserSearchResult[] } interface UserSearchProps { onSelect?: (user: { username: string; id: string }) => void placeholder?: string className?: string } const GRADIENT_PALETTES = [ 'from-violet-500 to-purple-600', 'from-blue-500 to-cyan-500', 'from-emerald-500 to-teal-600', 'from-orange-500 to-rose-500', 'from-pink-500 to-fuchsia-600', 'from-amber-500 to-yellow-400', 'from-sky-500 to-indigo-600', 'from-lime-500 to-green-600', ] function getGradientForUsername(username: string): string { let hash = 0 for (let i = 0; i < username.length; i++) { hash = (hash * 31 + username.charCodeAt(i)) | 0 } return GRADIENT_PALETTES[Math.abs(hash) % GRADIENT_PALETTES.length] } function useDebounce(value: T, delay: number): T { const [debouncedValue, setDebouncedValue] = useState(value) useEffect(() => { const handler = setTimeout(() => setDebouncedValue(value), delay) return () => clearTimeout(handler) }, [value, delay]) return debouncedValue } async function searchUsers(query: string): Promise { const { data } = await api.get('/v1/users/search', { params: { q: query, limit: 8 }, }) return data.users ?? [] } export default function UserSearch({ onSelect, placeholder = 'Search users…', className = '' }: UserSearchProps) { const [inputValue, setInputValue] = useState('') const [isOpen, setIsOpen] = useState(false) const [activeIndex, setActiveIndex] = useState(-1) const debouncedQuery = useDebounce(inputValue.trim(), 300) const containerRef = useRef(null) const inputRef = useRef(null) const listRef = useRef(null) const { data: results = [], isFetching } = useQuery({ queryKey: ['user-search', debouncedQuery], queryFn: () => searchUsers(debouncedQuery), enabled: debouncedQuery.length >= 2, staleTime: 30_000, }) // Open dropdown whenever there is a qualifying query useEffect(() => { if (debouncedQuery.length >= 2) { setIsOpen(true) setActiveIndex(-1) } else { setIsOpen(false) } }, [debouncedQuery]) // Click-outside closes the dropdown useEffect(() => { function handlePointerDown(event: MouseEvent) { if (containerRef.current && !containerRef.current.contains(event.target as Node)) { setIsOpen(false) setActiveIndex(-1) } } document.addEventListener('mousedown', handlePointerDown) return () => document.removeEventListener('mousedown', handlePointerDown) }, []) // Scroll active item into view useEffect(() => { if (activeIndex < 0 || !listRef.current) return const item = listRef.current.children[activeIndex] as HTMLElement | undefined item?.scrollIntoView({ block: 'nearest' }) }, [activeIndex]) const handleSelect = useCallback( (user: UserSearchResult) => { setInputValue('') setIsOpen(false) setActiveIndex(-1) onSelect?.({ username: user.username, id: user.id }) }, [onSelect], ) const handleKeyDown = useCallback( (event: KeyboardEvent) => { if (!isOpen) return switch (event.key) { case 'ArrowDown': { event.preventDefault() setActiveIndex((prev) => (prev < results.length - 1 ? prev + 1 : 0)) break } case 'ArrowUp': { event.preventDefault() setActiveIndex((prev) => (prev > 0 ? prev - 1 : results.length - 1)) break } case 'Enter': { event.preventDefault() if (activeIndex >= 0 && results[activeIndex]) { handleSelect(results[activeIndex]) } break } case 'Escape': { event.preventDefault() setIsOpen(false) setActiveIndex(-1) inputRef.current?.blur() break } default: break } }, [isOpen, activeIndex, results, handleSelect], ) const showDropdown = isOpen && debouncedQuery.length >= 2 const showEmpty = showDropdown && !isFetching && results.length === 0 return (
{/* Search input */}
= 0 ? `user-search-option-${activeIndex}` : undefined} value={inputValue} onChange={(e) => setInputValue(e.target.value)} onKeyDown={handleKeyDown} placeholder={placeholder} autoComplete="off" className="w-full rounded-lg border border-border bg-background py-2 pl-9 pr-9 text-sm text-foreground placeholder:text-foreground/50 focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30" /> {/* Loading spinner */} {isFetching && ( )}
{/* Dropdown */} {showDropdown && (
{showEmpty ? (

No users found

) : (
    {results.map((user, index) => { const isActive = index === activeIndex const gradient = getGradientForUsername(user.username) const initial = user.username[0]?.toUpperCase() ?? '?' return (
  • handleSelect(user)} tabIndex={-1} > {/* Avatar */}
    {user.avatar ? ( {user.username} ) : ( )}
    {/* Text */}

    @{user.username}

    {user.displayName && (

    {user.displayName}

    )}
  • ) })}
)}
)}
) }