import { useEffect } from "react";
import "./index.css";

const Modal = ({
  visible = false,
  onClose,
  children,
  className = "",
  maskClosable = true,
}) => {
  // 防止背景滚动
  useEffect(() => {
    if (visible) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "auto";
    }

    return () => {
      document.body.style.overflow = "auto";
    };
  }, [visible]);

  // 点击遮罩层关闭
  const handleMaskClick = (e) => {
    if (maskClosable && e.target.classList.contains("modal-mask")) {
      onClose?.();
    }
  };

  if (!visible) return null;

  return (
    <div className={`modal-mask ${className}`} onClick={handleMaskClick}>
      <div className="modal-content">{children}</div>
    </div>
  );
};

export default Modal;
