import { useState, useEffect, useRef } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { motion } from 'motion/react'; import { useTranslation } from '../../i18n'; import { debounce } from '../../utils/debounce'; import styles from './Navbar.module.css'; export function Navbar() { const { t, language, setLanguage } = useTranslation(); const location = useLocation(); const [isScrolled, setIsScrolled] = useState(false); const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); const [indicatorX, setIndicatorX] = useState(0); const navLinksRef = useRef(null); const linkRefs = useRef<(HTMLAnchorElement | null)[]>([]); const navLinks = [ { path: '/', label: t.nav.home }, { path: '/about', label: t.nav.about }, { path: '/contact', label: t.nav.contact }, ]; // Find active index const activeIndex = navLinks.findIndex((link) => link.path === location.pathname); useEffect(() => { let ticking = false; const handleScroll = () => { if (!ticking) { window.requestAnimationFrame(() => { setIsScrolled(window.scrollY > 20); ticking = false; }); ticking = true; } }; window.addEventListener('scroll', handleScroll, { passive: true }); return () => window.removeEventListener('scroll', handleScroll); }, []); useEffect(() => { setIsMobileMenuOpen(false); }, [location.pathname]); // Calculate indicator position useEffect(() => { const updateIndicatorPosition = () => { const activeLink = linkRefs.current[activeIndex]; const container = navLinksRef.current; if (activeLink && container) { const containerRect = container.getBoundingClientRect(); const linkRect = activeLink.getBoundingClientRect(); // Calculate center of the link relative to the container const centerX = linkRect.left - containerRect.left + linkRect.width / 2; setIndicatorX(centerX); } }; updateIndicatorPosition(); const debouncedUpdate = debounce(updateIndicatorPosition, 150); window.addEventListener('resize', debouncedUpdate); return () => { window.removeEventListener('resize', debouncedUpdate); debouncedUpdate.cancel(); }; }, [activeIndex, language]); // Recalculate when active link or language changes const toggleLanguage = () => { setLanguage(language === 'de' ? 'en' : 'de'); }; return ( ); }