import React, { useState, useEffect, memo, useCallback } from "react";
import { motion, AnimatePresence, useReducedMotion } from "framer-motion";
import { Menu, X, Phone, Mail, Recycle } from "lucide-react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import LanguageSelector from "@/components/LanguageSelector";

const Navigation = memo(() => {
  const [isOpen, setIsOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const prefersReducedMotion = useReducedMotion();
  const { t, i18n } = useTranslation();

  useEffect(() => {
    let ticking = false;
    
    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          setScrolled(window.scrollY > 50);
          ticking = false;
        });
        ticking = true;
      }
    };

    // Handle mobile viewport changes that affect sticky headers
    const handleResize = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          // Force recalculation on mobile viewport changes
          const nav = document.querySelector('nav');
          if (nav) {
            nav.style.transform = 'translateZ(0)'; // Force hardware acceleration
          }
          ticking = false;
        });
        ticking = true;
      }
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("resize", handleResize, { passive: true });
    window.addEventListener("orientationchange", handleResize, { passive: true });
    
    return () => {
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", handleResize);
      window.removeEventListener("orientationchange", handleResize);
    };
  }, []);

  // Scroll behavior on route changes
  useEffect(() => {
    if (location.pathname === '/muanyagipar' || location.pathname === '/epitoipar') {
      // Always scroll to top when navigating to product pages
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  }, [location.pathname]);

  // Menu items with proper translation dependency
  const menuItems = React.useMemo(() => [
    { name: t('navigation.home'), href: "/" },
    { name: t('navigation.about'), href: "#about" },
    { name: t('navigation.process'), href: "#process" },
    { name: t('navigation.products'), href: "#products" },
    { name: t('navigation.contact'), href: "#contact" }
  ], [t]);

  // Enhanced navigation handler with mobile-optimized smooth scrolling
  const handleNavigation = useCallback((href: string, closeMobileMenu: boolean = false) => {
    console.log('Navigation clicked:', href);
    
    // Always close mobile menu on any navigation
    setIsOpen(false);
    
    if (href === '/') {
      // Navigate to home page
      if (location.pathname !== '/') {
        navigate('/');
      } else {
        // Already on home, scroll to top smoothly
        window.scrollTo({ 
          top: 0, 
          behavior: 'smooth' 
        });
      }
    } else if (href.startsWith('#')) {
      // Landing page sections with mobile-optimized smooth scrolling
      if (location.pathname !== '/') {
        // Navigate to home first, then handle scrolling
        navigate('/');
        // Use longer timeout for mobile devices
        setTimeout(() => {
          scrollToSection(href.substring(1));
        }, 500);
      } else {
        // Already on home page, scroll directly
        setTimeout(() => {
          scrollToSection(href.substring(1));
        }, 100); // Small delay to ensure menu closes
      }
    } else {
      // External routes (like /muanyagipar, /epitoipar)
      navigate(href);
    }
  }, [location.pathname, navigate]);

  // Mobile-optimized scroll to section function
  const scrollToSection = useCallback((sectionId: string) => {
    const element = document.getElementById(sectionId);
    if (!element) return;

    // Enhanced mobile detection and offset calculation
    const isMobile = window.innerWidth < 1024;
    const navigationEl = document.querySelector('nav');
    let headerHeight = 80; // default

    if (navigationEl) {
      headerHeight = navigationEl.offsetHeight;
      // Add extra padding for mobile to ensure content is visible
      headerHeight += isMobile ? 30 : 20;
    }

    // Use getBoundingClientRect for more accurate positioning
    const elementRect = element.getBoundingClientRect();
    const currentScrollY = window.scrollY;
    const targetY = currentScrollY + elementRect.top - headerHeight;

    // Smooth scroll with fallback for older browsers
    try {
      window.scrollTo({
        top: Math.max(0, targetY),
        behavior: 'smooth'
      });
    } catch (error) {
      // Fallback for browsers that don't support smooth scrolling
      window.scrollTo(0, Math.max(0, targetY));
    }

    // Update hash for browser navigation
    window.history.pushState(null, '', `#${sectionId}`);
  }, []);

  const handleToggleMenu = useCallback((e?: React.MouseEvent) => {
    e?.preventDefault();
    setIsOpen(prev => !prev);
  }, []);

  // Close mobile menu when clicking outside or on overlay
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const nav = document.querySelector('nav');
      if (isOpen && nav && !nav.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    const handleEscapeKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && isOpen) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('keydown', handleEscapeKey);
      // Prevent body scroll when menu is open on mobile
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscapeKey);
      document.body.style.overflow = 'unset';
    };
  }, [isOpen]);

  return (
    <motion.nav
      initial={prefersReducedMotion ? {} : { y: -100 }}
      animate={prefersReducedMotion ? {} : { y: 0 }}
      className={`fixed top-0 w-full z-50 transition-all duration-500 transform-gpu ${
        scrolled 
          ? "bg-white/10 backdrop-blur-md border-b border-white/20 shadow-lg" 
          : "bg-white/5 backdrop-blur-sm"
      }`}
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        willChange: 'transform',
        backfaceVisibility: 'hidden',
        WebkitBackfaceVisibility: 'hidden',
      }}
      role="navigation"
      aria-label={t('aria.navigation')}
    >
      <div className="container mx-auto px-1 md:px-2">
        <div className="flex items-center justify-between h-20 md:h-20">
          {/* Logo with optimized animations */}
          <motion.div
            whileHover={prefersReducedMotion ? {} : { scale: 1.05 }}
            className="flex items-center"
          >
            <button
              onClick={() => handleNavigation('/')}
              className="flex items-center gap-2 md:gap-3 mr-8 lg:mr-12 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2 focus:ring-offset-transparent rounded-lg p-1"
              aria-label={t('navigation.home')}
            >
              <div className="flex items-center justify-center w-8 h-8 md:w-10 md:h-10">
                <motion.div
                  animate={{ rotate: 360 }}
                  transition={{ duration: 8, repeat: Infinity, ease: "linear" }}
                  className="flex items-center justify-center w-full h-full text-primary"
                  style={{ 
                    color: 'hsl(var(--primary))'
                  }}
                >
                  <Recycle 
                    size={32} 
                    className="w-6 h-6 md:w-8 md:h-8" 
                    strokeWidth={2.5}
                    fill="none"
                    stroke="currentColor"
                  />
                </motion.div>
              </div>
              <div className="flex flex-col items-start leading-tight">
                <span className="inline-block bg-gradient-to-r from-teal-400 via-cyan-500 to-blue-500 bg-clip-text text-transparent text-xl xs:text-2xl sm:text-3xl md:text-4xl lg:text-3xl xl:text-4xl font-bold font-display">
                  {t('hero.title')}
                </span>
                <span className={`text-sm font-medium tracking-wide whitespace-nowrap transition-colors duration-300 ${
                  scrolled ? 'text-muted-foreground' : 'text-gray-200'
                }`}>
                  {t('brand.tagline')}
                </span>
              </div>
            </button>
          </motion.div>

          {/* Desktop Menu */}
          <div className="hidden lg:flex items-center space-x-2 xl:space-x-3">
            {menuItems.map((item) => (
              <button
                key={item.href}
                onClick={() => handleNavigation(item.href)}
                className={`text-sm lg:text-base font-medium transition-colors hover:text-primary focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2 focus:ring-offset-transparent rounded-sm px-1.5 py-1 whitespace-nowrap ${
                  scrolled ? "text-foreground" : "text-white"
                }`}
                aria-label={t('aria.go_to_section', { section: item.name })}
              >
                {item.name}
              </button>
            ))}
            
            {/* Product Pages */}
            <div className="flex items-center space-x-1.5 lg:space-x-2 ml-2 lg:ml-3 border-l border-border pl-2 lg:pl-3">
              <Link to="/muanyagipar" className="inline-block">
                <Button variant="outline" size="sm" className={`text-xs transition-all duration-300 px-2 py-1 h-7 ${
                  scrolled ? "text-foreground border-border hover:bg-accent hover:text-accent-foreground" : "text-white border-white hover:bg-white hover:text-secondary"
                }`}>
                  {t('navigation.plastics')}
                </Button>
              </Link>
              <Link to="/epitoipar" className="inline-block">
                <Button variant="outline" size="sm" className={`text-xs transition-all duration-300 px-2 py-1 h-7 ${
                  scrolled ? "text-foreground border-border hover:bg-accent hover:text-accent-foreground" : "text-white border-white hover:bg-white hover:text-secondary"
                }`}>
                  {t('navigation.construction')}
                </Button>
              </Link>
            </div>

            {/* Contact Info - Compact on laptop, full on desktop */}
            <div className="flex items-center space-x-1.5 lg:space-x-2 ml-2 lg:ml-3 border-l border-border pl-2 lg:pl-3">
              <a 
                href="tel:+3622582034"
                className={`flex items-center gap-1 text-xs transition-colors hover:text-primary focus:outline-none focus:ring-2 focus:ring-primary/50 rounded-sm px-1 py-0.5 ${
                  scrolled ? "text-muted-foreground hover:text-primary" : "text-gray-300 hover:text-white"
                }`}
                aria-label={t('aria.call_phone')}
                title="+36 22 582 034"
              >
                <Phone size={12} aria-hidden="true" />
                <span className="hidden xl:inline">+36 22 582 034</span>
              </a>
              <a 
                href="mailto:office@reus.hu" 
                className={`flex items-center gap-1 text-xs transition-colors hover:text-primary focus:outline-none focus:ring-2 focus:ring-primary/50 rounded-sm px-1 py-0.5 ${
                  scrolled ? "text-muted-foreground hover:text-primary" : "text-gray-300 hover:text-white"
                }`}
                aria-label={t('aria.send_email')}
                title="office@reus.hu"
              >
                <Mail size={12} aria-hidden="true" />
                <span className="hidden xl:inline">office@reus.hu</span>
              </a>
            </div>

            {/* Language Selector */}
            <div className="ml-2 lg:ml-3 border-l border-border pl-2 lg:pl-3">
              <LanguageSelector />
            </div>
          </div>

          {/* Mobile Menu Button */}
          <Button
            variant="ghost"
            size="sm"
            className="lg:hidden p-2 focus-visible:ring-0 focus-visible:ring-offset-0 shadow-none hover:shadow-none focus:shadow-none"
            onClick={handleToggleMenu}
            aria-expanded={isOpen}
            aria-label={isOpen ? t('aria.close_menu') : t('aria.open_menu')}
          >
            {isOpen ? <X size={20} /> : <Menu size={20} />}
          </Button>
        </div>
      </div>

      {/* Mobile Menu Overlay */}
      <AnimatePresence>
        {isOpen && (
          <>
            {/* Overlay backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="lg:hidden fixed inset-0 bg-black/20 backdrop-blur-sm z-40"
              onClick={() => setIsOpen(false)}
            />
            
            {/* Mobile Menu */}
            <motion.div
              initial={prefersReducedMotion ? { opacity: 0 } : { opacity: 0, y: -20 }}
              animate={prefersReducedMotion ? { opacity: 1 } : { opacity: 1, y: 0 }}
              exit={prefersReducedMotion ? { opacity: 0 } : { opacity: 0, y: -20 }}
              transition={{ duration: 0.3, ease: "easeOut" }}
              className="lg:hidden fixed top-[80px] left-0 right-0 bg-background/95 backdrop-blur-sm border-t border-border z-50 max-h-[calc(100vh-80px)] overflow-y-auto"
            >
            <div className="container mx-auto px-4 py-3">
              <div className="flex flex-col space-y-2">
                {menuItems.map((item) => (
                  <motion.button
                    key={item.href}
                    whileTap={{ scale: 0.98 }}
                    onClick={(e) => {
                      e.preventDefault();
                      handleNavigation(item.href, true);
                    }}
                    className="text-left py-2 px-3 text-foreground hover:text-primary hover:bg-accent/50 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary/50 rounded-lg w-full font-medium text-base active:bg-accent"
                    aria-label={t('aria.go_to_section', { section: item.name })}
                  >
                    {item.name}
                  </motion.button>
                ))}
                
                <div className="border-t border-border pt-4 mt-4">
                  <div className="flex flex-col space-y-3">
                    <Link 
                      to="/muanyagipar" 
                      onClick={() => setIsOpen(false)}
                      className="w-full"
                    >
                      <Button variant="outline" className="w-full justify-start">
                        {t('navigation.plastics')}
                      </Button>
                    </Link>
                    <Link 
                      to="/epitoipar" 
                      onClick={() => setIsOpen(false)}
                      className="w-full"
                    >
                      <Button variant="outline" className="w-full justify-start">
                        {t('navigation.construction')}
                      </Button>
                    </Link>
                  </div>
                  
                  {/* Mobile Language Selector */}
                  <div className="mt-4 flex justify-center">
                    <LanguageSelector />
                  </div>
                </div>

                 <div className="border-t border-border pt-4 mt-4 space-y-3">
                  <a 
                    href="tel:+3622582034" 
                    className="flex items-center gap-2 text-sm text-muted-foreground hover:text-primary transition-colors focus:outline-none focus:ring-2 focus:ring-primary/50 rounded-sm px-2 py-1"
                    aria-label={t('aria.call_phone')}
                    onClick={() => setIsOpen(false)}
                  >
                    <Phone size={16} aria-hidden="true" />
                    +36 22 582 034
                  </a>
                  <a 
                    href="mailto:office@reus.hu" 
                    className="flex items-center gap-2 text-sm text-muted-foreground hover:text-primary transition-colors focus:outline-none focus:ring-2 focus:ring-primary/50 rounded-sm px-2 py-1"
                    aria-label={t('aria.send_email')}
                    onClick={() => setIsOpen(false)}
                  >
                    <Mail size={16} aria-hidden="true" />
                    office@reus.hu
                  </a>
                </div>
              </div>
            </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </motion.nav>
  );
});

Navigation.displayName = 'Navigation';

export default Navigation;