import { useEffect, useRef } from 'react';
import type { MenuItem } from '../../data/types';

type Props = {
  readonly menuItems: MenuItem[];
  readonly isOpen: boolean;
  readonly onItemClick: (section: string) => void;
  readonly onClose: () => void;
};

export default function MobileMenu({ menuItems, isOpen, onItemClick, onClose }: Props) {
  const firstButtonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (isOpen && firstButtonRef.current) {
      firstButtonRef.current.focus();
    }
  }, [isOpen]);

  if (!isOpen) return null;

  return (
    <nav id="mobile-menu" className="navbar__mobile-menu" role="navigation" aria-label="Mobile navigation">
      <div className="navbar__mobile-menu__header">
        <button
          onClick={onClose}
          className="navbar__mobile-menu__close"
          type="button"
          aria-label="Close menu"
        >
          ×
        </button>
      </div>
      <div className="navbar__mobile-menu__items">
        {menuItems.map((item, index) => (
          <button
            key={item.label}
            ref={index === 0 ? firstButtonRef : undefined}
            onClick={() => onItemClick(item.section)}
            className="navbar__mobile-menu__item"
            type="button"
          >
            {item.label}
          </button>
        ))}
      </div>
    </nav>
  );
}
