import isDesktop from "../../utils/isDesktop";
import isMobile from "../../utils/isMobile";
import createWidgetElements from "../../core/widgetElements";
import createWidgetState from "../../core/widgetState";
import createWidgetActions from "../../core/widgetActions";
import createDeviceActions from "../../core/deviceActions";

export default function setupOutsideClickListener(
  containerElement,
  expandOnMobile
) {
  const elements = createWidgetElements(containerElement);
  const state = createWidgetState(elements);
  const actions = createWidgetActions(elements);
  const deviceActions = createDeviceActions(elements);

  const widgetRoot = document.getElementById("firevert-widget-root");

  const handleOutsideClick = (event) => {
    if (state.getIsWidgetHidden()) return;

    const isClickOutside =
      !widgetRoot?.contains(event.target) && event.target !== widgetRoot;

    if (isClickOutside) {
      actions.hideWidget();

      if (isMobile()) {
        deviceActions.mobile.reset();

        if (expandOnMobile) {
          elements.bubble?.click();
          deviceActions.mobile.activate();
        }
      }

      if (isDesktop() && !state.getIsBubbleOpen()) {
        elements.accordion?.classList.add(
          "firevert-powerwidget__accordion--init-desktop-position"
        );
        elements.accordion?.classList.add(
          "firevert-powerwidget__accordion--active"
        );
        elements.accordion?.classList.add(
          "firevert-powerwidget__accordion--collapsed"
        );
        elements.widget?.classList.remove("firevert-widget--hidden");
        elements.widget?.classList.add(
          "firevert-widget--init-desktop-position"
        );
        elements.widget?.classList.add(
          "firevert-widget--init-desktop-active-position"
        );
        elements.powerWidget?.classList.add(
          "firevert-powerwidget--init-desktop-position"
        );
        elements.powerWidget?.classList.remove(
          "firevert-powerwidget--init-desktop-active-position"
        );
      }
    }
  };

  document.addEventListener("click", handleOutsideClick);
}
