import type { MutableRefObject, RefObject } from 'react'
import type { MainMenuId } from '../home-main-menu/main-menu-config'
import { MAIN_MENU_ENTRIES } from '../home-main-menu/main-menu-config'
import type { MenuMeta } from './home-menu-meta'
import styles from '../../pages/HomePage.module.css'

type HomeMenuProps = {
  menuRef: RefObject<HTMLDivElement | null>
  menuItemRefs: MutableRefObject<Array<HTMLButtonElement | null>>
  indicatorTop: number
  selectedIndex: number
  flashIndex: number | null
  isCoarsePointer: boolean
  menuMeta: Record<MainMenuId, MenuMeta>
  onHoverItem: (index: number) => void
  onActivateItem: (index: number) => void
}

export function HomeMenu({
  menuRef,
  menuItemRefs,
  indicatorTop,
  selectedIndex,
  flashIndex,
  isCoarsePointer,
  menuMeta,
  onHoverItem,
  onActivateItem,
}: HomeMenuProps) {
  return (
    <div className={styles.menuWrap} ref={menuRef}>
      <span className={styles.menuTriangle} style={{ top: `${indicatorTop}px` }} aria-hidden />
      <nav className={styles.menu} aria-label="Main menu">
        {MAIN_MENU_ENTRIES.map((entry, index) => {
          const meta = menuMeta[entry.id]
          const selected = selectedIndex === index
          const flashed = flashIndex === index
          return (
            <button
              key={entry.id}
              type="button"
              ref={(node) => {
                menuItemRefs.current[index] = node
              }}
              className={`${styles.menuItem}${selected ? ` ${styles.menuItemSelected}` : ''}${flashed ? ` ${styles.menuItemFlash}` : ''}`}
              onClick={() => {
                onActivateItem(index)
              }}
              onMouseEnter={() => {
                if (!isCoarsePointer) {
                  onHoverItem(index)
                }
              }}
            >
              <span className={`${styles.menuBadge} ${meta.badgeClass}`} aria-hidden>
                {meta.badge}
              </span>
              <span className={styles.menuText}>
                <span className={styles.menuLabel}>{meta.label}</span>
                <span className={styles.menuSubLabel}>{meta.subLabel}</span>
              </span>
            </button>
          )
        })}
      </nav>
    </div>
  )
}
