'use client';

import { Suspense, useState, useEffect, useCallback, useRef } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname, useSearchParams, useRouter } from 'next/navigation';
import { Menu, X } from 'lucide-react';
import { AnimatePresence, motion } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { COMPANY_INFO, NAVIGATION, type NavigationItem } from '@/lib/constants';
import { useFocusTrap } from '@/hooks/use-focus-trap';

function HeaderContent() {
  const [isOpen, setIsOpen] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const router = useRouter();
  const focusTrapRef = useFocusTrap<HTMLDivElement>(isOpen);
  const isScrollingRef = useRef(false);
  const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const getActiveSection = useCallback(() => {
    if (pathname === '/contact') return 'contact';
    if (pathname === '/') {
      const section = searchParams.get('section');
      return section || 'home';
    }
    return '';
  }, [pathname, searchParams]);

  const activeSection = getActiveSection();

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 20);
      
      if (pathname === '/' && !isScrollingRef.current) {
        const scrollPosition = window.scrollY + 100;
        const sections = ['home', 'services', 'products', 'cases', 'about', 'news'];
        
        for (const sectionId of sections) {
          const element = document.getElementById(sectionId);
          if (element) {
            const offsetTop = element.offsetTop;
            const offsetHeight = element.offsetHeight;
            
            if (scrollPosition >= offsetTop && scrollPosition < offsetTop + offsetHeight) {
              const currentSection = searchParams.get('section') || 'home';
              if (currentSection !== sectionId) {
                const url = sectionId === 'home' ? '/' : `/?section=${sectionId}`;
                window.history.replaceState(null, '', url);
              }
              break;
            }
          }
        }
      }
    };

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

    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('keydown', handleGlobalKeyDown);

    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('keydown', handleGlobalKeyDown);
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, [pathname, isOpen, searchParams]);

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      setIsOpen(!isOpen);
    }
    if (e.key === 'Escape' && isOpen) {
      setIsOpen(false);
    }
  }, [isOpen]);

  const handleNavClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>, item: NavigationItem) => {
    e.preventDefault();
    
    if (item.id === 'contact') {
      router.push('/contact');
    } else if (item.id === 'home') {
      if (pathname === '/') {
        isScrollingRef.current = true;
        window.scrollTo({ top: 0, behavior: 'smooth' });
        window.history.pushState(null, '', '/');
        
        scrollTimeoutRef.current = setTimeout(() => {
          isScrollingRef.current = false;
        }, 1000);
      } else {
        router.push('/');
      }
    } else {
      if (pathname === '/') {
        const scrollToSection = (retryCount = 0) => {
          const element = document.getElementById(item.id);
          if (element) {
            isScrollingRef.current = true;
            element.scrollIntoView({ behavior: 'smooth', block: 'start' });
            window.history.pushState(null, '', `/?section=${item.id}`);
            
            scrollTimeoutRef.current = setTimeout(() => {
              isScrollingRef.current = false;
            }, 1000);
          } else if (retryCount < 10) {
            setTimeout(() => scrollToSection(retryCount + 1), 100);
          }
        };
        scrollToSection();
      } else {
        router.push(`/?section=${item.id}`);
      }
    }
    
    setIsOpen(false);
  }, [pathname, router]);

  const isActive = useCallback((item: NavigationItem) => {
    if (item.id === 'contact') {
      return pathname === '/contact';
    }
    
    if (pathname === '/') {
      return activeSection === item.id;
    }
    
    return false;
  }, [pathname, activeSection]);

  const navigationItems = NAVIGATION;

  return (
    <>
      <header 
        className={`
          fixed top-0 left-0 right-0 z-50
          transition-all duration-300 ease-out
          ${isScrolled 
            ? 'bg-white/95 backdrop-blur-xl border-b border-[#E2E8F0] shadow-sm' 
            : 'bg-transparent'
          }
        `}
      >
        <div className="container-wide">
          <div className="flex items-center justify-between h-16">
            <Link 
              href="/"
              className="flex items-center group"
            >
              <Image 
                src="/logo.svg" 
                alt={COMPANY_INFO.name}
                width={32}
                height={32}
                className="h-8 w-auto transition-transform duration-200 group-hover:scale-105"
                priority
              />
            </Link>

            <nav className="hidden md:flex items-center gap-1" role="navigation" aria-label="主导航" data-testid="desktop-navigation">
              {navigationItems.map((item) => (
                <Link
                  key={item.id}
                  href={item.href}
                  onClick={(e) => handleNavClick(e, item)}
                  className={`
                    relative px-3 py-1.5 text-sm font-medium
                    transition-all duration-300
                    ${isActive(item)
                      ? 'text-[#1C1C1C]'
                      : 'text-[#3D3D3D] hover:text-[#1C1C1C]'
                    }
                  `}
                  aria-current={isActive(item) ? 'page' : undefined}
                >
                  {item.label}
                  <span 
                    className={`
                      absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 bg-[#C41E3A] rounded-full
                      transition-all duration-200 ease-out
                      ${isActive(item) 
                        ? 'opacity-100 scale-x-100' 
                        : 'opacity-0 scale-x-0'
                      }
                    `}
                  />
                </Link>
              ))}
            </nav>

            <div className="hidden md:flex items-center gap-3">
              <Button 
                size="sm"
                asChild
              >
                <Link href="/contact" data-testid="consult-button">立即咨询</Link>
              </Button>
            </div>

            <button
              className="md:hidden p-3 -mr-3 text-[#3D3D3D] hover:text-[#1C1C1C] hover:bg-[#F5F5F5] rounded-lg transition-all duration-200 active:scale-95"
              onClick={() => setIsOpen(!isOpen)}
              onKeyDown={handleKeyDown}
              aria-expanded={isOpen}
              aria-controls="mobile-menu"
              aria-label={isOpen ? '关闭菜单' : '打开菜单'}
              data-testid="mobile-menu-button"
              style={{ minWidth: '44px', minHeight: '44px' }}
            >
              {isOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
            </button>
          </div>
        </div>
      </header>

      <AnimatePresence mode="wait">
        {isOpen && (
          <motion.div 
            ref={focusTrapRef}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="fixed inset-0 z-40 md:hidden"
          >
            <div 
              className="absolute inset-0 bg-black/30 backdrop-blur-sm"
              onClick={() => setIsOpen(false)}
              aria-hidden="true"
            />
            <motion.div 
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ type: "spring", stiffness: 300, damping: 30 }}
              className="absolute top-16 right-0 bottom-0 left-0 bg-white/98 backdrop-blur-xl shadow-2xl overflow-y-auto"
              id="mobile-menu"
              role="navigation"
              aria-label="移动端导航"
              data-testid="mobile-navigation"
            >
              <nav className="container-wide py-6">
                {navigationItems.map((item, index) => (
                  <motion.div
                    key={item.id}
                    initial={{ x: 20, opacity: 0 }}
                    animate={{ x: 0, opacity: 1 }}
                    transition={{ delay: index * 0.05 }}
                  >
                    <Link
                      href={item.href}
                      onClick={(e) => handleNavClick(e, item)}
                      className={`
                        block px-4 py-4 text-base font-medium rounded-lg
                        transition-all duration-200
                        ${isActive(item)
                          ? 'text-[#1C1C1C] bg-[#F5F5F5] border-l-4 border-[#C41E3A]'
                          : 'text-[#3D3D3D] hover:text-[#1C1C1C] hover:bg-[#F5F5F5]'
                        }
                      `}
                      style={{ minHeight: '48px', display: 'flex', alignItems: 'center' }}
                    >
                      {item.label}
                    </Link>
                  </motion.div>
                ))}
                <div className="mt-6 px-4 pt-6 border-t border-[#E2E8F0]">
                  <Button 
                    className="w-full"
                    asChild
                    size="lg"
                  >
                    <Link href="/contact" onClick={() => setIsOpen(false)}>
                      联系我们
                    </Link>
                  </Button>
                </div>
              </nav>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

function HeaderFallback() {
  return (
    <header className="fixed top-0 left-0 right-0 z-50 bg-transparent">
      <div className="container-wide">
        <div className="flex items-center justify-between h-16">
          <div className="h-8 w-8 bg-gray-200 animate-pulse rounded" />
          <nav className="hidden md:flex items-center gap-1">
            {[1, 2, 3, 4, 5].map((i) => (
              <div key={i} className="h-6 w-16 bg-gray-200 animate-pulse rounded mx-1" />
            ))}
          </nav>
          <div className="h-9 w-20 bg-gray-200 animate-pulse rounded" />
        </div>
      </div>
    </header>
  );
}

export function Header() {
  return (
    <Suspense fallback={<HeaderFallback />}>
      <HeaderContent />
    </Suspense>
  );
}
