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 setupBubbleListener(containerElement, expandOnMobile) {
  const elements = createWidgetElements(containerElement);
  const state = createWidgetState(elements);
  const actions = createWidgetActions(elements);
  const deviceActions = createDeviceActions(elements);

  const handleBubbleClick = () => {
    const isWidgetHidden = state.getIsWidgetHidden();

    if (isWidgetHidden) {
      actions.showWidget();
    } else {
      actions.hideWidget();
    }

    deviceActions.runForDevice(
      () => {
        deviceActions.desktop.resetPosition();
        actions.setBubbleState(false);
        deviceActions.desktop.activate();
      },
      () => {
        deviceActions.mobile.activate();
      }
    );
  };

  const initializeDesktop = () => {
    deviceActions.desktop.initPosition();

    if (state.getIsBubbleOpen()) return;

    elements.bubble?.classList.add("firevert-bubble--hide-on-desktop");
    elements.bubble?.click();
    deviceActions.desktop.activate();
  };

  const initializeMobile = () => {
    if (!expandOnMobile) return;

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

  elements.bubble?.addEventListener("click", handleBubbleClick);

  deviceActions.runForDevice(initializeDesktop, initializeMobile);
}
