import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useEffect } from "react";
import { nanoid } from "nanoid"; // Stack which will hold the modal ids
// The last element of the stack is the topmost modal

var modalStack = []; // Event name for when the modal stack changes

var MODAL_CHANGED_NAME = "clever_modal_changed"; // Send a custom event to notify that the modal stack has changed

var sendModalChangedEvent = function sendModalChangedEvent() {
  var modalChangedEvent = new CustomEvent(MODAL_CHANGED_NAME);
  window.dispatchEvent(modalChangedEvent);
};

function useDialogCount(open, debugName) {
  var _React$useState = React.useState(debugName || nanoid()),
      _React$useState2 = _slicedToArray(_React$useState, 1),
      modalId = _React$useState2[0];

  var _React$useReducer = React.useReducer(function (x) {
    return x + 1;
  }, 0),
      _React$useReducer2 = _slicedToArray(_React$useReducer, 2),
      rerender = _React$useReducer2[1];

  var modalCount = modalStack.findIndex(function (id) {
    return id === modalId;
  });
  var isOnTop = modalStack[modalStack.length - 1] === modalId; // Listen for modal stack changes and to rerender all dialogs.
  // This is needed because the only dialog which will rerender will be the one where the change occurs.

  useEffect(function () {
    var callback = function callback() {
      rerender();
    };

    window.addEventListener(MODAL_CHANGED_NAME, callback);
    return function () {
      window.removeEventListener(MODAL_CHANGED_NAME, callback);
    };
  }, []); // Add or remove the modal id from the stack depending on the open state

  useEffect(function () {
    if (open && !modalStack.includes(modalId)) {
      modalStack.push(modalId);
      sendModalChangedEvent();
    }

    if (!open && modalStack.includes(modalId)) {
      modalStack = modalStack.filter(function (id) {
        return id !== modalId;
      });
      sendModalChangedEvent();
    }
  }, [open, modalId]); // Remove modal from the stack when the component unmounts

  useEffect(function () {
    return function () {
      if (modalStack.includes(modalId)) {
        modalStack = modalStack.filter(function (id) {
          return id !== modalId;
        });
        sendModalChangedEvent();
      }
    };
  }, []);
  return {
    number: modalCount,
    isOnTop: isOnTop
  };
}

export default useDialogCount;