'use client';

import { useState, useEffect } from 'react';
import { Menu, X, ChevronDown } from 'lucide-react';
import { StaticLink } from '@/components/ui/static-link';
import { NAVIGATION_V2, MEGA_DROPDOWN_DATA } from '@/lib/constants';
import { cn } from '@/lib/utils';
import { useFocusTrap } from '@/hooks/use-focus-trap';

interface MobileMenuProps {
  className?: string;
}

export function MobileMenu({ className }: MobileMenuProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [expandedDropdown, setExpandedDropdown] = useState<string | null>(null);
  const focusTrapRef = useFocusTrap<HTMLDivElement>(isOpen);

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isOpen]);

  const handleKeyDown = (event: React.KeyboardEvent, action?: () => void) => {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      action?.();
    }
    if (event.key === 'Escape' && isOpen) {
      setIsOpen(false);
    }
  };

  const toggleDropdown = (key: string) => {
    setExpandedDropdown(expandedDropdown === key ? null : key);
  };

  return (
    <div className={cn('lg:hidden', className)} ref={focusTrapRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        onKeyDown={(e) => handleKeyDown(e)}
        className="p-3 rounded-md hover:bg-[var(--color-primary-lighter)] transition-colors focus:outline-none focus:ring-2 focus:ring-[var(--color-brand-primary)] focus:ring-offset-2 min-w-[48px] min-h-[48px] flex items-center justify-center"
        aria-label={isOpen ? '关闭菜单' : '打开菜单'}
        aria-expanded={isOpen}
        aria-controls="mobile-menu-panel"
      >
        {isOpen ? (
          <X className="w-6 h-6 text-[var(--color-text-primary)]" />
        ) : (
          <Menu className="w-6 h-6 text-[var(--color-text-primary)]" />
        )}
      </button>

      {isOpen && (
        <>
          <div
            className="fixed inset-0 bg-[var(--color-primary)]/20 backdrop-blur-sm z-40"
            onClick={() => setIsOpen(false)}
            aria-hidden="true"
          />

          <nav
            id="mobile-menu-panel"
            className="fixed top-16 left-0 right-0 bg-[var(--color-bg-primary)] border-b border-[var(--color-border-primary)] z-50 shadow-lg max-h-[calc(100vh-4rem)] overflow-y-auto"
            role="navigation"
            aria-label="移动端导航"
          >
            <div className="container-wide py-4">
              <ul className="space-y-1" role="list">
                {NAVIGATION_V2.map((item) => (
                  <li key={item.id}>
                    {item.hasDropdown && item.dropdownKey ? (
                      <div>
                        <button
                          onClick={() => toggleDropdown(item.dropdownKey!)}
                          onKeyDown={(e) => handleKeyDown(e, () => toggleDropdown(item.dropdownKey!))}
                          className="flex items-center justify-between w-full text-left px-4 py-4 text-[var(--color-text-primary)] hover:bg-[var(--color-brand-primary-bg)] hover:text-[var(--color-brand-primary)] rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-[var(--color-brand-primary)] focus:ring-inset min-h-[48px]"
                          aria-expanded={expandedDropdown === item.dropdownKey}
                        >
                          {item.label}
                          <ChevronDown
                            className={cn(
                              'w-4 h-4 transition-transform duration-200',
                              expandedDropdown === item.dropdownKey && 'rotate-180'
                            )}
                          />
                        </button>
                        {expandedDropdown === item.dropdownKey && (
                          <ul className="pl-4 space-y-1 mt-1 mb-2" role="list">
                            {(MEGA_DROPDOWN_DATA[item.dropdownKey] ?? []).flatMap(group => group.items).filter(sub => sub.href !== '#').map((sub) => (
                              <li key={sub.id}>
                                <StaticLink
                                  href={sub.href}
                                  onClick={() => setIsOpen(false)}
                                  className="block px-4 py-3 text-sm text-[var(--color-text-muted)] hover:text-[var(--color-brand-primary)] hover:bg-[var(--color-brand-primary-bg)] rounded-md transition-colors"
                                >
                                  <span className="font-medium text-[var(--color-text-primary)]">{sub.title}</span>
                                  <span className="block text-xs text-[var(--color-text-hint)] mt-0.5">{sub.description}</span>
                                </StaticLink>
                              </li>
                            ))}
                          </ul>
                        )}
                      </div>
                    ) : (
                      <StaticLink
                        href={item.href}
                        onClick={() => setIsOpen(false)}
                        className="block px-4 py-4 text-[var(--color-text-primary)] hover:bg-[var(--color-brand-primary-bg)] hover:text-[var(--color-brand-primary)] rounded-md transition-colors min-h-[48px]"
                      >
                        {item.label}
                      </StaticLink>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          </nav>
        </>
      )}
    </div>
  );
}
