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";
// (helper inlined as scrollToSectionSmooth)
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();

  // Smooth-scroll to a section. Triggers LazySection mount via hashchange,
  // then polls for the element (it may render asynchronously) and scrolls it
  // into view. Falls back to route navigation when not on the homepage.
  const scrollToSectionSmooth = useCallback((id: string) => {
    const navbarOffset = 80;
    const scrollNow = () => {
      const el = document.getElementById(id);
      if (!el) return false;
      const top = el.getBoundingClientRect().top + window.scrollY - navbarOffset;
      window.scrollTo({ top, behavior: 'smooth' });
      return true;
    };

    if (isHomePage) {
      // Ensure LazySection wrappers mount their children on first click
      if (window.location.hash !== '#' + id) {
        window.history.replaceState(null, '', '#' + id);
        window.dispatchEvent(new HashChangeEvent('hashchange'));
      }
      if (scrollNow()) return;
      let tries = 25;
      const tick = () => {
        if (scrollNow()) return;
        if (--tries > 0) setTimeout(tick, 100);
      };
      setTimeout(tick, 50);
    } else {
      navigate('/#' + id);
    }
  }, [isHomePage, navigate]);


  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 lg: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-12 sm:h-14 lg:h-20 xl:h-24 w-auto mr-3"
                loading="eager"
                decoding="sync"
                width={96}
                height={96}
                fetchPriority="high"
              />
            </picture>
          </Link>

          {/* Desktop Navigation */}
          <div className="hidden lg: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(); scrollToSectionSmooth('services'); }}
            >
              {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(); scrollToSectionSmooth('pricing'); }}
            >
              {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); scrollToSectionSmooth(item.to.replace('/#', '')); }}
                      >
                        {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 bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 text-primary-foreground px-4 py-2 h-10 transition-all duration-200 focus-visible:ring-enhanced"
                role="menuitem"
              >
                {t('nav.freeAudit')}
              </a>
              <Button
                variant="outline"
                className="border-2 border-primary text-primary bg-transparent hover:bg-primary/10 hover:text-primary focus-visible:ring-enhanced"
                onClick={() => navigate('/contact')}
                aria-label="Contact Us"
              >
                Contact Us
              </Button>
              <LanguageSwitcher />
            </div>
          </div>

          {/* Mobile Controls */}
          <div className="lg: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>

      </nav>

      {/* Mobile Menu (sibling of <nav> so backdrop-filter on <nav> does not trap its fixed positioning) */}
      <div
        className={`lg:hidden fixed left-0 right-0 max-h-[calc(100dvh-4rem)] overflow-y-auto bg-white border-t border-border shadow-2xl z-50 transition-transform duration-300 ${
          mobileMenuOpen
            ? 'top-16 translate-y-0'
            : 'top-16 -translate-y-8 pointer-events-none invisible'
        }`}
        style={{ backgroundColor: '#ffffff' }}
        id="mobile-navigation-menu"
        role="menu"
        aria-label={t('a11y.mobileNavigation')}
      >
        <div className="flex flex-col">
          <div className="p-4 pb-0">
            <div className="space-y-1 pt-2" role="none">

              {/* Services */}
              <a
                href="/#services"
                className="block px-4 py-2.5 text-foreground hover:bg-muted transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced"
                onClick={(e) => {
                  e.preventDefault();
                  setMobileMenuOpen(false);
                  setTimeout(() => scrollToSectionSmooth('services'), 300);
                }}
                role="menuitem"
              >
                {t('nav.services')}
              </a>
              {/* Pricing */}
              <a
                href="/#pricing"
                className="block px-4 py-2.5 text-foreground hover:bg-muted transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced"
                onClick={(e) => {
                  e.preventDefault();
                  setMobileMenuOpen(false);
                  setTimeout(() => scrollToSectionSmooth('pricing'), 300);
                }}
                role="menuitem"
              >
                {t('nav.pricing')}
              </a>

              {/* About */}
              <Link
                to="/about"
                className={`block px-4 py-2.5 transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced ${
                  isCurrentRoute('/about')
                    ? 'bg-primary/20 text-primary font-semibold'
                    : 'text-foreground hover:bg-muted'
                }`}
                onClick={handleCloseMenu}
                role="menuitem"
                aria-current={isCurrentRoute('/about') ? 'page' : undefined}
              >
                {t('nav.aboutUs')}
              </Link>
              {/* Contact Us */}
              <Link
                to="/contact"
                className={`block px-4 py-2.5 transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced ${
                  isCurrentRoute('/contact')
                    ? 'bg-primary/20 text-primary font-semibold'
                    : 'text-foreground hover:bg-muted'
                }`}
                onClick={handleCloseMenu}
                role="menuitem"
                aria-current={isCurrentRoute('/contact') ? 'page' : undefined}
              >
                Contact Us
              </Link>
              {/* Blog */}
              <Link
                to="/blog"
                className={`block px-4 py-2.5 transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced ${
                  location.pathname.startsWith('/blog')
                    ? 'bg-primary/20 text-primary font-semibold'
                    : 'text-foreground hover:bg-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-4 py-2.5 transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced ${
                  isCurrentRoute('/revenue-calculator')
                    ? 'bg-primary/20 text-primary font-semibold'
                    : 'text-foreground hover:bg-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-4 py-2.5 bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 text-primary-foreground rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced transition-colors text-center"
                onClick={handleCloseMenu}
                role="menuitem"
              >
                {t('nav.freeAudit')}
              </a>
              {/* Certifications */}
              <Link
                to="/certifications"
                className={`block px-4 py-2.5 transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced ${
                  isCurrentRoute('/certifications')
                    ? 'bg-primary/20 text-primary font-semibold'
                    : 'text-foreground hover:bg-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-4 py-2.5 text-foreground hover:bg-muted transition-colors rounded-lg text-sm font-medium touch-manipulation focus-visible:ring-enhanced"
                onClick={(e) => {
                  e.preventDefault();
                  setMobileMenuOpen(false);
                  setTimeout(() => scrollToSectionSmooth('how-it-works'), 300);
                }}
                role="menuitem"
              >
                {t('nav.howItWorks')}
              </a>
            </div>
          </div>

        </div>
      </div>
    </>

  );
};

export default Navbar;
