'use client';

import React from 'react';

import { useMenu } from '@/contexts/MenuContext';
import MenuArea from '@/components/Page/Menu/MenuArea/';

import styles from './MenuGrid.module.css';

interface MenuGridProps {
  navigationData: Awaited<
    ReturnType<
      typeof import('@/lib/readers/system/navigation').getNavigationData
    >
  >;
}

export default function MenuGrid({ navigationData }: MenuGridProps) {
  const { isMenuOpen, closeMenu, isClosing, startClosing, resetClosing } =
    useMenu();
  const menuRef = React.useRef<HTMLElement>(null);
  const handleClose = React.useCallback(() => {
    startClosing();
    setTimeout(() => {
      closeMenu();
      resetClosing();
    }, 800);
  }, [closeMenu, startClosing, resetClosing]);

  React.useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isMenuOpen) {
        handleClose();
      }
    };

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

  React.useEffect(() => {
    if (isMenuOpen && menuRef.current) {
      const initialFocus = menuRef.current.querySelector(
        'a, button'
      ) as HTMLElement;
      initialFocus?.focus();
    }
  }, [isMenuOpen]);

  if (!navigationData) return null;

  const { items } = navigationData;

  return (
    <nav
      ref={menuRef}
      className={`${styles.menu} ${isMenuOpen ? styles.isOpen : ''} ${isClosing ? styles.isClosing : ''}`}
      aria-hidden={!isMenuOpen}
      aria-label="Main navigation"
    >
      {items.map((item, index) => (
        <MenuArea key={item.gridPosition} item={item} />
      ))}
    </nav>
  );
}
