import { onPageLoadComplete } from '@nimius/event-utility';
import {
    computePosition,
    flip,
    shift,
    offset,
    arrow,
} from '@floating-ui/dom';

let activeItem = null;
let activePopup = null;
const activeClass = 'c-hot-spot-item--is-active';

/**
 * Reset functions
 */
function resetPopup(popup) {
    if (!popup) {
        return;
    }

    popup.style = '';
    activeItem.classList.remove(activeClass);
    activeItem.dataset.isOpen = 'false';
}

function resetItem(item) {
    item.classList.remove(activeClass);
    item.dataset.isOpen = 'false';
}

function updatePopupPosition(trigger, popup, arrowElement) {
    computePosition(trigger, popup, {
        placement: 'top',
        middleware: [
            offset(6),
            flip(),
            shift({ padding: 5 }),
            arrow({ element: arrowElement }),
        ],
    }).then(({ x, y, placement, middlewareData }) => {
        Object.assign(popup.style, {
            left: x + 'px',
            top: y + 'px',
        });

        const { x: arrowX, y: arrowY } = middlewareData.arrow;
        const staticSide = {
            top: 'bottom',
            right: 'left',
            bottom: 'top',
            left: 'right',
        }[ placement.split('-')[ 0 ] ];

        Object.assign(arrowElement.style, {
            left: arrowX != null ? arrowX + 'px' : '',
            top: arrowY != null ? arrowY + 'px' : '',
            right: '',
            bottom: '',
            [ staticSide ]: '-4px',
        });
    });
}

function activatePopup(item, trigger, popup, arrowElement) {
    updatePopupPosition(trigger, popup, arrowElement);
    if (activePopup && activeItem) {
        resetItem(activeItem);
        resetPopup(activePopup);
    }

    item.classList.add(activeClass);
    item.dataset.isOpen = 'true';

    activeItem = item;
    activePopup = popup;
}

function hidePopup(item, popup) {
    resetItem(item);
    resetPopup(popup);

    activePopup = null;
    activeItem = null;
}

const initHotspotPopups = (hotSpotItems) => {
    hotSpotItems.forEach((item) => {
        const trigger = item.querySelector('[data-hot-spot-item-trigger]');
        const popup = item.querySelector('[data-hot-spot-item-popover]');
        const arrowElement = item.querySelector('[data-hot-spot-item-arrow]');

        trigger.addEventListener('click', () => {
            const isOpen = item.dataset.isOpen;

            /**
             * Toggle Popup depending on openState
             */
            isOpen === 'false'
                ? activatePopup(item, trigger, popup, arrowElement)
                : hidePopup(item, popup);
        });
    });
};

onPageLoadComplete(() => {
    const hotSpotItems = document.querySelectorAll('[data-hot-spot-item]');

    if (hotSpotItems.length) {
        initHotspotPopups(hotSpotItems);
    }
});
