import React, { FC, useMemo } from 'react';

import { TopNavDesktop } from './TopNavDesktop/TopNavDesktop';
import { TopNavMobile } from './TopNavMobile/TopNavMobile';
import { ITopNavAllProps, ITopNavItem, ITopNavProps } from './types';

export const TopNav: FC<ITopNavProps> = ({ documentWidth, items }) => {
  const { desktop: navDesktopProps, mobile: navMobileProps } = useMemo<
    ITopNavAllProps
  >(() => {
    const desktopLeftItems: JSX.Element[] = [];
    const desktopRightItems: JSX.Element[] = [];

    const mobileMenuItems: JSX.Element[] = [];
    const mobileAboveMenuItems: JSX.Element[] = [];
    const mobileBelowMenuItems: JSX.Element[] = [];

    items.forEach(({ position, element }: ITopNavItem) => {
      switch (position.desktop) {
        case 'left':
          desktopLeftItems.push(element);
          break;
        case 'right':
          desktopRightItems.push(element);
      }

      switch (position.mobile) {
        case 'above':
          mobileAboveMenuItems.push(element);
          break;
        case 'below':
          mobileBelowMenuItems.push(element);
          break;
        default:
          mobileMenuItems.push(element);
      }
    });

    return {
      desktop: {
        leftItems: desktopLeftItems,
        rightItems: desktopRightItems,
      },
      mobile: {
        menuItems: mobileMenuItems,
        aboveMenuItems: mobileAboveMenuItems,
        belowMenuItems: mobileBelowMenuItems,
      },
    };
  }, []);

  return documentWidth >= 768 ? (
    <TopNavDesktop {...navDesktopProps} />
  ) : (
    <TopNavMobile {...navMobileProps} />
  );
};
