'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { Menu, X, ChevronDown } from 'lucide-react';
import { navLinkRel } from '@/lib/cms/rel-utils';

/**
 * Navigation item with pre-resolved href.
 * The href should already be resolved by the server component
 * to avoid passing functions across the Server/Client boundary.
 */
interface ResolvedNavItem {
  label: string;
  href: string | null;
  openInNewTab?: boolean;
  children?: ResolvedNavItem[];
}

interface MobileNavProps {
  /** Navigation items with pre-resolved hrefs */
  navigation: ResolvedNavItem[];
}

/**
 * Mobile Navigation Component
 *
 * Renders a hamburger menu that expands to show navigation items.
 * Solves the issue of navigation consuming too much vertical space
 * on mobile devices in portrait orientation.
 *
 * Features:
 * - Hamburger icon toggle (hidden on desktop, visible on mobile)
 * - Collapsible dropdown submenus (tap to expand, not hover)
 * - Smooth animations for open/close states
 * - Accessible with proper ARIA attributes
 * - Focus trap when menu is open (Tab cycles within menu)
 * - Scroll lock prevents body scrolling behind open menu
 */
export function MobileNav({ navigation }: MobileNavProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set());
  const navRef = useRef<HTMLElement>(null);
  const toggleRef = useRef<HTMLButtonElement>(null);

  const toggleMenu = () => {
    setIsOpen(!isOpen);
    // Reset expanded items when closing menu
    if (isOpen) {
      setExpandedItems(new Set());
    }
  };

  const toggleDropdown = (index: number, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setExpandedItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(index)) {
        newSet.delete(index);
      } else {
        newSet.add(index);
      }
      return newSet;
    });
  };

  // Close menu on Escape key for accessibility
  useEffect(() => {
    if (!isOpen) return;

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setIsOpen(false);
        setExpandedItems(new Set());
        // Return focus to toggle button when closing with Escape
        toggleRef.current?.focus();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen]);

  // Scroll lock: prevent body scroll when menu is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  // Focus trap: keep Tab navigation within the open menu
  const handleFocusTrap = useCallback((e: KeyboardEvent) => {
    if (e.key !== 'Tab' || !navRef.current) return;

    const focusableElements = navRef.current.querySelectorAll<HTMLElement>(
      'button, a[href], [tabindex]:not([tabindex="-1"])'
    );

    if (focusableElements.length === 0) {
      // Fallback: if no focusable elements, keep focus on toggle
      e.preventDefault();
      toggleRef.current?.focus();
      return;
    }

    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];

    if (e.shiftKey) {
      // Shift+Tab: if on first element, wrap to last
      if (document.activeElement === firstElement || document.activeElement === toggleRef.current) {
        e.preventDefault();
        lastElement.focus();
      }
    } else {
      // Tab: if on last element, wrap to toggle button
      if (document.activeElement === lastElement) {
        e.preventDefault();
        toggleRef.current?.focus();
      }
    }
  }, []);

  useEffect(() => {
    if (!isOpen) return;

    document.addEventListener('keydown', handleFocusTrap);
    return () => document.removeEventListener('keydown', handleFocusTrap);
  }, [isOpen, handleFocusTrap]);

  return (
    <>
      {/* Hamburger Toggle Button - only visible on mobile */}
      <button
        ref={toggleRef}
        className="mobile-nav-toggle"
        onClick={toggleMenu}
        aria-expanded={isOpen}
        aria-controls="mobile-nav-menu"
        aria-label={isOpen ? 'Close navigation menu' : 'Open navigation menu'}
      >
        {isOpen ? <X size={24} /> : <Menu size={24} />}
      </button>

      {/* Mobile Navigation Menu */}
      <nav
        ref={navRef}
        id="mobile-nav-menu"
        className={`mobile-nav-menu ${isOpen ? 'mobile-nav-menu--open' : ''}`}
        aria-hidden={!isOpen}
      >
        <ul className="mobile-nav-list">
          {navigation.map((item, index) => {
            const hasChildren = item.children && item.children.length > 0;
            const isExpanded = expandedItems.has(index);

            return (
              <li key={index} className="mobile-nav-item">
                <div className="mobile-nav-link-wrapper">
                  {item.href ? (
                    <a
                      href={item.href}
                      target={item.openInNewTab ? '_blank' : undefined}
                      rel={navLinkRel(item.href, item.openInNewTab)}
                      className="mobile-nav-link"
                      onClick={() => !hasChildren && setIsOpen(false)}
                    >
                      {item.label}
                    </a>
                  ) : (
                    <span className="mobile-nav-link mobile-nav-link--no-href">
                      {item.label}
                    </span>
                  )}

                  {hasChildren && (
                    <button
                      className={`mobile-nav-dropdown-toggle ${isExpanded ? 'mobile-nav-dropdown-toggle--expanded' : ''}`}
                      onClick={(e) => toggleDropdown(index, e)}
                      aria-expanded={isExpanded}
                      aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${item.label} submenu`}
                    >
                      <ChevronDown size={20} />
                    </button>
                  )}
                </div>

                {/* Dropdown submenu */}
                {hasChildren && (
                  <ul
                    className={`mobile-nav-dropdown ${isExpanded ? 'mobile-nav-dropdown--open' : ''}`}
                    aria-hidden={!isExpanded}
                  >
                    {/* Safe: hasChildren guard above ensures children exists and has length > 0 */}
                    {item.children!.map((child, childIndex) => (
                      <li key={childIndex} className="mobile-nav-dropdown-item">
                        {child.href ? (
                          <a
                            href={child.href}
                            target={child.openInNewTab ? '_blank' : undefined}
                            rel={navLinkRel(child.href, child.openInNewTab)}
                            className="mobile-nav-dropdown-link"
                            onClick={() => setIsOpen(false)}
                          >
                            {child.label}
                          </a>
                        ) : (
                          <span className="mobile-nav-dropdown-link mobile-nav-dropdown-link--no-href">
                            {child.label}
                          </span>
                        )}
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            );
          })}
        </ul>
      </nav>

      {/* Backdrop overlay when menu is open */}
      {isOpen && (
        <div
          className="mobile-nav-backdrop"
          onClick={toggleMenu}
          aria-hidden="true"
        />
      )}
    </>
  );
}
