'use client';

import s from './styles.module.scss';
import { TMenuItem } from '@shared/const/menu';
import clsx from 'clsx';
import { useEffect, useState } from 'react';
import { MenuItem } from '@widgets/sidebar/menu-item';

type MenuListProps = {
  items: TMenuItem[];
  level: number;
  onClose: () => void;
  isOpen: boolean;
};

function MenuList({ items, level, onClose, isOpen }: MenuListProps) {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);

  const toggleItem = (index: number): void => {
    setActiveIndex((prev) => (prev === index ? null : index));
  };

  useEffect(() => {
    if (!isOpen) {
      setActiveIndex(null);
    }
  }, [isOpen]);

  return (
    <ul className={clsx(s.Menu, s[`Menu_level_${level}`])}>
      {items.map((item, index) => (
        <MenuItem
          key={index}
          item={item}
          level={level}
          isOpen={activeIndex === index}
          onToggle={() => toggleItem(index)}
          onClose={onClose}
        />
      ))}
    </ul>
  );
}

export { MenuList };
