import { useEffect } from 'react';
import { delegate, hideAll } from 'tippy.js';
import 'tippy.js/dist/tippy.css';
import './TooltipService.scss';
const VALID_PLACEMENTS = new Set([
    'auto',
    'auto-start',
    'auto-end',
    'top',
    'top-start',
    'top-end',
    'bottom',
    'bottom-start',
    'bottom-end',
    'right',
    'right-start',
    'right-end',
    'left',
    'left-start',
    'left-end',
]);
const getTooltipContent = (reference) => {
    const contentNode = document.createElement('div');
    // Accept template content via id
    const templateId = reference.getAttribute('data-tooltip-id');
    if (templateId) {
        const templateEl = document.getElementById(templateId);
        if (templateEl) {
            // Remove HTML comments 
            let htmlContent = templateEl.innerHTML
                .replace(/<!--[\s\S]*?-->/g, '')
                .trim();
            // Clean up literal string quotes which sometimes appear when accidentally typing "" in JSX instead of {""}
            if (htmlContent === '""' ||
                htmlContent === "''" ||
                htmlContent === '&quot;&quot;') {
                htmlContent = '';
            }
            // Prevent rendering if the template is completely empty or contains only a placeholder empty generic tag.
            if (htmlContent === '' ||
                /^<([a-zA-Z0-9-]+)[^>]*>\s*<\/\1>$/i.test(htmlContent)) {
                return '';
            }
            contentNode.innerHTML = templateEl.innerHTML;
            return contentNode;
        }
    }
    const rawText = reference.getAttribute('data-tooltip') || '';
    if (!rawText.trim())
        return '';
    const text = rawText
        .replace(/\\n/g, ' ')
        .replace(/\n/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();
    if (!text)
        return '';
    const isPureHTML = text.trim().startsWith('<') && text.trim().endsWith('>');
    const hasHTML = /<(?:[a-z][\s\S]*>|\/[a-z0-9]+>)|&[#a-zA-Z0-9]+;/i.test(text);
    const allowHTML = reference.hasAttribute('data-tooltip-allowhtml');
    // This if  condition for future refrence if any place  html tag or speacial char need to render
    if (allowHTML) {
        if (isPureHTML) {
            contentNode.innerHTML = text;
        }
        else {
            contentNode.style.wordBreak = 'break-word';
            if (hasHTML) {
                contentNode.innerHTML = text;
            }
            else {
                contentNode.textContent = text;
            }
        }
    }
    else {
        contentNode.style.wordBreak = 'break-word';
        contentNode.textContent = text;
    }
    return contentNode;
};
const TooltipService = () => {
    useEffect(() => {
        const hideTooltipsOnScroll = (event) => {
            const target = event.target;
            if (target instanceof Element && target.closest('[data-tippy-root]')) {
                return;
            }
            hideAll({ duration: 0 });
        };
        window.addEventListener('scroll', hideTooltipsOnScroll, true);
        const instance = delegate(document.body, {
            target: '[data-tooltip], [data-tooltip-id]',
            arrow: false,
            placement: 'bottom',
            theme: 'ff-global-tooltip',
            appendTo: document.body,
            allowHTML: true,
            popperOptions: {
                modifiers: [
                    {
                        name: 'preventOverflow',
                        options: {
                            altAxis: true,
                            padding: 8,
                        },
                    },
                    {
                        name: 'flip',
                        options: {
                            padding: 8,
                            fallbackPlacements: ['top', 'right', 'left'],
                        },
                    },
                ],
            },
            content(reference) {
                return getTooltipContent(reference);
            },
            onShow(tippyInstance) {
                const { reference } = tippyInstance;
                const latestContent = getTooltipContent(reference);
                // If no tooltip content is currently available, prevent showing.
                if (latestContent === '') {
                    return false;
                }
                // This is  specific tooltip attributefor interactive
                const isInteractive = tippyInstance.reference.hasAttribute('data-tooltip-interactive');
                //  placement attribute for tooltip
                const rawPlacement = tippyInstance.reference.getAttribute('data-tooltip-placement');
                const normalizedPlacement = rawPlacement?.trim().toLowerCase();
                const placement = normalizedPlacement && VALID_PLACEMENTS.has(normalizedPlacement)
                    ? normalizedPlacement
                    : 'bottom';
                tippyInstance.setProps({
                    interactive: isInteractive,
                    placement,
                    content: latestContent,
                });
            },
            onMount(tippyInstance) {
                const isExplicitlyInteractive = tippyInstance.reference.hasAttribute('data-tooltip-interactive');
                if (!isExplicitlyInteractive) {
                    const tippyBox = tippyInstance.popper.querySelector('.tippy-box');
                    if (tippyBox && tippyBox.scrollHeight > tippyBox.clientHeight) {
                        tippyInstance.setProps({ interactive: true });
                    }
                }
            },
        });
        return () => {
            window.removeEventListener('scroll', hideTooltipsOnScroll, true);
            if (Array.isArray(instance)) {
                instance.forEach((i) => i.destroy());
            }
            else {
                instance.destroy();
            }
        };
    }, []);
    return null;
};
export default TooltipService;
//# sourceMappingURL=TooltipService.js.map