'use client'
// src/components/ui/Modal.tsx
// Input: open, onClose, title, children
// Output: centered modal with animated entry, backdrop blur
// Rationale: used for Secure Deploy dialog and other confirmations

import { useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'

export interface ModalProps {
  open: boolean
  onClose: () => void
  title: string
  children: React.ReactNode
  className?: string
  size?: 'md' | 'lg' | 'xl'
}

const sizeClasses = {
  md: 'max-w-[480px]',
  lg: 'max-w-[560px]',
  xl: 'max-w-[640px]',
}

export function Modal({ open, onClose, title, children, className, size = 'lg' }: ModalProps) {
  // Close on Escape
  useEffect(() => {
    if (!open) return
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [open, onClose])

  return (
    <AnimatePresence>
      {open && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.15 }}
            className="fixed inset-0 z-50 bg-bg-base/80 backdrop-blur-sm"
            onClick={onClose}
          />
          {/* Content */}
          <motion.div
            initial={{ opacity: 0, scale: 0.96 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.96 }}
            transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
            className="fixed inset-0 z-50 flex items-center justify-center p-6 pointer-events-none"
          >
            <div
              className={cn(
                'pointer-events-auto w-full bg-bg-overlay border border-bg-border rounded-xl shadow-lg',
                sizeClasses[size],
                className
              )}
              onClick={(e) => e.stopPropagation()}
            >
              {/* Header */}
              <div className="flex items-center justify-between px-6 py-4 border-b border-bg-border">
                <h2 className="text-h2 text-text-primary">{title}</h2>
                <button
                  onClick={onClose}
                  className="p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-subtle transition-colors duration-fast"
                >
                  <X size={16} strokeWidth={1.5} />
                </button>
              </div>
              {/* Body */}
              <div className="p-6">
                {children}
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}
