window.calendarSwipe = {
    register: function (element, dotnetHelper) {
        let startX = 0, startY = 0;
        let endX = 0, endY = 0;

        // Touch events
        element.addEventListener('touchstart', (e) => {
            if (e.touches.length === 1) {
                startX = e.touches[0].clientX;
                startY = e.touches[0].clientY;
            }
        });

        element.addEventListener('touchend', (e) => {
            if (e.changedTouches.length === 1) {
                endX = e.changedTouches[0].clientX;
                endY = e.changedTouches[0].clientY;
                handle();
            }
        });

        // Mouse events
        let mouseDown = false;
        element.addEventListener('mousedown', (e) => {
            if (e.button !== 0) return;
            mouseDown = true;
            startX = e.clientX;
            startY = e.clientY;
        });

        element.addEventListener('mouseup', (e) => {
            if (!mouseDown) return;
            mouseDown = false;
            endX = e.clientX;
            endY = e.clientY;
            handle();
        });

        function handle() {
            let diffX = endX - startX;
            let diffY = endY - startY;

            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > 40) {
                    if (diffX < 0) dotnetHelper.invokeMethodAsync('OnSwipeLeft');
                    else dotnetHelper.invokeMethodAsync('OnSwipeRight');
                }
            } else {
                if (Math.abs(diffY) > 40) {
                    if (diffY < 0) dotnetHelper.invokeMethodAsync('OnSwipeUp');
                    else dotnetHelper.invokeMethodAsync('OnSwipeDown');
                }
            }
        }
    }
};
