import React, { useState, useEffect, useRef } from 'react';
import { CONTENT } from '../constants.ts';
import { Menu, X, ChevronDown, Search } from 'lucide-react';
import VistaLogo from './VistaLogo.tsx';
import { useLanguage } from '../contexts/LanguageContext.tsx';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import SearchOverlay from './SearchOverlay.tsx';

const Navbar: React.FC = () => {
  const [scrolled, setScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [activeMenuIndex, setActiveMenuIndex] = useState<number | null>(null);
  const [searchOpen, setSearchOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  
  const { language, toggleLanguage } = useLanguage();
  const location = useLocation();
  const navigate = useNavigate();
  
  const t = CONTENT[language].nav;

  // Handle Scroll Effect
  useEffect(() => {
    const handleScroll = () => {
      const isScrolled = window.scrollY > 50;
      setScrolled(isScrolled);
      if (isScrolled) {
        setActiveMenuIndex(null);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Handle Click Outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setActiveMenuIndex(null);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // Prevent Body Scroll when Mobile Menu Open
  useEffect(() => {
    if (mobileMenuOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }
  }, [mobileMenuOpen]);

  // Handle Navigation Click (Smart Routing)
  const handleNavClick = (e: React.MouseEvent, link: string) => {
    // 处理纯锚点链接（如 #itinerary-highlights）
    if (link.startsWith('#') && !link.startsWith('#/')) {
        e.preventDefault();
        const anchorId = link.substring(1);

        // First try to find the anchor on current page
        const el = document.getElementById(anchorId);
        if (el) {
            // Scroll to anchor on current page
            el.scrollIntoView({ behavior: 'smooth' });
        } else if (location.pathname !== '/') {
            // Only redirect to home if anchor not found on current page
            navigate('/');
            setTimeout(() => {
                const homeEl = document.getElementById(anchorId);
                if (homeEl) homeEl.scrollIntoView({ behavior: 'smooth' });
            }, 100);
        }
        setActiveMenuIndex(null);
    }
    // 处理包含锚点的路由链接（如 #/itineraries#itinerary-highlights）
    else if (link.startsWith('#/') && link.includes('#')) {
        e.preventDefault();
        const [routePart, anchorPart] = link.substring(1).split('#');
        const anchorId = anchorPart;

        // 先导航到路由，然后滚动到锚点
        navigate(routePart);
        setTimeout(() => {
            const el = document.getElementById(anchorId);
            if (el) el.scrollIntoView({ behavior: 'smooth' });
        }, 100);
        setActiveMenuIndex(null);
    }
    // 处理包含查询参数的路由链接（如 #/itineraries?section=routes）
    else if (link.startsWith('#/') && link.includes('?')) {
        e.preventDefault();
        const routePart = link.substring(1);
        // 直接导航到包含查询参数的路由
        navigate(routePart);
        setActiveMenuIndex(null);
    }
    else if (link.startsWith('#/')) {
       setActiveMenuIndex(null);
    }
  };

  const getLinkTo = (link: string) => {
      if (link.startsWith('#/')) {
          // 处理包含锚点或查询参数的路由链接
          // 如 #/itineraries#itinerary-highlights 或 #/itineraries?section=routes
          const routeAndParams = link.substring(1); // 去掉开头的 #
          
          // 处理 hash 锚点
          if (routeAndParams.includes('#')) {
              const [route] = routeAndParams.split('#');
              return route;
          }
          
          // 处理查询参数
          if (routeAndParams.includes('?')) {
              return routeAndParams;
          }
          
          // 普通路由
          return routeAndParams;
      }
      if (link.startsWith('#')) return '/';
      return link;
  };

  return (
    <>
      <nav 
        className={`fixed w-full z-50 transition-all duration-500 ease-in-out ${
          scrolled 
            ? 'bg-white shadow-md py-3' 
            : 'bg-gradient-to-b from-black/60 to-transparent py-6'
        }`}
      >
        <div className="max-w-7xl mx-auto px-6 flex justify-between items-center relative">
          {/* Logo Area */}
          <div onClick={() => { navigate('/'); setActiveMenuIndex(null); }} className="cursor-pointer z-50 relative">
             <VistaLogo color={scrolled ? '#c5a059' : '#ffffff'} />
          </div>

          {/* Desktop Menu */}
          <div className="hidden lg:flex space-x-8 items-center h-full" ref={menuRef}>
            {t.menu.map((item, index) => (
              <div 
                key={index} 
                className="relative group h-full flex items-center py-4"
                onMouseEnter={() => item.submenu && setActiveMenuIndex(index)}
                onMouseLeave={() => setActiveMenuIndex(null)}
              >
                {/* Main Menu Item */}
                {item.link.startsWith('#/') ? (
                   <Link 
                      to={getLinkTo(item.link)}
                      className={`text-sm font-bold uppercase tracking-widest pb-1 border-b-2 cursor-pointer flex items-center gap-1 transition-colors ${
                        scrolled 
                          ? 'text-vista-darkblue hover:text-vista-gold' 
                          : 'text-white hover:text-vista-gold'
                      } ${
                        activeMenuIndex === index 
                        ? 'text-vista-gold border-vista-gold' 
                        : 'border-transparent'
                      }`}
                   >
                     {item.title}
                     {item.submenu && <ChevronDown size={14} className={`transition-transform duration-300 ${activeMenuIndex === index ? 'rotate-180' : ''}`} />}
                   </Link>
                ) : (
                   <a 
                    href={item.link}
                    onClick={(e) => handleNavClick(e, item.link)}
                    className={`text-sm font-bold uppercase tracking-widest pb-1 border-b-2 cursor-pointer flex items-center gap-1 transition-colors ${
                        scrolled 
                          ? 'text-vista-darkblue hover:text-vista-gold' 
                          : 'text-white hover:text-vista-gold'
                      } ${
                        activeMenuIndex === index 
                        ? 'text-vista-gold border-vista-gold' 
                        : 'border-transparent'
                    }`}
                  >
                    {item.title}
                    {item.submenu && <ChevronDown size={14} className={`transition-transform duration-300 ${activeMenuIndex === index ? 'rotate-180' : ''}`} />}
                  </a>
                )}
                
                {/* Desktop Dropdown */}
                {item.submenu && (
                  <div className={`absolute left-1/2 -translate-x-1/2 top-full w-56 pt-2 transition-all duration-300 transform origin-top ${
                      activeMenuIndex === index 
                      ? 'opacity-100 visible translate-y-0' 
                      : 'opacity-0 invisible -translate-y-2 pointer-events-none'
                  }`}>
                    <div className="bg-white shadow-xl rounded-sm border-t-2 border-vista-gold">
                      <div className="py-2">
                        {item.submenu.map((sub, subIndex) => (
                          <React.Fragment key={subIndex}>
                           {sub.link.startsWith('#/') ? (
                               <Link
                                 to={getLinkTo(sub.link)}
                                 onClick={() => setActiveMenuIndex(null)}
                                 className="block px-6 py-3 text-sm text-vista-darkblue/80 hover:bg-vista-darkblue/5 hover:text-vista-gold font-sans transition-colors border-l-2 border-transparent hover:border-vista-gold"
                               >
                                 {sub.title}
                               </Link>
                           ) : (
                               <a 
                                 href={sub.link}
                                 onClick={(e) => handleNavClick(e, sub.link)}
                                 className="block px-6 py-3 text-sm text-vista-darkblue/80 hover:bg-vista-darkblue/5 hover:text-vista-gold font-sans transition-colors border-l-2 border-transparent hover:border-vista-gold"
                               >
                                 {sub.title}
                               </a>
                           )}
                          </React.Fragment>
                        ))}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Right Action Area (Desktop) */}
          <div className="hidden lg:flex items-center space-x-6">
               <button 
                  onClick={() => setSearchOpen(true)} 
                  className={`transition-colors hover:text-vista-gold ${scrolled ? 'text-vista-darkblue' : 'text-white'}`}
                  aria-label="Search"
               >
                  <Search size={20} />
               </button>

               <button 
                  onClick={toggleLanguage} 
                  className={`text-xs font-bold uppercase tracking-widest transition-colors ${scrolled ? 'text-vista-darkblue hover:text-vista-gold' : 'text-white hover:text-vista-gold'}`}
               >
                  {language === 'zh' ? 'EN' : '中文'}
               </button>

               <a 
                  href="https://www.dreamcruises.cn/ticket/index?b=d7945ce3d91637802d7ac1c7b9e34988"
                  onClick={(e) => handleNavClick(e, '/')}
                  className={`px-6 py-2 border transition-all duration-300 text-xs font-bold tracking-widest uppercase ${
                   scrolled 
                   ? 'border-vista-darkblue text-vista-darkblue hover:bg-vista-darkblue hover:text-white' 
                   : 'border-white text-white hover:bg-white hover:text-vista-darkblue'
               }`}>
                  {t.book}
               </a>
          </div>

          {/* Mobile Toggle Button */}
          <div className="lg:hidden flex items-center space-x-4 z-50">
             <button 
                  onClick={() => setSearchOpen(true)} 
                  className={`transition-colors hover:text-vista-gold ${scrolled ? 'text-vista-darkblue' : 'text-white'}`}
                  aria-label="Search"
               >
                  <Search size={22} />
               </button>

            <button 
                  onClick={toggleLanguage} 
                  className={`text-xs font-bold uppercase tracking-widest ${scrolled ? 'text-vista-darkblue' : 'text-white'}`}
            >
               {language === 'zh' ? 'EN' : 'CN'}
            </button>
            <button 
              onClick={() => setMobileMenuOpen(true)} 
              className={`transition-colors ${scrolled ? 'text-vista-darkblue' : 'text-white'}`}
            >
              <Menu size={28} />
            </button>
          </div>
        </div>
      </nav>

      {/* Global Search Overlay */}
      <SearchOverlay isOpen={searchOpen} onClose={() => setSearchOpen(false)} />

      {/* Mobile Menu Backdrop */}
      <div 
         className={`fixed inset-0 z-[60] bg-black/50 backdrop-blur-sm transition-opacity duration-500 lg:hidden ${mobileMenuOpen ? 'opacity-100 visible' : 'opacity-0 invisible'}`}
         onClick={() => setMobileMenuOpen(false)}
      ></div>

      {/* Mobile Menu Drawer - Side Slide-In (Half Width) */}
      <div 
        className={`fixed top-0 right-0 z-[70] h-full w-1/2 bg-vista-darkblue shadow-2xl transition-transform duration-500 transform lg:hidden flex flex-col ${
            mobileMenuOpen ? 'translate-x-0' : 'translate-x-full'
        }`}
      >
           <div className="flex justify-between items-center p-6 border-b border-white/10">
              <span className="text-white font-serif text-lg tracking-wider">MENU</span>
              <button 
                onClick={() => setMobileMenuOpen(false)}
                className="text-white hover:text-vista-gold transition-colors"
              >
                  <X size={28} />
              </button>
           </div>

           <div className="flex-1 overflow-y-auto p-6 flex flex-col space-y-6">
              {t.menu.map((item, index) => (
                <div key={index}>
                    {item.link.startsWith('#/') ? (
                         <Link 
                            to={getLinkTo(item.link)}
                            className="text-xl font-serif text-white block hover:text-vista-gold transition-colors mb-2"
                            onClick={() => setMobileMenuOpen(false)}
                        >
                            {item.title}
                        </Link>
                    ) : (
                        <a 
                            href={item.link} 
                            onClick={(e) => { handleNavClick(e, item.link); setMobileMenuOpen(false); }}
                            className="text-xl font-serif text-white block hover:text-vista-gold transition-colors mb-2"
                        >
                            {item.title}
                        </a>
                    )}
                   
                    {/* Submenu */}
                    {item.submenu && (
                        <div className="pl-4 border-l border-white/20 space-y-3 mt-2">
                             {item.submenu.map((sub, idx) => (
                                 <React.Fragment key={idx}>
                                     {sub.link.startsWith('#/') ? (
                                         <Link 
                                            to={getLinkTo(sub.link)}
                                            className="block text-sm text-white/60 hover:text-white transition-colors"
                                            onClick={() => setMobileMenuOpen(false)}
                                         >
                                             {sub.title}
                                         </Link>
                                     ) : (
                                          <a 
                                            href={sub.link}
                                            onClick={(e) => { handleNavClick(e, sub.link); setMobileMenuOpen(false); }}
                                            className="block text-sm text-white/60 hover:text-white transition-colors"
                                         >
                                             {sub.title}
                                         </a>
                                     )}
                                 </React.Fragment>
                             ))}
                        </div>
                    )}
                </div>
              ))}
           </div>
           
           <div className="p-6 border-t border-white/10 bg-vista-darkblue">
                <a 
                    href="#book" 
                    onClick={(e) => { handleNavClick(e, '#book'); setMobileMenuOpen(false); }} 
                    className="block w-full py-4 bg-vista-gold text-white font-bold uppercase tracking-widest text-sm text-center hover:bg-white hover:text-vista-darkblue transition-colors mb-4"
                >
                  {t.book}
                </a>
                <button onClick={() => setMobileMenuOpen(false)} className="block w-full text-white/60 text-sm hover:text-white transition-colors text-center">
                  {t.contact}
                </button>
           </div>
      </div>
    </>
  );
};

export default Navbar;