'use client'

import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'
import { SearchModal } from '@/components/search-modal'
import { SEARCH_RESTORE_EVENT } from '@/lib/search/restore-search'

interface SearchModalContextValue {
  open: () => void
  close: () => void
}

const SearchModalContext = createContext<SearchModalContextValue>({
  open: () => {},
  close: () => {},
})

export function useSearchModal() {
  return useContext(SearchModalContext)
}

export function SearchModalProvider({ children }: { children: ReactNode }) {
  const [isOpen, setIsOpen] = useState(false)

  const open = () => setIsOpen(true)
  const close = () => setIsOpen(false)

  // Global keyboard shortcut: Ctrl+K or Cmd+K
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault()
        setIsOpen(prev => !prev)
      }
    }
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [])

  useEffect(() => {
    const restore = () => setIsOpen(true)
    window.addEventListener(SEARCH_RESTORE_EVENT, restore)
    return () => window.removeEventListener(SEARCH_RESTORE_EVENT, restore)
  }, [])

  return (
    <SearchModalContext.Provider value={{ open, close }}>
      {children}
      <SearchModal isOpen={isOpen} onClose={close} />
    </SearchModalContext.Provider>
  )
}
