const SWIPE_THRESHOLD = 50;

export default function registerSwipe(id) {
    const el = document.querySelector(`[data-toast-id="${id}"]`);
    if (!el) {
        return;
    }
    let dragStartTime = null;
    let pointerStart = null;

    el.addEventListener("pointerdown", function (event) {
        dragStartTime = new Date();
        event.target.setPointerCapture(event.pointerId);
        if (event.target.tagName === "BUTTON") {
            return;
        }
        el.dataset.swiping = true;
        pointerStart = { x: event.clientX, y: event.clientY };
    });
    
    el.addEventListener("pointerup", function (event) {
        pointerStart = null;
        const swipeAmount = Number(
            el.style.getPropertyValue("--swipe-amount").replace("px", "") || 0,
        );
        const timeTaken = new Date().getTime() - dragStartTime.getTime();
        const velocity = Math.abs(swipeAmount) / timeTaken;

        // Remove only if threshold is met
        if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {
            ToastinTakin.remove(id);
            return;
        }

        el.style.setProperty("--swipe-amount", "0px");
        el.dataset.swiping = false;
    });

    el.addEventListener("pointermove", function (event) {
        if (!pointerStart) {
            return;
        }
        const yPosition = event.clientY - pointerStart.y;
        const xPosition = event.clientX - pointerStart.x;

        const clampedX = Math.max(0, xPosition);
        const swipeStartThreshold = event.pointerType === "touch" ? 10 : 2;
        const isAllowedToSwipe = Math.abs(clampedX) > swipeStartThreshold;

        if (isAllowedToSwipe) {
            el.style.setProperty("--swipe-amount", `${xPosition}px`);
        } else if (Math.abs(yPosition) > swipeStartThreshold) {
            // Swipe is heading into the wrong direction, possibly the user wants to abort.
            pointerStart = null;
        }
    });
}