import { useEffect, useRef } from 'react';

const SIZES = {
  sm:    'max-w-[440px]',
  md:    'max-w-[560px]',
  lg:    'max-w-[680px]',
  xl:    'max-w-[860px]',
  '2xl': 'max-w-[1080px]',
};

export default function Modal({ isOpen, onClose, title, children, size = 'lg', hideClose = false, footer }) {
  const overlayRef = useRef(null);

  useEffect(() => {
    if (!isOpen) return;
    const handleKey = (e) => { if (e.key === 'Escape' && !hideClose) onClose(); };
    document.addEventListener('keydown', handleKey);
    const scrollY = window.scrollY;
    document.body.style.overflow = 'hidden';
    document.body.style.position = 'fixed';
    document.body.style.top = `-${scrollY}px`;
    document.body.style.width = '100%';
    return () => {
      document.removeEventListener('keydown', handleKey);
      document.body.style.overflow = '';
      document.body.style.position = '';
      document.body.style.top = '';
      document.body.style.width = '';
      window.scrollTo(0, scrollY);
    };
  }, [isOpen, onClose, hideClose]);

  if (!isOpen) return null;

  return (
    <div
      ref={overlayRef}
      className="rf-modal-overlay fixed inset-0 z-[100000] flex items-center justify-center p-4"
      style={{ background: 'rgba(15, 23, 42, 0.55)' }}
      onClick={e => { if (e.target === overlayRef.current && !hideClose) onClose(); }}
    >
      <div
        className={`modal-content relative w-full ${SIZES[size] || SIZES.lg} bg-white rounded-2xl flex flex-col max-h-[90vh] overflow-hidden`}
        style={{ boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0,0,0,0.06)' }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 shrink-0 bg-white">
          <h2 className="text-base font-bold text-slate-900 pr-8 leading-tight">{title}</h2>
          {!hideClose && (
            <button
              onClick={onClose}
              className="absolute top-3.5 right-4 p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors"
              aria-label="Close"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          )}
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-6 py-5">
          {children}
        </div>

        {/* Optional footer */}
        {footer && (
          <div className="shrink-0 px-6 py-4 border-t border-slate-200 bg-slate-50">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}
