import { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import ThemeToggle from '../ThemeToggle';
import LanguageToggle from '../LanguageToggle';
import MobileMenu from './MobileMenu';
import logoUrl from '../../assets/logo.svg';
import { useLanguage } from '../../contexts/LanguageContext';
import { scrollToSection } from '../../utils/scrollUtils';
import type { Theme } from '../../data/types';

type Props = {
  theme: Theme;
  setTheme: React.Dispatch<React.SetStateAction<Theme>>;
};

export default function Navbar({
  theme,
  setTheme
}: Readonly<Props>) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [activeSection, setActiveSection] = useState<string>('');
  const location = useLocation();
  const navigate = useNavigate();
  const { texts } = useLanguage();

  const isLandingPage = location.pathname === '/de/' || location.pathname === '/en/' || location.pathname === '/';
  const technicalPath = location.pathname.startsWith('/en') ? '/en/technical' : '/de/technical';
  const menuItems = isLandingPage
    ? texts.navigation.landingMenuItems
    : texts.navigation.menuItems;

  // Track active section based on scroll position
  useEffect(() => {
    if (location.pathname !== technicalPath && !isLandingPage) {
      setActiveSection('');
      return;
    }

    const handleScroll = () => {
      const sections = menuItems.map(item => item.section.toLowerCase());
      const scrollPosition = window.scrollY + 100; // Offset for navbar height

      const reversedSections = [...sections].reverse();
      for (const section of reversedSections) {
        const element = document.getElementById(section);
        if (element && element.offsetTop <= scrollPosition) {
          setActiveSection(section);
          return;
        }
      }
      setActiveSection('');
    };

    handleScroll(); // Initial check
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [location.pathname, menuItems]);

  function handleNavigation(section: string): void {
    const sectionId = section.toLowerCase();
    scrollToSection(sectionId, location.pathname, navigate);

    // Close mobile menu if open
    setMenuOpen(false);
  }

  return (
    <div className={`navbar${isLandingPage ? ' navbar--landing' : ''}`}>
      <Link
        to={isLandingPage ? location.pathname : technicalPath}
        className="navbar__name"
        onClick={(e) => {
          e.preventDefault();
          window.scrollTo({ top: 0, behavior: 'smooth' });
        }}
      >
        <img src={logoUrl} alt={texts.navigation.logoAlt} className="navbar__logo" />
      </Link>
      <div className="navbar__container">
        {menuItems.map((item) => (
          <button
            key={item.label}
            onClick={() => handleNavigation(item.section)}
            className={`navbar__container__button ${activeSection === item.section.toLowerCase() ? 'navbar__container__button--active' : ''}`}
          >
            {item.label}
          </button>
        ))}
        <LanguageToggle />
        <ThemeToggle theme={theme} setTheme={setTheme} />
        {/* Burger Button für Mobile */}
        <button
          type="button"
          className={`navbar__burger-button ${menuOpen ? 'active' : ''}`}
          aria-label={texts.navigation.mobileMenuAriaLabel}
          aria-expanded={menuOpen}
          aria-controls="mobile-menu"
          onClick={() => setMenuOpen(!menuOpen)}
        >
          {[0, 1, 2].map(i => <span key={i} className="navbar__burger-button__item"></span>)}
        </button>

        <MobileMenu
          menuItems={menuItems}
          isOpen={menuOpen}
          onItemClick={handleNavigation}
          onClose={() => setMenuOpen(false)}
        />
      </div>
    </div>
  );
}
