'use client'; import { useState, useMemo, useRef, useEffect } from 'react'; import { Municipality } from '@/types/charging'; interface MunicipalitySelectorProps { municipalities: Municipality[]; selected: string; onChange: (slug: string) => void; } type SortOrder = 'asc' | 'desc'; export default function MunicipalitySelector({ municipalities, selected, onChange, }: MunicipalitySelectorProps) { const [searchTerm, setSearchTerm] = useState(''); const [showDropdown, setShowDropdown] = useState(false); const [sortOrder, setSortOrder] = useState('asc'); const [highlightedIndex, setHighlightedIndex] = useState(-1); const containerRef = useRef(null); const inputRef = useRef(null); const dropdownRef = useRef(null); // Get selected municipality display name const selectedMunicipality = municipalities.find(m => m.slug === selected); const displayValue = selectedMunicipality ? `${selectedMunicipality.name} (${selectedMunicipality.province})` : ''; // Get Nederland separately (always shown as sticky footer) const nederland = useMemo(() => municipalities.find(m => m.slug === 'nederland'), [municipalities] ); // Sort and filter municipalities (excluding Nederland) const filteredMunicipalities = useMemo(() => { // Exclude Nederland from regular list (it will be sticky at bottom) let filtered = municipalities.filter(m => m.slug !== 'nederland'); // Filter by search term if (searchTerm) { filtered = filtered.filter(m => m.name.toLowerCase().includes(searchTerm.toLowerCase()) || m.province.toLowerCase().includes(searchTerm.toLowerCase()) ); } // Sort alphabetically filtered = [...filtered].sort((a, b) => { const nameA = a.name.toLowerCase(); const nameB = b.name.toLowerCase(); return sortOrder === 'asc' ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA); }); return filtered; }, [municipalities, searchTerm, sortOrder]); // Reset highlighted index when search term or dropdown visibility changes useEffect(() => { setHighlightedIndex(-1); }, [searchTerm, showDropdown]); // Scroll highlighted item into view useEffect(() => { if (highlightedIndex >= 0 && dropdownRef.current) { const highlightedElement = dropdownRef.current.querySelector( `[data-index="${highlightedIndex}"]` ); if (highlightedElement) { highlightedElement.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } } }, [highlightedIndex]); // Close dropdown when clicking outside useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(event.target as Node)) { setShowDropdown(false); setSearchTerm(''); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); // Global keyboard shortcut (Cmd/Ctrl + K) to focus search useEffect(() => { const handleGlobalKeydown = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); inputRef.current?.focus(); setShowDropdown(true); } }; document.addEventListener('keydown', handleGlobalKeydown); return () => document.removeEventListener('keydown', handleGlobalKeydown); }, []); const handleSelect = (slug: string) => { onChange(slug); setShowDropdown(false); setSearchTerm(''); setHighlightedIndex(-1); }; const toggleSort = () => { setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc'); }; // Keyboard navigation const handleKeyDown = (e: React.KeyboardEvent) => { if (!showDropdown) { // Open dropdown on ArrowDown when closed if (e.key === 'ArrowDown') { e.preventDefault(); setShowDropdown(true); } return; } // Total items including sticky Nederland const totalItems = filteredMunicipalities.length + (nederland ? 1 : 0); switch (e.key) { case 'ArrowDown': e.preventDefault(); setHighlightedIndex(prev => prev < totalItems - 1 ? prev + 1 : prev ); break; case 'ArrowUp': e.preventDefault(); setHighlightedIndex(prev => (prev > 0 ? prev - 1 : -1)); break; case 'Enter': e.preventDefault(); if (highlightedIndex >= 0 && highlightedIndex < filteredMunicipalities.length) { handleSelect(filteredMunicipalities[highlightedIndex].slug); } else if (highlightedIndex === filteredMunicipalities.length && nederland) { // Nederland is selected (sticky footer) handleSelect(nederland.slug); } else if (filteredMunicipalities.length === 1) { // Auto-select if only one result handleSelect(filteredMunicipalities[0].slug); } break; case 'Escape': e.preventDefault(); setShowDropdown(false); setSearchTerm(''); setHighlightedIndex(-1); inputRef.current?.blur(); break; case 'Tab': // Close dropdown on Tab setShowDropdown(false); setSearchTerm(''); setHighlightedIndex(-1); break; } }; return (
{ setSearchTerm(e.target.value); setShowDropdown(true); }} onFocus={() => setShowDropdown(true)} onKeyDown={handleKeyDown} placeholder={selectedMunicipality ? displayValue : "Selecteer gemeente..."} className="w-full px-3 md:px-4 py-2.5 md:py-2 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 text-sm" autoComplete="off" role="combobox" aria-autocomplete="list" aria-expanded={showDropdown} aria-controls="municipality-listbox" aria-activedescendant={ highlightedIndex >= 0 ? `municipality-option-${highlightedIndex}` : undefined } />
{showDropdown && (
{/* Header */}
{filteredMunicipalities.length} gemeentes
⌘K
{/* Municipality list */} {filteredMunicipalities.length > 0 ? ( filteredMunicipalities.map((m, index) => ( )) ) : (
Geen gemeentes gevonden voor "{searchTerm}"
)} {/* Sticky Nederland footer */} {nederland && (
)}
)}
); }