import { useSwapContext } from "@src/context";
import { FC, ReactNode } from "react";

/**
 * This component was created to meet the following requirements:
 * - Modals needs to be inside the shadow root,
 * - Modals needs to be inside all app's main contexts,
 * - Modals' need to rerender on props change.
 *
 * Usage:
 * ```
 * const [open, setOpen] = useState(false);
 *
 * return (
 *  <>
 *    { open && <Modal onClose={() => setOpen(false)}>...</Modal>}
 *
 *    <button onClick={() => setOpen(true)}>Open modal</button>
 *  </>
 * );
 * ```
 */
export const Modal: FC<{
  className?: string;
  children: ReactNode;
  onClose: () => void;
}> = ({ className, children, onClose }) => {
  const { overlay } = useSwapContext();

  return (
    <div
      className={`${
        overlay ? "fixed bg-[rgba(0,0,0,0.8)]" : "absolute"
      } top-0 left-0 right-0 bottom-0 flex items-center justify-center z-10 ${
        className || ""
      }`}
      onMouseDown={(e) => {
        if (e.target === e.currentTarget && overlay) {
          e.stopPropagation();
          e.nativeEvent.stopImmediatePropagation();
          e.preventDefault();
          onClose();
        }
      }}
    >
      <div
        className="flex flex-col bg-t_bg_primary rounded-3xl p-4 w-full min-w-[340px]"
        style={{
          height: overlay ? "600px" : "100%",
          maxWidth: "480px",
          maxHeight: "100%",
        }}
      >
        {children}
      </div>
    </div>
  );
};
