import React from "react";
import { get } from "lodash";
import reducers from "@sc/plugins/webcomponents/v2/Button/reducers";

const ouibounce =
  typeof window === "object" ? require("ouibounce") : (x, y) => false;

type ExitIntentProps = {
  exitPayload: any;
  updateComponentSettings: () => void;
  getComponentSettings: () => void;
};

export const ExitIntent: React.FC<ExitIntentProps> = ({
  exitPayload = "{}",
  updateComponentSettings = () => null,
  getComponentSettings = () => null,
}) => {
  let payload = exitPayload;
  if (typeof exitPayload === "string") payload = JSON.parse(exitPayload);

  React.useEffect(() => {
    // console.log("The popup to show on exit is", get(payload, "id"));

    if (get(payload, 'id')) {
      // Exit Popup
      ouibounce(false, {
        callback: () => {
          const id = get(payload, "id", false);
          if (id) {
            reducers([], {
              type: "OPEN_POPUP",
              payload: {
                showId: id,
              },
              updateComponentSettings,
              getComponentSettings,
            });
          }
        },
      });
      
    }
  }, []);

  return null;
};

export default ExitIntent;
