// [REQ D4]  React Portals – modal montowany w #portal-root poza drzewem DOM aplikacji
// [REQ T6]  Optymalizacja – useCallback dla handlera klawisza Escape
import { useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { X, AlertTriangle } from 'lucide-react';
import styles from './Modal.module.scss';

const Modal = ({ isOpen, onClose, onConfirm, title, message, confirmLabel = 'Confirm', danger = false }) => {
  const handleKeyDown = useCallback(
    (e) => { if (e.key === 'Escape') onClose(); },
    [onClose]
  );

  useEffect(() => {
    if (!isOpen) return;
    document.addEventListener('keydown', handleKeyDown);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = '';
    };
  }, [isOpen, handleKeyDown]);

  if (!isOpen) return null;

  // Resolved lazily so this is safe in tests and SSR-like environments
  const portalRoot = document.getElementById('portal-root') ?? document.body;

  return createPortal(
    <div
      className={styles['modal__overlay']}
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-title"
      onClick={onClose}
    >
      <div className={styles['modal__panel']} onClick={(e) => e.stopPropagation()}>
        <button className={styles['modal__close-btn']} onClick={onClose} aria-label="Close modal">
          <X size={18} />
        </button>

        <div className={styles['modal__icon-wrapper']}>
          <span className={[
            styles['modal__icon'],
            danger ? styles['modal__icon--danger'] : '',
          ].join(' ')}>
            <AlertTriangle size={22} />
          </span>
        </div>

        <h2 id="modal-title" className={styles['modal__title']}>{title}</h2>
        <p className={styles['modal__body']}>{message}</p>

        <div className={styles['modal__footer']}>
          <button
            className={[styles['modal__btn'], styles['modal__btn--cancel']].join(' ')}
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            className={[
              styles['modal__btn'],
              styles['modal__btn--confirm'],
              danger ? styles['modal__btn--danger'] : '',
            ].join(' ')}
            onClick={onConfirm}
          >
            {confirmLabel}
          </button>
        </div>
      </div>
    </div>,
    portalRoot
  );
};

export default Modal;
