import { useEffect, useState } from 'react'
import { X, Keyboard } from 'lucide-react'

/**
 * Global shortcut help banner. Listens for `show-shortcut-help` custom
 * events on `window` and renders a dismissible banner near the top of
 * the viewport. Auto-dismisses after 6s. Escape also dismisses.
 *
 * Triggered by the global keyboard handler when the user presses '?'.
 * Pages can also dispatch the event themselves (e.g. from a tooltip).
 */
export const SHOW_SHORTCUT_HELP_EVENT = 'mealplanner:show-shortcut-help'

export const SHORTCUTS: ReadonlyArray<{ keys: string; label: string }> = [
  { keys: 'g d', label: 'Go to Dashboard' },
  { keys: 'g r', label: 'Go to Recipes' },
  { keys: 'g p', label: 'Go to Pantry' },
  { keys: 'g s', label: 'Go to Shopping List' },
  { keys: '/', label: 'Focus the search box' },
  { keys: '?', label: 'Show this help' },
  { keys: 'Esc', label: 'Close banners' },
]

export function ShortcutHelpBanner() {
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout> | null = null
    const show = () => {
      setVisible(true)
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => setVisible(false), 6000)
    }
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && visible) setVisible(false)
    }
    window.addEventListener(SHOW_SHORTCUT_HELP_EVENT, show)
    window.addEventListener('keydown', onKey)
    return () => {
      window.removeEventListener(SHOW_SHORTCUT_HELP_EVENT, show)
      window.removeEventListener('keydown', onKey)
      if (timer) clearTimeout(timer)
    }
  }, [visible])

  if (!visible) return null

  return (
    <div
      role="dialog"
      aria-label="Keyboard shortcuts"
      className="fixed top-16 left-1/2 -translate-x-1/2 z-50 bg-white border border-surface-200 rounded-xl shadow-lg p-4 max-w-md w-[calc(100vw-2rem)] animate-fade-in"
    >
      <div className="flex items-start justify-between gap-3 mb-2">
        <div className="flex items-center gap-2 text-sm font-semibold text-surface-900">
          <Keyboard className="w-4 h-4 text-primary-600" />
          Keyboard shortcuts
        </div>
        <button
          onClick={() => setVisible(false)}
          aria-label="Close shortcut help"
          className="p-1 rounded text-surface-500 hover:bg-surface-100 focus:outline-none focus:ring-2 focus:ring-primary-400"
        >
          <X className="w-4 h-4" />
        </button>
      </div>
      <ul className="space-y-1.5 text-sm">
        {SHORTCUTS.map((s) => (
          <li key={s.keys} className="flex items-center justify-between gap-3">
            <span className="text-surface-600">{s.label}</span>
            <kbd className="px-1.5 py-0.5 bg-surface-100 text-surface-700 rounded text-xs font-mono border border-surface-200">
              {s.keys}
            </kbd>
          </li>
        ))}
      </ul>
    </div>
  )
}
