'use client';

import s from './modal.module.scss';
import { ReactNode, useEffect } from 'react';
import clsx from 'clsx';
import { detectIOS } from '@shared/lib';
import { createPortal } from 'react-dom';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  children: ReactNode;
}

const Modal = ({ children, isOpen, onClose }: ModalProps) => {
  useEffect(() => {
    const html = document.documentElement;
    if (isOpen) {
      html.style.overflow = 'hidden';
    }
    return () => {
      html.style.overflow = '';
    };
  }, [isOpen]);

  if (!isOpen) return null;

  const isIOS = detectIOS();

  return createPortal(
    <div
      className={clsx(
        s.ModalBackdrop,
        isOpen && s.ModalBackdrop__open,
        isIOS && s.ModalBackdrop_isIOS,
      )}
    >
      {children}
    </div>,
    document.body,
  );
};

export { Modal };
