
document.addEventListener('DOMContentLoaded', function () {
    const pageLinks = Array.from(
        document.querySelectorAll('a[href*="page="]')
    );

    if (!pageLinks.length) return;

    const candidates = [];

    pageLinks.forEach(function (link) {
        let parent = link.parentElement;

        while (parent && parent !== document.body) {
            const linksInside = parent.querySelectorAll('a[href*="page="]');

            if (linksInside.length >= 2) {
                candidates.push(parent);
                break;
            }

            parent = parent.parentElement;
        }
    });

    if (!candidates.length) return;

    candidates.sort(function (a, b) {
        return a.querySelectorAll('a[href*="page="]').length
             - b.querySelectorAll('a[href*="page="]').length;
    });

    const pagination = candidates[0];
    pagination.classList.add('es-unit-pagination');
});
