import Tooltip from './TooltipComponent.svelte';
let currentTooltip;
let timeout;
// Adds an HTML tooltip on mouseenter
function tooltip(node, html, placement = 'top') {
    let offset = 0;
    if (html && typeof html === 'object') {
        offset = html.offset || 0;
        html = html.text;
    }
    let tooltip;
    function createTooltip() {
        if (!html)
            return;
        clearTimeout(timeout);
        if (!currentTooltip) {
            tooltip = currentTooltip = new Tooltip({
                target: document.body,
                props: { target: node, html, placement, offset },
            });
            tooltip.removeTooltip = removeTooltip;
        }
        else {
            tooltip = currentTooltip;
            tooltip.$set({ target: node, html, placement, offset });
        }
    }
    function queueRemoveTooltip() {
        if (tooltip) {
            tooltip = null;
            timeout = setTimeout(removeTooltip, 10);
        }
    }
    function removeTooltip() {
        if (currentTooltip) {
            currentTooltip.$destroy();
            currentTooltip = null;
            tooltip = null;
        }
    }
    node.addEventListener('mouseenter', createTooltip);
    node.addEventListener('mouseleave', queueRemoveTooltip);
    node.addEventListener('mousedown', removeTooltip);
    return {
        update(value) {
            if (typeof value === 'object') {
                offset = value.offset || 0;
                html = value.text;
            }
            else {
                html = value;
            }
            if (tooltip)
                tooltip.$set({ html, offset });
        },
        destroy() {
            removeTooltip();
            node.removeEventListener('mouseenter', createTooltip);
            node.removeEventListener('mouseleave', queueRemoveTooltip);
            node.removeEventListener('mousedown', removeTooltip);
        },
    };
}
export { tooltip as tooltipTop };
export function tooltipRight(node, html) {
    return tooltip(node, html, 'right');
}
export function tooltipLeft(node, html) {
    return tooltip(node, html, 'left');
}
export function tooltipBottom(node, html) {
    return tooltip(node, html, 'bottom');
}
