'use client'

import { useMessage } from '@/hooks/useMessage'
import { canvasState, currentMenuState } from '@/store/canvasAtom'
import { useRecoilState, useRecoilValue } from 'recoil'
import { menuTypeState, subMenusState } from '@/store/menuAtom'
import useMenu from '@/hooks/common/useMenu'
import { useEffect } from 'react'

export default function MenuDepth01() {
  const type = useRecoilValue(menuTypeState)
  const canvas = useRecoilValue(canvasState)
  const { getMessage } = useMessage()
  const { handleMenu } = useMenu()
  const [currentMenu, setCurrentMenu] = useRecoilState(currentMenuState)
  const subMenus = useRecoilValue(subMenusState)

  const onClickMenu = ({ id, menu }) => {
    if (menu === currentMenu) {
      handleMenu(type)
    } else {
      setCurrentMenu(menu)
    }
  }

  useEffect(() => {
    handleMenu(type)
    canvas.discardActiveObject()
  }, [currentMenu])
  return (
    <div className="canvas-depth2-inner">
      <ul className="canvas-depth2-list">
        {subMenus[type]?.map((menu) => {
          return (
            <li key={menu.id} className={`canvas-depth2-item ${menu.menu === currentMenu ? 'active' : ''}`}>
              <button onClick={() => onClickMenu(menu)}>{getMessage(menu.name)}</button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}
