import { useEffect } from 'react'

// Simple centered modal used by the admin editors.
export default function Modal({ title, onClose, children, footer, width = 560 }) {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [onClose])

  return (
    <div
      onMouseDown={onClose}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(6,9,13,0.66)',
        backdropFilter: 'blur(3px)',
        display: 'grid',
        placeItems: 'center',
        padding: 18,
        zIndex: 100,
      }}
    >
      <div
        onMouseDown={(e) => e.stopPropagation()}
        className="panel"
        style={{ width: '100%', maxWidth: width, maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '18px 22px',
            borderBottom: '1px solid var(--line-soft)',
          }}
        >
          <h2 className="display" style={{ margin: 0, fontSize: '1.2rem', color: 'var(--head)' }}>
            {title}
          </h2>
          <button
            onClick={onClose}
            className="sans"
            style={{ border: 'none', background: 'transparent', color: 'var(--muted)', fontSize: '1.4rem', cursor: 'pointer', lineHeight: 1 }}
            aria-label="Close"
          >
            ×
          </button>
        </div>
        <div style={{ padding: 22, overflow: 'auto' }}>{children}</div>
        {footer && (
          <div
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
              gap: 10,
              padding: '16px 22px',
              borderTop: '1px solid var(--line-soft)',
            }}
          >
            {footer}
          </div>
        )}
      </div>
    </div>
  )
}
