/**
 * Tiny bus for "focus the first search input on this page" requests
 * dispatched by the global keyboard shortcut handler. Pages that have
 * a top-of-page search input call `useFocusSearchOnShortcut(inputRef)`
 * to listen; the global handler in App.tsx dispatches the event when
 * the user presses '/'.
 *
 * The bus is just a CustomEvent on `window`. We don't use a full
 * EventEmitter because nothing else needs it and a DOM event gives
 * us bubbling + capture for free if we ever want it.
 */
import { useEffect, type RefObject } from 'react'

export const FOCUS_SEARCH_EVENT = 'mealplanner:focus-search'

/** Dispatch a focus-search request. Called from the global keyboard handler. */
export function requestFocusSearch(): void {
  window.dispatchEvent(new CustomEvent(FOCUS_SEARCH_EVENT))
}

/**
 * Subscribe a search input to focus-search requests. `ref` must point
 * to the underlying <input> element. `enabled` lets pages opt out
 * (e.g. when the search field is hidden behind a tab).
 */
export function useFocusSearchOnShortcut(
  ref: RefObject<HTMLInputElement>,
  enabled = true,
): void {
  useEffect(() => {
    if (!enabled) return
    const handler = () => {
      const el = ref.current
      if (!el) return
      el.focus()
      // Select existing text so the user can replace it with a new query.
      el.select()
    }
    window.addEventListener(FOCUS_SEARCH_EVENT, handler)
    return () => window.removeEventListener(FOCUS_SEARCH_EVENT, handler)
  }, [ref, enabled])
}
