import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { APP_NAME } from '../app/branding'
import { DanceFloor } from '../features/home/DanceFloor'
import { HighScoreCard } from '../features/home/HighScoreCard'
import { HomeMenu } from '../features/home/HomeMenu'
import { useHomeAvatarCanvas } from '../features/home/avatar/useHomeAvatarCanvas'
import { HOME_MENU_META } from '../features/home/home-menu-meta'
import { playSound, SFX_BUTTON_DEFAULT, SFX_BUTTON_START } from '../lib/sounds'
import { useTopHighscore } from '../features/leaderboard/useTopHighscore'
import { MAIN_MENU_ENTRIES } from '../features/home-main-menu/main-menu-config'
import styles from './HomePage.module.css'

function useDanceFloorGrid() {
  return useMemo(() => {
    if (typeof window === 'undefined') return { cols: 18, rows: 8 }
    if (window.matchMedia('(max-width: 600px)').matches) return { cols: 12, rows: 6 }
    return { cols: 20, rows: 8 }
  }, [])
}

/**
 * Main hub: arcade layout (title, menu, hi-score, avatar slot, dance floor).
 * Song-select screen palette (purple/black, magenta accent, grid + scanlines).
 * MediaPipe avatar + D-pad feedback can replace placeholders later.
 */
export function HomePage() {
  const navigate = useNavigate()
  const [selectedIndex, setSelectedIndex] = useState(0)
  const [flashIndex, setFlashIndex] = useState<number | null>(null)
  const [isCoarsePointer, setIsCoarsePointer] = useState(false)
  const [indicatorTop, setIndicatorTop] = useState(0)
  const menuRef = useRef<HTMLDivElement | null>(null)
  const menuItemRefs = useRef<Array<HTMLButtonElement | null>>([])
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const { topScore, topName: topNameFromDB, loading: hiScoreLoading } = useTopHighscore()
  const { cols: floorCols, rows: floorRows } = useDanceFloorGrid()

  useHomeAvatarCanvas(canvasRef)

  // Rainbow EQ bars removed

  const updateIndicator = useCallback(() => {
    const wrapper = menuRef.current
    const selected = menuItemRefs.current[selectedIndex]
    if (!wrapper || !selected) return
    const wrapperRect = wrapper.getBoundingClientRect()
    const itemRect = selected.getBoundingClientRect()
    setIndicatorTop(itemRect.top - wrapperRect.top + itemRect.height / 2)
  }, [selectedIndex])

  const activateSelection = useCallback(
    (index: number) => {
      const item = MAIN_MENU_ENTRIES[index]
      if (!item) return
      playSound(index === 0 ? SFX_BUTTON_START : SFX_BUTTON_DEFAULT)
      setFlashIndex(index)
      window.setTimeout(() => {
        setFlashIndex(null)
        navigate(item.to)
      }, 110)
    },
    [navigate],
  )

  useEffect(() => {
    updateIndicator()
  }, [updateIndicator])

  useEffect(() => {
    const onResize = () => updateIndicator()
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [updateIndicator])

  useEffect(() => {
    const mq = window.matchMedia('(hover: none), (pointer: coarse)')
    const syncPointerMode = () => setIsCoarsePointer(mq.matches)
    syncPointerMode()

    if (typeof mq.addEventListener === 'function') {
      mq.addEventListener('change', syncPointerMode)
      return () => mq.removeEventListener('change', syncPointerMode)
    }

    mq.addListener(syncPointerMode)
    return () => mq.removeListener(syncPointerMode)
  }, [])

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'ArrowDown') {
        event.preventDefault()
        setSelectedIndex((prev) => (prev + 1) % MAIN_MENU_ENTRIES.length)
        return
      }
      if (event.key === 'ArrowUp') {
        event.preventDefault()
        setSelectedIndex((prev) => (prev - 1 + MAIN_MENU_ENTRIES.length) % MAIN_MENU_ENTRIES.length)
        return
      }
      if (event.key === 'Enter') {
        event.preventDefault()
        activateSelection(selectedIndex)
      }
    }

    document.addEventListener('keydown', onKeyDown)
    return () => document.removeEventListener('keydown', onKeyDown)
  }, [activateSelection, selectedIndex])

  return (
    <div className={styles.page}>
      <div className={styles.backdrop} aria-hidden />
      <DanceFloor cols={floorCols} rows={floorRows} />
      <div className={styles.scanlines} aria-hidden />
      <div className={`${styles.corner} ${styles.cornerTopLeft}`} aria-hidden />
      <div className={`${styles.corner} ${styles.cornerTopRight}`} aria-hidden />
      <div className={`${styles.corner} ${styles.cornerBottomLeft}`} aria-hidden />
      <div className={`${styles.corner} ${styles.cornerBottomRight}`} aria-hidden />

      <div className={styles.layout}>
        <main className={styles.mainRow}>
          <aside className={styles.leftPanel}>
            <header className={styles.titleBlock}>
              <h1 className={styles.gameTitle}>{APP_NAME}</h1>
            </header>

            <HomeMenu
              menuRef={menuRef}
              menuItemRefs={menuItemRefs}
              indicatorTop={indicatorTop}
              selectedIndex={selectedIndex}
              flashIndex={flashIndex}
              isCoarsePointer={isCoarsePointer}
              menuMeta={HOME_MENU_META}
              onHoverItem={setSelectedIndex}
              onActivateItem={activateSelection}
            />

            {/* Rainbow EQ bars removed */}
          </aside>

          <section className={styles.centerPanel} aria-label="Avatar preview">
            {/* Mediapipe ready badge removed */}
            <canvas ref={canvasRef} className={styles.avatarCanvas} width={360} height={612} />
          </section>

          <aside className={styles.rightPanel}>
            <HighScoreCard
              hiScoreLoading={hiScoreLoading}
              topScore={topScore}
              topName={topNameFromDB}
            />
          </aside>
        </main>
      </div>
    </div>
  )
}
