import { AnimatePresence, motion, type PanInfo } from "motion/react";
import usePopupStore from "../store/popupStore";

function PopupContainer() {
  const { popup, setPopup } = usePopupStore();

  const isMobile = innerWidth < 640;

  const handleDragEnd = (
    _event: MouseEvent | TouchEvent | PointerEvent,
    info: PanInfo
  ) => {
    // Закрываем попап если свайпнули вниз больше чем на 100px или со скоростью > 500
    if (info.offset.y > 100 || info.velocity.y > 500) setPopup(null);
  };

  return (
    <AnimatePresence>
      {popup && (
        <motion.div
          className="fixed bottom-0 z-[9999]"
          initial={{ opacity: 0, y: isMobile ? "100%" : undefined }}
          animate={{ opacity: 1, y: isMobile ? "0%" : undefined }}
          exit={{ opacity: 0, y: isMobile ? "100%" : undefined }}
          transition={{ bounce: 0, ease: "easeInOut" }}
          drag={isMobile ? "y" : false}
          dragConstraints={{ top: 0, bottom: 0 }}
          dragElastic={{ top: 0, bottom: 0 }}
          onDragEnd={handleDragEnd}
        >
          {popup}
        </motion.div>
      )}
    </AnimatePresence>
  );
}

export default PopupContainer;
