import {Controller} from '@hotwired/stimulus';

import {getComponent} from "@symfony/ux-live-component";

export default class extends Controller {
    initialize() {
        getComponent(this.element).then((component) => {
            this.component = component;
        }).catch(() => {
            // Not a live component
        });
    }

    showContextMenu(event) {
        const row = event.currentTarget;
        const menu = row.querySelector('el-menu');
        if (!menu) return;

        event.preventDefault();

        const oldAnchor = menu.getAttribute('anchor');
        menu.removeAttribute('anchor');

        menu.style.position = 'fixed';
        menu.style.left = `${event.clientX}px`;
        menu.style.top = `${event.clientY}px`;
        menu.style.margin = '0';

        if (menu.showPopover) {
            menu.showPopover();
        } else {
            menu.classList.remove('hidden');
        }

        const onToggle = (e) => {
            if (e.newState === 'closed') {
                if (oldAnchor) {
                    menu.setAttribute('anchor', oldAnchor);
                }
                menu.removeEventListener('toggle', onToggle);
            }
        };
        menu.addEventListener('toggle', onToggle);
    }
}
