import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Button } from "@/components/ui/button";
import { Menu, X, ChevronDown } from "lucide-react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { useLanguage } from "@/contexts/LanguageContext";
import { useIsMobile } from "@/hooks/use-mobile";
import { navigateAndScroll } from "@/utils/scrollToSection";
import LanguageSwitcher from "@/components/LanguageSwitcher";
import SkipLinks from "@/components/SkipLinks";

const FREE_AUDIT_URL = 'https://audit.arcconsulting.io';

const Navbar = () => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [navbarVisible, setNavbarVisible] = useState(true);
  const [resourcesOpen, setResourcesOpen] = useState(false);
  const lastScrollY = useRef(0);
  const resourcesRef = useRef<HTMLDivElement>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const location = useLocation();
  const navigate = useNavigate();
  const isHomePage = location.pathname === '/';
  const { t } = useLanguage();
  const isMobile = useIsMobile();

  const RESOURCE_ITEMS = [
    { label: t('nav.blog'), to: '/blog', type: 'route' as const },
    { label: t('nav.revenueCalculator'), to: '/revenue-calculator', type: 'route' as const },
    { label: t('nav.certifications'), to: '/certifications', type: 'route' as const },
    { label: t('nav.howItWorks'), to: '/#how-it-works', type: 'hash' as const },
  ];

  // Optimized scroll handler with RAF
  useEffect(() => {
    let ticking = false;
    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          const currentScrollY = window.scrollY;
          setIsScrolled(currentScrollY > 10);
          if (isMobile && Math.abs(currentScrollY - lastScrollY.current) > 10) {
            if (currentScrollY > lastScrollY.current && currentScrollY > 100) {
              setNavbarVisible(false);
              setMobileMenuOpen(false);
            } else {
              setNavbarVisible(true);
            }
            lastScrollY.current = currentScrollY;
          }
          ticking = false;
        });
        ticking = true;
      }
    };
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, [isMobile]);



  const handleCloseMenu = useCallback(() => {
    setMobileMenuOpen(false);
  }, []);

  // Close menu on escape
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setMobileMenuOpen(false);
        setResourcesOpen(false);
      }
    };
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, []);

  // Click outside to close resources dropdown
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (resourcesRef.current && !resourcesRef.current.contains(e.target as Node)) {
        setResourcesOpen(false);
      }
    };
    if (resourcesOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [resourcesOpen]);

  // Reset on route change
  useEffect(() => {
    window.scrollTo(0, 0);
    setMobileMenuOpen(false);
    setResourcesOpen(false);
  }, [location.pathname]);

  // Prevent body scroll when mobile menu is open
  useEffect(() => {
    document.body.style.overflow = mobileMenuOpen ? 'hidden' : 'unset';
    return () => { document.body.style.overflow = 'unset'; };
  }, [mobileMenuOpen]);

  const isCurrentRoute = (path: string) => location.pathname === path;
  const isResourcesActive = RESOURCE_ITEMS.some(
    (item) => item.type === 'route' && location.pathname.startsWith(item.to)
  );

  const getNavLinkClass = (isActive = false) =>
    `transition-all duration-200 hover:text-primary ${
      isActive ? 'text-primary font-medium' : 'text-foreground'
    }`;

  // Hover delay handlers for desktop dropdown
  const openResources = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setResourcesOpen(true);
  };
  const scheduleCloseResources = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setResourcesOpen(false), 150);
  };

  return (
    <>
      <SkipLinks />
      {mobileMenuOpen && (
        <div
          className="fixed inset-0 bg-black/70 backdrop-blur-sm z-40 animate-fade-in md:hidden"
          onClick={handleCloseMenu}
          aria-hidden="true"
        />
      )}

      <nav
        className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${
          !navbarVisible && isMobile ? 'transform -translate-y-full' : ''
        } ${
          (isScrolled || isMobile) ? 'bg-background/95 backdrop-blur-md shadow-md py-2' : 'bg-transparent py-4'
        }`}
        role="navigation"
        aria-label={t('a11y.mainNavigation')}
        id="navigation"
      >
        <div className="container mx-auto px-4 sm:px-6 flex items-center justify-between">
          <Link
            to="/"
            className="flex items-center relative z-50 focus-visible:ring-enhanced rounded-sm"
            onClick={() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            aria-label={t('a11y.homeLink')}
          >
            <picture>
              <source srcSet="/lovable-uploads/f9f10bfd-e36a-48d8-a3c5-d4a7b313c943.webp" type="image/webp" />
              <img
                src="/lovable-uploads/f9f10bfd-e36a-48d8-a3c5-d4a7b313c943.png"
                alt="ARC Consulting - Revenue Management Experts"
                className="h-10 sm:h-12 mr-3"
                loading="eager"
                decoding="sync"
                width={48}
                height={48}
                fetchPriority="high"
              />
            </picture>
          </Link>

          {/* Desktop Navigation */}
          <div className="hidden md:flex items-center space-x-6" role="menubar">
            <a
              href="/#services"
              className={`${getNavLinkClass()} focus-visible:ring-enhanced rounded-sm px-2 py-1`}
              role="menuitem"
              aria-label={t('a11y.servicesLink')}
              onClick={(e) => { e.preventDefault(); navigateAndScroll(navigate, 'services', isHomePage); }}
            >
              {t('nav.services')}
            </a>
            <a
              href="/#pricing"
              className={`${getNavLinkClass()} focus-visible:ring-enhanced rounded-sm px-2 py-1`}
              role="menuitem"
              aria-label={t('a11y.pricingLink')}
              onClick={(e) => { e.preventDefault(); navigateAndScroll(navigate, 'pricing', isHomePage); }}
            >
              {t('nav.pricing')}
            </a>
            <Link
              to="/about"
              className={`${getNavLinkClass(isCurrentRoute('/about'))} focus-visible:ring-enhanced rounded-sm px-2 py-1`}
              role="menuitem"
              aria-label={t('a11y.aboutLink')}
            >
              {t('nav.aboutUs')}
            </Link>

            {/* Resources dropdown */}
            <div
              ref={resourcesRef}
              className="relative"
              onMouseEnter={openResources}
              onMouseLeave={scheduleCloseResources}
            >
              <button
                type="button"
                className={`${getNavLinkClass(isResourcesActive)} focus-visible:ring-enhanced rounded-sm px-2 py-1 flex items-center gap-1`}
                aria-haspopup="menu"
                aria-expanded={resourcesOpen}
                onClick={() => setResourcesOpen((v) => !v)}
              >
                {t('nav.resources')}
                <ChevronDown
                  className={`h-4 w-4 transition-transform duration-200 ${resourcesOpen ? 'rotate-180' : ''}`}
                  aria-hidden="true"
                />
              </button>

              {resourcesOpen && (
                <div
                  className="absolute left-0 top-full mt-2 w-56 rounded-lg bg-background border border-border shadow-lg overflow-hidden animate-fade-in z-50"
                  role="menu"
                  aria-label="Resources"
                  onMouseEnter={openResources}
                  onMouseLeave={scheduleCloseResources}
                >
                  {RESOURCE_ITEMS.map((item) =>
                    item.type === 'route' ? (
                      <Link
                        key={item.to}
                        to={item.to}
                        className="block px-4 py-2.5 text-sm text-foreground hover:bg-primary hover:text-primary-foreground transition-colors"
                        role="menuitem"
                        onClick={() => setResourcesOpen(false)}
                      >
                        {item.label}
                      </Link>
                    ) : (
                      <a
                        key={item.to}
                        href={item.to}
                        className="block px-4 py-2.5 text-sm text-foreground hover:bg-primary hover:text-primary-foreground transition-colors"
                        role="menuitem"
                        onClick={(e) => { e.preventDefault(); setResourcesOpen(false); navigateAndScroll(navigate, item.to.replace('/#', ''), isHomePage); }}
                      >
                        {item.label}
                      </a>
                    )
                  )}
                </div>
              )}
            </div>

            <div className="flex items-center space-x-4">
              <a
                href={FREE_AUDIT_URL}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center rounded-md text-sm font-medium border-2 border-primary text-primary bg-transparent hover:bg-primary/10 px-4 py-2 transition-all duration-200 focus-visible:ring-enhanced"
                role="menuitem"
              >
                {t('nav.freeAudit')}
              </a>
              <Button
                className="bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 text-primary-foreground focus-visible:ring-enhanced"
                onClick={() => window.open('https://calendly.com/get-your-ivi-now', '_blank', 'noopener,noreferrer')}
                aria-label={t('a11y.contactButton')}
              >
                {t('nav.talkToUs')}
              </Button>
              <LanguageSwitcher />
            </div>
          </div>

          {/* Mobile Controls */}
          <div className="md:hidden flex items-center space-x-3 z-50">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              aria-label={mobileMenuOpen ? t('a11y.closeMobileMenu') : t('a11y.openMobileMenu')}
              aria-expanded={mobileMenuOpen}
              aria-controls="mobile-navigation-menu"
              className="h-10 w-10 hover:bg-accent transition-colors focus-visible:ring-enhanced"
            >
              <div className="relative w-6 h-6">
                <Menu
                  className={`absolute inset-0 transition-all duration-300 ${
                    mobileMenuOpen ? 'rotate-180 opacity-0 scale-50' : 'rotate-0 opacity-100 scale-100'
                  }`}
                  aria-hidden="true"
                />
                <X
                  className={`absolute inset-0 transition-all duration-300 ${
                    mobileMenuOpen ? 'rotate-0 opacity-100 scale-100' : '-rotate-180 opacity-0 scale-50'
                  }`}
                  aria-hidden="true"
                />
              </div>
            </Button>
            <LanguageSwitcher />
          </div>
        </div>

        {/* Mobile Menu */}
        <div
          className={`md:hidden fixed left-0 right-0 h-[calc(100dvh-4rem)] bg-white border-t border-border shadow-2xl z-50 transition-all duration-300 ${
            mobileMenuOpen
              ? 'top-16 bottom-0 opacity-100 translate-y-0'
              : 'top-16 bottom-0 opacity-0 -translate-y-8 pointer-events-none'
          }`}
          id="mobile-navigation-menu"
          role="menu"
          aria-label={t('a11y.mobileNavigation')}
        >
          <div className="flex flex-col h-full">
            <div className="flex-1 overflow-y-auto p-6 pb-0">
              <nav className="space-y-2 pt-4" role="none">
                {/* Services */}
                <a
                  href="/#services"
                  className="block px-6 py-4 text-foreground hover:bg-muted transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border border-transparent hover:border-muted shadow-sm"
                  onClick={(e) => {
                    e.preventDefault();
                    setMobileMenuOpen(false);
                    setTimeout(() => navigateAndScroll(navigate, 'services', isHomePage), 300);
                  }}
                  role="menuitem"
                >
                  {t('nav.services')}
                </a>
                {/* Pricing */}
                <a
                  href="/#pricing"
                  className="block px-6 py-4 text-foreground hover:bg-muted transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border border-transparent hover:border-muted shadow-sm"
                  onClick={(e) => {
                    e.preventDefault();
                    setMobileMenuOpen(false);
                    setTimeout(() => navigateAndScroll(navigate, 'pricing', isHomePage), 300);
                  }}
                  role="menuitem"
                >
                  {t('nav.pricing')}
                </a>
                {/* About */}
                <Link
                  to="/about"
                  className={`block px-6 py-4 transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border shadow-sm ${
                    isCurrentRoute('/about')
                      ? 'bg-primary/20 text-primary font-bold border-primary/40'
                      : 'text-foreground hover:bg-muted border-transparent hover:border-muted'
                  }`}
                  onClick={handleCloseMenu}
                  role="menuitem"
                  aria-current={isCurrentRoute('/about') ? 'page' : undefined}
                >
                  {t('nav.aboutUs')}
                </Link>
                {/* Blog */}
                <Link
                  to="/blog"
                  className={`block px-6 py-4 transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border shadow-sm ${
                    location.pathname.startsWith('/blog')
                      ? 'bg-primary/20 text-primary font-bold border-primary/40'
                      : 'text-foreground hover:bg-muted border-transparent hover:border-muted'
                  }`}
                  onClick={handleCloseMenu}
                  role="menuitem"
                  aria-current={location.pathname.startsWith('/blog') ? 'page' : undefined}
                >
                  {t('nav.blog')}
                </Link>
                {/* Revenue Calculator */}
                <Link
                  to="/revenue-calculator"
                  className={`block px-6 py-4 transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border shadow-sm ${
                    isCurrentRoute('/revenue-calculator')
                      ? 'bg-primary/20 text-primary font-bold border-primary/40'
                      : 'text-foreground hover:bg-muted border-transparent hover:border-muted'
                  }`}
                  onClick={handleCloseMenu}
                  role="menuitem"
                  aria-current={isCurrentRoute('/revenue-calculator') ? 'page' : undefined}
                >
                  {t('nav.revenueCalculator')}
                </Link>
                {/* Free Audit */}
                <a
                  href={FREE_AUDIT_URL}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="block px-6 py-4 border-2 border-primary text-primary rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced transition-colors hover:bg-primary/10"
                  onClick={handleCloseMenu}
                  role="menuitem"
                >
                  {t('nav.freeAudit')}
                </a>
                {/* Certifications */}
                <Link
                  to="/certifications"
                  className={`block px-6 py-4 transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border shadow-sm ${
                    isCurrentRoute('/certifications')
                      ? 'bg-primary/20 text-primary font-bold border-primary/40'
                      : 'text-foreground hover:bg-muted border-transparent hover:border-muted'
                  }`}
                  onClick={handleCloseMenu}
                  role="menuitem"
                  aria-current={isCurrentRoute('/certifications') ? 'page' : undefined}
                >
                  {t('nav.certifications')}
                </Link>
                {/* How It Works */}
                <a
                  href="/#how-it-works"
                  className="block px-6 py-4 text-foreground hover:bg-muted transition-colors rounded-xl text-lg font-semibold touch-manipulation focus-visible:ring-enhanced border border-transparent hover:border-muted shadow-sm"
                  onClick={(e) => {
                    e.preventDefault();
                    setMobileMenuOpen(false);
                    setTimeout(() => navigateAndScroll(navigate, 'how-it-works', isHomePage), 300);
                  }}
                  role="menuitem"
                >
                  {t('nav.howItWorks')}
                </a>
              </nav>
            </div>

            {/* Talk to Us CTA pinned at bottom */}
            <div className="flex-shrink-0 p-6 pt-0 border-t border-border bg-background">
              <Button
                className="w-full h-14 bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 text-primary-foreground font-semibold text-lg touch-manipulation focus-visible:ring-enhanced rounded-xl shadow-lg"
                onClick={() => {
                  window.open('https://calendly.com/get-your-ivi-now', '_blank', 'noopener,noreferrer');
                  handleCloseMenu();
                }}
                aria-label={t('a11y.contactButton')}
              >
                {t('nav.talkToUs')}
              </Button>
            </div>
          </div>
        </div>
      </nav>
    </>
  );
};

export default Navbar;
