/* global jQuery */
/**
 * ScholarSyncPagination — shared pagination widget.
 * Requires jQuery. Used by scholar-sync-author-display.js and scholar-sync-group-public.js.
 *
 * API:
 *   ScholarSyncPagination.render($container, data, onPageChange)
 *     Renders numbered page buttons (with ellipsis) + Prev/Next into $container.
 *     data = { current_page, pages }
 *     onPageChange(page) is called when a button is clicked.
 *
 *   ScholarSyncPagination.renderInfo($container, data)
 *     Renders "Showing X–Y of Z articles" text into $container.
 *     data = { total, per_page, current_page }
 */
window.ScholarSyncPagination = (function ($) {
    'use strict';

    function getPagesToShow(current, pages) {
        var result = [];
        var i;
        for (i = 1; i <= pages; i++) {
            if (i === 1 || i === pages || (i >= current - 2 && i <= current + 2)) {
                result.push(i);
            } else if (result[result.length - 1] !== '...') {
                result.push('...');
            }
        }
        return result;
    }

    function render($container, data, onPageChange) {
        var current = data.current_page || 1;
        var pages   = data.pages        || 1;

        if (pages <= 1) {
            $container.empty();
            return;
        }

        var html = '<div class="scholar-sync-pagination">';

        // Prev
        html += '<button class="scholar-sync-page-btn scholar-sync-prev-btn" data-page="' +
            (current - 1) + '"' + (current <= 1 ? ' disabled' : '') + '>&lsaquo;&nbsp;Prev</button>';

        // Numbered pages
        getPagesToShow(current, pages).forEach(function (p) {
            if (p === '...') {
                html += '<span class="scholar-sync-page-ellipsis">&hellip;</span>';
            } else {
                html += '<button class="scholar-sync-page-btn' + (p === current ? ' active' : '') +
                    '" data-page="' + p + '">' + p + '</button>';
            }
        });

        // Next
        html += '<button class="scholar-sync-page-btn scholar-sync-next-btn" data-page="' +
            (current + 1) + '"' + (current >= pages ? ' disabled' : '') + '>Next&nbsp;&rsaquo;</button>';

        html += '</div>';

        $container.html(html);

        $container.find('.scholar-sync-page-btn').on('click', function () {
            if (!$(this).prop('disabled')) {
                onPageChange(parseInt($(this).data('page'), 10));
            }
        });
    }

    function renderInfo($container, data) {
        var total   = data.total        || 0;
        var perPage = data.per_page     || 20;
        var current = data.current_page || 1;
        var from    = total === 0 ? 0 : (current - 1) * perPage + 1;
        var to      = Math.min(current * perPage, total);
        $container.text('Showing ' + from + '\u2013' + to + ' of ' + total + ' articles');
    }

    return {
        render:     render,
        renderInfo: renderInfo
    };

}(jQuery));
