document.addEventListener("DOMContentLoaded", () => {
    // Hide inline thumbs when JS is active
    document.querySelectorAll(".thumb-inline").forEach(img => img.style.display = "none");

    const tip = document.createElement("div");
    tip.className = "thumb-tooltip";
    document.body.appendChild(tip);

    function show(e) {
        const el = e.currentTarget;
        const url = el.getAttribute("data-tooltip");
        if (!url) return;

        tip.style.backgroundImage = `url("${url}")`;
        tip.style.display = "block";

        // preload image to size tooltip
        const img = new Image();
        img.onload = () => {
            tip.style.width = img.naturalWidth + "px";
            tip.style.height = img.naturalHeight + "px";

            // position tooltip relative to element
            const rect = el.getBoundingClientRect();
            const scrollX = window.scrollX;
            const scrollY = window.scrollY;

            let left = rect.left + scrollX + (rect.width - tip.offsetWidth) / 2;
            let top = rect.top + scrollY - tip.offsetHeight - 8; // above element

            // fallback below if not enough space
            if (top < scrollY) {
                top = rect.bottom + scrollY + 8;
            }

            tip.style.left = left + "px";
            tip.style.top = top + "px";
        };
        img.src = url;
    }

    function hide() {
        tip.style.display = "none";
    }

    document.querySelectorAll("li.credit").forEach(item => {
        item.addEventListener("mouseenter", show);
        item.addEventListener("mouseleave", hide);
        item.addEventListener("focusin", show);
        item.addEventListener("focusout", hide);
    });
});
