import { listenOnce } from "./event-utils.js";
const RIPPLE = 'ripple';
function getAnimationDurationInMilliseconds(radiusPixels) {
    return 129.21 * Math.cbrt(radiusPixels);
}
function setPositionRelativeIfStatic(element) {
    if ('static' === getComputedStyle(element).position) element.classList.add('ripple-relative');
}
async function createRipple(event, options) {
    const button = options.parent ?? event.currentTarget;
    const existingRipple = button.getElementsByClassName(RIPPLE)[0];
    existingRipple?.remove();
    button.classList.add('ripple-parent');
    setPositionRelativeIfStatic(button);
    Array.from(button.children).forEach(setPositionRelativeIfStatic);
    const ripple = document.createElement('span');
    ripple.classList.add(RIPPLE);
    ripple.style.backgroundColor = `var(--atomic-${options.color})`;
    ripple.setAttribute('part', RIPPLE);
    const diameter = Math.max(button.clientWidth, button.clientHeight);
    const radius = diameter / 2;
    const animationDuration = getAnimationDurationInMilliseconds(radius);
    const { top, left } = button.getBoundingClientRect();
    ripple.style.width = ripple.style.height = `${diameter}px`;
    ripple.style.left = `${event.clientX - (left + radius)}px`;
    ripple.style.top = `${event.clientY - (top + radius)}px`;
    ripple.style.setProperty('--animation-duration', `${animationDuration}ms`);
    button.prepend(ripple);
    await cleanupAnimationOnFinish(ripple, animationDuration);
}
async function cleanupAnimationOnFinish(ripple, animationDuration) {
    listenOnce(ripple, 'animationend', ()=>{
        ripple?.remove();
    });
    setTimeout(()=>ripple?.remove(), animationDuration + 0.1 * animationDuration);
}
export { createRipple };
