'use client'

import * as motion from 'framer-motion/m'
import { AnimatePresence } from 'framer-motion'
import { useEffect } from 'react'

interface SearchModalProps {
  isOpen: boolean
  onClose: () => void
}

export default function SearchModal({ isOpen, onClose }: SearchModalProps) {
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    if (isOpen) document.addEventListener('keydown', handleEsc)
    return () => document.removeEventListener('keydown', handleEsc)
  }, [isOpen, onClose])

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
            onClick={onClose}
          />
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            className="fixed z-50 w-full max-w-xl p-4"
          >
            <input
              type="text"
              placeholder="Search vegetables, fruits, meat..."
              className="w-full px-6 py-4 rounded-full text-lg outline-none shadow-xl"
              autoFocus
            />
            <button onClick={onClose} className="absolute top-0 right-4 text-white text-3xl">&times;</button>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}