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

  const interactiveElements = [
    elements.accordion,
    elements.widgetContainer,
  ].filter(Boolean);

  const handleClick = () => {
    const isExpanded = actions.togglePowerWidget();

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

      if (!isExpanded) {
        elements.powerWidget?.classList.remove(
          "firevert-powerwidget--mobile-bottom-position-active"
        );
      }
    }

    if (isDesktop() && isExpanded) {
      elements.accordion?.classList.add(
        "firevert-powerwidget__accordion--init-desktop-position"
      );
      elements.powerWidget?.classList.add(
        "firevert-powerwidget--init-desktop-active-position"
      );
    }

    if (isDesktop() && !isExpanded) {
      elements.accordion?.classList.remove(
        "firevert-powerwidget__accordion--init-desktop-position"
      );
      elements.powerWidget?.classList.remove(
        "firevert-powerwidget--init-desktop-active-position"
      );
    }
  };

  const handleMouseEnter = () => {
    if (!isDesktop()) return;

    actions.expandPowerWidget();

    const isPowerWidgetExpanded = state.getIsPowerWidgetOpen();
    const isDesktopInit = state.getIsDesktopInit();

    if (isDesktopInit) {
      deviceActions.desktop.activateHover();
    }

    if (elements.accordionText) {
      elements.accordionText.textContent = isPowerWidgetExpanded
        ? elements.accordionText.dataset.closeText
        : elements.accordionText.dataset.openText;
    }

    if (isPowerWidgetExpanded) {
      elements.accordion?.classList.add(
        "firevert-powerwidget__accordion--collapsed"
      );
    } else {
      elements.accordion?.classList.remove(
        "firevert-powerwidget__accordion--collapsed"
      );
    }
  };

  interactiveElements.forEach((element) => {
    element.addEventListener("click", handleClick);

    if (isDesktop()) {
      element.addEventListener("mouseenter", handleMouseEnter);
    }
  });
}
