// src/components/ui/Modal.jsx
import { useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import Button from '@/components/ui/Button'

const FOCUSABLE = ['a[href]', 'button:not([disabled])', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', '[tabindex]:not([tabindex="-1"])'].join(', ')

export default function Modal({ open, onClose, title, size = 'md', footer, persistent = false, children, className = '' }) {
  const modalRef = useRef(null)

  useEffect(() => {
    if (!open) return
    function onKeyDown(e) {
      if (e.key === 'Escape' && !persistent) { e.stopPropagation(); onClose(); return }
      if (e.key === 'Tab' && modalRef.current) {
        const focusable = [...modalRef.current.querySelectorAll(FOCUSABLE)]
        if (focusable.length === 0) return
        const first = focusable[0]; const last = focusable[focusable.length - 1]
        if (e.shiftKey) { if (document.activeElement === first) { e.preventDefault(); last.focus() } }
        else { if (document.activeElement === last) { e.preventDefault(); first.focus() } }
      }
    }
    document.addEventListener('keydown', onKeyDown)
    return () => document.removeEventListener('keydown', onKeyDown)
  }, [open, onClose, persistent])

  useEffect(() => {
    if (!open || !modalRef.current) return
    modalRef.current.querySelector(FOCUSABLE)?.focus()
  }, [open])

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : ''
    return () => { document.body.style.overflow = '' }
  }, [open])

  if (!open) return null

  return createPortal(
    <div className="modal-overlay" onClick={(e) => { if (!persistent && e.target === e.currentTarget) onClose() }} aria-modal="true" role="dialog" aria-labelledby={title ? 'modal-title' : undefined}>
      <div ref={modalRef} className={['modal', `modal-${size}`, className].filter(Boolean).join(' ')}>
        <div className="modal-header">
          {title ? <h2 id="modal-title" className="modal-title">{title}</h2> : <span />}
          <button className="modal-close" onClick={onClose} aria-label="Close dialog">
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
              <path d="M4 4l10 10M14 4L4 14" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
            </svg>
          </button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-footer">{footer}</div>}
      </div>
    </div>,
    document.body
  )
}
