import React, { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import './Navigation.css';

export default function Navigation() {
  const [scrolled, setScrolled] = useState(false);
  const [isOverlayOpen, setIsOverlayOpen] = useState(false);
  const location = useLocation();

  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 50);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Close overlay on route change — use a layout effect to avoid setState-in-body lint
  const prevPathRef = React.useRef(location.pathname);
  React.useLayoutEffect(() => {
    if (prevPathRef.current !== location.pathname) {
      prevPathRef.current = location.pathname;
      setIsOverlayOpen(false);
    }
  }, [location.pathname]);

  return (
    <>
      <nav className={`navigation ${scrolled ? 'scrolled glass-panel' : ''}`}>
        <div className="nav-container app-container">
          <Link to="/" className="logo">
            <img src="/logos/logo-dHIVE-2x.webp" alt="d-HIVE Logo" className="logo-image" />
          </Link>
          
          <button 
            className={`hamburger ${isOverlayOpen ? 'active' : ''}`}
            onClick={() => setIsOverlayOpen(!isOverlayOpen)}
            aria-label="Toggle menu"
          >
            <span></span>
            <span></span>
            <span></span>
          </button>
        </div>
      </nav>

      {/* Overlay Menu */}
      <div className={`nav-overlay ${isOverlayOpen ? 'open' : ''}`}>
        <div className="overlay-content">
          <Link to="/" className="overlay-link" onClick={() => setIsOverlayOpen(false)}>Home</Link>
          <Link to="/usecases" className="overlay-link" onClick={() => setIsOverlayOpen(false)}>Use Cases</Link>
          <Link to="/request-access" className="overlay-link" onClick={() => setIsOverlayOpen(false)}>Request Access</Link>
        </div>
      </div>
    </>
  );
}
