import React from 'react';
import classNames from 'classnames';

export default function SubMenu(props) {

  const { pathPrefix, menus, show, onShowChange } = props;
  const [style, setStyle] = React.useState({});
  const [current, setCurrent] = React.useState(null);
  const ref = React.useRef();

  const onMouseLeaveCapture = e => {
    if (e.target === ref.current) {
      onShowChange(false);
    }
  }

  React.useEffect(() => {
    const pageNav = document.getElementById('pageNav');
    const rect = pageNav.getBoundingClientRect();
    setStyle({
      top: (rect.bottom + rect.top) + 'px',
    });

    // astro 暂时不支持 onXXXCapture 事件绑定模式
    const el = ref.current;
    el.addEventListener('mouseleave', onMouseLeaveCapture, true);

    return () => {
      el.removeEventListener('mouseleave', onMouseLeaveCapture, true);
    }
  }, []);

  return (
    <div
      id="sub-menu"
      ref={ref}
      style={style}
      className={classNames("container-fluid bg-white", { show })}
    >
      <div className="row">
        {
          menus?.map((menu) => (
            <div className={classNames("col p-5", { 'has-level3': menu.levelDeep >= 3 })} key={menu.path}>
              <p className="menu-level-1 fs-4">
                <a
                  className="sub-menu-link link-dark p-2 border-bottom"
                  href={`${pathPrefix}${menu.path}`}
                >{menu.name}</a>
              </p>
              <div className="row">
                <div className="col pe-0">
                {
                  menu.children?.map((item) => (
                    <p
                      key={item.path}
                      className={classNames("menu-level-2 mb-1", { 'bg-white': item === current })}
                      onMouseEnter={() => setCurrent(item)}
                    >
                      <a className="sub-menu-link link-dark p-2" href={`${pathPrefix}${item.path}`}>{item.name}</a>
                    </p>
                  ))
                }
                </div>
                {
                  menu.levelDeep >= 3 && (
                    <div className={classNames("col", { 'bg-white': current?.children?.length > 0 })}>
                      {
                        current?.children?.map((it) => (
                          <p className="menu-level-3 mb-1">
                            <a className="sub-menu-link link-dark p-2" href={`${pathPrefix}${it.path}`}>{it.name}</a>
                          </p>
                        ))
                      }
                    </div>
                  )
                }
              </div>
            </div>
          ))
        }
      </div>
    </div>
  );
}
