document.addEventListener("DOMContentLoaded", () => {
    const tooltip = document.createElement('div');
    tooltip.className = 'custom-tooltip';
    document.body.appendChild(tooltip);

    const positionClasses = ['tooltip-top', 'tooltip-bottom', 'tooltip-left', 'tooltip-right'];
    let previousCustomClass = null;

    function getAvailableSpace(rect) {
        return {
            top: rect.top,
            bottom: window.innerHeight - rect.bottom,
            left: rect.left,
            right: window.innerWidth - rect.right
        };
    }

    function getBestPosition(rect, ttRect) {
        const space = getAvailableSpace(rect);
        const spacing = 8;
        const fits = {
            top: space.top >= ttRect.height + spacing,
            bottom: space.bottom >= ttRect.height + spacing,
            right: space.right >= ttRect.width + spacing,
            left: space.left >= ttRect.width + spacing
        };

        if (fits.top) return 'top';
        if (fits.bottom) return 'bottom';
        if (fits.right) return 'right';
        if (fits.left) return 'left';

        return Object.entries(space).sort((a, b) => b[1] - a[1])[0][0];
    }

    function showTooltip(el) {
        tooltip.textContent = el.getAttribute('data-tooltip');
        tooltip.style.display = 'block';
        tooltip.style.opacity = '0';
        tooltip.style.top = '-9999px';
        tooltip.style.left = '-9999px';

        if (previousCustomClass) tooltip.classList.remove(previousCustomClass);
        const customClass = el.getAttribute('data-tooltip-class');
        if (customClass) {
            tooltip.classList.add(customClass);
            previousCustomClass = customClass;
        }

        const rect = el.getBoundingClientRect();
        const spacing = 8;

        requestAnimationFrame(() => {
            const ttRect = tooltip.getBoundingClientRect();

            // Check if element has manual class
            let pos = null;
            if (el.classList.contains('tooltip-top')) pos = 'top';
            else if (el.classList.contains('tooltip-bottom')) pos = 'bottom';
            else if (el.classList.contains('tooltip-left')) pos = 'left';
            else if (el.classList.contains('tooltip-right')) pos = 'right';
            else pos = getBestPosition(rect, ttRect); // fallback to auto

            tooltip.classList.remove(...positionClasses);
            tooltip.classList.add(`tooltip-${pos}`);

            let top = 0, left = 0;
            switch (pos) {
                case 'top':
                    top = window.scrollY + rect.top - ttRect.height - spacing;
                    left = window.scrollX + rect.left + (rect.width - ttRect.width) / 2;
                    break;
                case 'bottom':
                    top = window.scrollY + rect.bottom + spacing;
                    left = window.scrollX + rect.left + (rect.width - ttRect.width) / 2;
                    break;
                case 'right':
                    top = window.scrollY + rect.top + (rect.height - ttRect.height) / 2;
                    left = window.scrollX + rect.right + spacing;
                    break;
                case 'left':
                    top = window.scrollY + rect.top + (rect.height - ttRect.height) / 2;
                    left = window.scrollX + rect.left - ttRect.width - spacing;
                    break;
            }

            // Ensure tooltip stays in viewport
            top = Math.max(0, Math.min(top, window.scrollY + window.innerHeight - ttRect.height));
            left = Math.max(0, Math.min(left, window.scrollX + window.innerWidth - ttRect.width));

            tooltip.style.top = `${top}px`;
            tooltip.style.left = `${left}px`;
            tooltip.style.opacity = '1';
        });
    }

    function hideTooltip() {
        tooltip.style.opacity = '0';
        tooltip.style.display = 'none';
    }

    document.querySelectorAll('.has-tooltip').forEach(el => {
        el.addEventListener('mouseenter', () => showTooltip(el));
        el.addEventListener('mouseleave', hideTooltip);
    });
});