/* global scholar_sync_public_object, ScholarSyncPagination, scholarSyncRenderArticleCard, scholarSyncWireFeedEvents, scholarSyncFormatApa7, scholarSyncGenerateShortName */
(function ($) {
    'use strict';

    function escAttr(s) {
        return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    function escHtml(s) {
        return $('<div>').text(s == null ? '' : s).html();
    }

    /* ── Single researcher card — shared with admin/js/scholar-sync-groups.js
     * (group_preview.php enqueues this file so the preview panel renders the
     * exact same markup as the live public grid, instead of a hand-duplicated
     * copy). ─────────────────────────────────────────────────────────────── */
    window.scholarSyncRenderGroupCard = function (author, settings, targetPage) {
        var imageShape = settings.image_shape || 'circle';
        var shadow     = settings.shadow === true || settings.shadow === '1' || settings.shadow === 1;
        var imgClass   = imageShape + (shadow ? ' with-shadow' : '');

        var imgUrl = author.thumbnail
            ? author.thumbnail
            : (scholar_sync_public_object.plugin_url + 'includes/images/scholar_avatar.png');

        var link = '';
        if (targetPage && author.author_id) {
            link = targetPage + '?author-id=' + encodeURIComponent(author.author_id);
        } else if (author.effective_link) {
            link = author.effective_link;
        }
        var safeLink = link ? escHtml(link) : '';
        var nameHtml = escHtml(author.name);

        var html = '<article class="scholar-sync-group-card">';
        html += '<div class="scholar-sync-group-card-main">';

        if (safeLink) {
            html += '<a class="scholar-sync-group-card-image-link" href="' + safeLink + '">'
                + '<img class="scholar-sync-group-card-image ' + escAttr(imgClass) + '" src="' + escAttr(imgUrl) + '" alt="' + escAttr(author.name) + '" loading="lazy">'
                + '</a>';
        } else {
            html += '<img class="scholar-sync-group-card-image ' + escAttr(imgClass) + '" src="' + escAttr(imgUrl) + '" alt="' + escAttr(author.name) + '" loading="lazy">';
        }

        html += '<div class="scholar-sync-group-card-content">';
        if (safeLink) {
            html += '<a class="scholar-sync-group-card-name" href="' + safeLink + '">' + nameHtml + '</a>';
        } else {
            html += '<div class="scholar-sync-group-card-name">' + nameHtml + '</div>';
        }

        if (settings.show_position !== false && author.position) {
            html += '<div class="scholar-sync-group-card-position">' + escHtml(author.position) + '</div>';
        }
        if (settings.show_institution !== false && author.affiliations) {
            html += '<div class="scholar-sync-group-card-institution">' + escHtml(author.affiliations) + '</div>';
        }
        if (settings.show_tags !== false && author.interests) {
            var maxTags = parseInt(settings.max_tags, 10) || 3;
            var tags = String(author.interests).split(',').map(function (t) { return $.trim(t); }).filter(function (t) { return t !== ''; });
            if (tags.length > 0) {
                html += '<div class="scholar-sync-group-card-tags">';
                for (var t = 0; t < tags.length; t++) {
                    var isOverflow = t >= maxTags;
                    html += '<span class="scholar-sync-group-card-tag' + (isOverflow ? ' scholar-sync-group-card-tag-overflow' : '') + '"'
                        + (isOverflow ? ' hidden' : '') + '>' + escHtml(tags[t]) + '</span>';
                }
                if (tags.length > maxTags) {
                    var moreLabel = '+' + (tags.length - maxTags) + ' more';
                    html += '<button class="scholar-sync-group-card-tags-toggle" type="button" aria-expanded="false" data-label="' + escAttr(moreLabel) + '">' + escHtml(moreLabel) + '</button>';
                }
                html += '</div>';
            }
        }
        html += '</div>'; // .scholar-sync-group-card-content
        html += '</div>'; // .scholar-sync-group-card-main

        var showPubs = settings.show_publications !== false;
        var showLink = settings.show_profile_link !== false;
        if (showPubs || showLink) {
            html += '<div class="scholar-sync-group-card-footer">';
            if (showPubs) {
                var count = parseInt(author.publication_count, 10) || 0;
                html += '<span class="scholar-sync-group-card-publications">'
                    + '<svg class="scholar-sync-group-card-pub-icon" width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><rect x="1" y="1" width="12" height="12" rx="2" stroke="currentColor" stroke-width="1.3"/><path d="M3.5 4.5H10.5M3.5 7H10.5M3.5 9.5H8" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>'
                    + count + (count === 1 ? ' Publication' : ' Publications')
                    + '</span>';
            } else {
                html += '<span></span>';
            }
            if (showLink && safeLink) {
                html += '<a class="scholar-sync-group-card-profile-link" href="' + safeLink + '">View Profile <span aria-hidden="true">&rarr;</span></a>';
            }
            html += '</div>';
        }

        html += '</article>';
        return html;
    };

    /* ── Grid renderer ─────────────────────────────────────────── */
    function renderGrid(container, authors, settings, targetPage) {
        var columns = parseInt(settings.columns, 10) || 2;

        if (!authors || authors.length === 0) {
            container.html('<div class="scholar-sync-group-grid-empty"><h3>No researchers found</h3><p>No researcher profiles are currently available.</p></div>');
            return;
        }

        var html = '<div class="scholar-sync-group-grid" style="grid-template-columns:repeat(' + columns + ',minmax(260px,1fr))">';
        $.each(authors, function (i, a) {
            html += window.scholarSyncRenderGroupCard(a, settings, targetPage);
        });
        html += '</div>';
        container.html(html);
    }

    /* ── Feed article renderer ────────────────────────────────── */
    function renderFeedArticles($target, articles, authorPhotos, options) {
        if (!articles || articles.length === 0) {
            $target.html('<p class="scholar-sync-group-empty">' +
                (window.scholar_sync_i18n ? window.scholar_sync_i18n.no_articles : 'No articles found.') +
                '</p>');
            return;
        }
        authorPhotos = authorPhotos || {};
        options = options || {};
        const pluginUrl = scholar_sync_public_object.plugin_url || '';
        let html = '<div class="scholar-sync-feed-container">';
        for (let i = 0; i < articles.length; i++) {
            html += scholarSyncRenderArticleCard(articles[i], i, authorPhotos, pluginUrl, options);
        }
        html += '</div>';
        $target.html(html);
        // Store articles on container for lazy APA7 generation (avoids listener stacking on re-renders).
        const containerEl = $target[0];
        containerEl._feedArticles = articles;
        if (!containerEl._feedEventsWired) {
            containerEl._feedEventsWired = true;
            scholarSyncWireFeedEvents(containerEl);
        }
    }

    /* ── Feed mode: sets up search + pagination UI ─────────── */
    function initFeedMode($el, groupId, settings, showSearch, feedOptions, sortBy) {
        const restBase = scholar_sync_public_object.rest + 'group-display';

        const searchHtml = !!showSearch
            ? '<div class="scholar-sync-feed-controls">' +
            '<input type="text" class="wps-feed-search" placeholder="Search articles…">' +
            '<button type="button" class="wps-feed-search-btn">Search</button>' +
            '<button type="button" class="wps-feed-clear-btn" style="display:none;">&times;</button>' +
            '</div>' +
            '<div class="scholar-sync-controls-bar">' +
            '<span class="wps-feed-info"></span>' +
            '<div class="scholar-sync-perpage-container">' +
            'Per page:&nbsp;' +
            '<select class="wps-feed-perpage">' +
            '<option value="20">20</option>' +
            '<option value="50">50</option>' +
            '<option value="100">100</option>' +
            '</select>' +
            '</div>' +
            '</div>'
            : '';

        $el.html(
            searchHtml +
            '<div class="wps-feed-list"></div>' +
            '<div class="wps-feed-pagination"></div>'
        );

        function loadFeedPage(page) {
            const perPage = parseInt($el.find('.wps-feed-perpage').val(), 10) || 20;
            const search = $.trim($el.find('.wps-feed-search').val());

            $el.find('.wps-feed-list').html('<p class="scholar-sync-loading">Loading…</p>');

            $.ajax({
                url:     restBase,
                type:    'GET',
                data:    { id: groupId, page: page, per_page: perPage, search: search, sort_by: sortBy || '' },
                headers: { 'X-WP-Nonce': scholar_sync_public_object.rest_nonce },
                success: function (data) {
                    const authorPhotos = data.author_photos || {};
                    renderFeedArticles($el.find('.wps-feed-list'), data.articles || [], authorPhotos, feedOptions);
                    ScholarSyncPagination.renderInfo($el.find('.wps-feed-info'), data);
                    ScholarSyncPagination.render($el.find('.wps-feed-pagination'), data, loadFeedPage);
                },
                error: function () {
                    $el.find('.wps-feed-list').html('<p class="scholar-sync-error">Could not load articles.</p>');
                }
            });
        }

        $el.on('click',  '.wps-feed-search-btn', function () { loadFeedPage(1); });
        $el.on('change', '.wps-feed-perpage',     function () { loadFeedPage(1); });
        $el.on('keydown', '.wps-feed-search', function (e) {
            if (e.key === 'Enter') { loadFeedPage(1); }
        });
        $el.on('input', '.wps-feed-search', function () {
            $el.find('.wps-feed-clear-btn').toggle($.trim($(this).val()) !== '');
        });
        $el.on('click', '.wps-feed-clear-btn', function () {
            $el.find('.wps-feed-search').val('');
            $(this).hide();
            loadFeedPage(1);
        });

        loadFeedPage(1);
    }

    /* ── Grid mode: paginated researcher directory ─────────── */
    function initGridMode($el, groupId, settings, targetPage) {
        const restBase = scholar_sync_public_object.rest + 'group-display';

        $el.html('<div class="scholar-sync-group-grid-wrap"></div><div class="scholar-sync-group-grid-pagination"></div>');

        function loadGridPage(page) {
            const $grid = $el.find('.scholar-sync-group-grid-wrap');
            $grid.html('<p class="scholar-sync-loading">Loading…</p>');

            $.ajax({
                url:     restBase,
                type:    'GET',
                data:    { id: groupId, authors_page: page, authors_per_page: settings.per_page || 12 },
                headers: { 'X-WP-Nonce': scholar_sync_public_object.rest_nonce },
                success: function (data) {
                    renderGrid($grid, data.authors || [], settings, targetPage);
                    ScholarSyncPagination.render(
                        $el.find('.scholar-sync-group-grid-pagination'),
                        { current_page: data.authors_page, pages: data.authors_pages },
                        loadGridPage
                    );
                },
                error: function () {
                    $grid.html('<p class="scholar-sync-error">Could not load group.</p>');
                }
            });
        }

        loadGridPage(1);
    }

    function loadGroup(el) {
        const $el = $(el);
        const groupId = $el.data('group-id');
        const restBase = scholar_sync_public_object.rest + 'group-display';

        $el.html('<p class="scholar-sync-loading">Loading…</p>');

        $.ajax({
            url:     restBase,
            type:    'GET',
            data:    { id: groupId },
            headers: { 'X-WP-Nonce': scholar_sync_public_object.rest_nonce },
            success: function (data) {
                const group = data.group || {};
                const authors = data.authors || [];

                // Shortcode data-* attrs can override DB settings.
                const settings = $.extend({}, group.settings || {});
                if ($el.data('columns')      !== undefined) { settings.columns      = $el.data('columns'); }
                if ($el.data('image-shape')  !== undefined) { settings.image_shape  = $el.data('image-shape'); }
                if ($el.data('shadow')       !== undefined) { settings.shadow       = $el.data('shadow'); }
                if ($el.data('article-image') !== undefined) { settings.show_article_image = String($el.data('article-image')) !== '0'; }
                if ($el.data('per-page')     !== undefined) { settings.per_page     = parseInt($el.data('per-page'), 10) || 12; }
                // Legacy combined toggle — applies to both institution and tags unless the
                // finer-grained attributes below are also present (those win, since they're
                // read after this).
                if ($el.data('show-text')    !== undefined) {
                    const showText = $el.data('show-text') !== '0' && $el.data('show-text') !== 0;
                    settings.show_institution = showText;
                    settings.show_tags        = showText;
                }
                if ($el.data('show-position')     !== undefined) { settings.show_position     = String($el.data('show-position')) !== '0'; }
                if ($el.data('show-institution')  !== undefined) { settings.show_institution  = String($el.data('show-institution')) !== '0'; }
                if ($el.data('show-tags')         !== undefined) { settings.show_tags         = String($el.data('show-tags')) !== '0'; }
                if ($el.data('max-tags')          !== undefined) { settings.max_tags          = parseInt($el.data('max-tags'), 10) || 3; }
                if ($el.data('show-publications') !== undefined) { settings.show_publications = String($el.data('show-publications')) !== '0'; }
                if ($el.data('show-profile-link') !== undefined) { settings.show_profile_link = String($el.data('show-profile-link')) !== '0'; }

                const targetPage = $el.data('target-page') || '';
                const showSearch = ($el.data('search') !== 0);
                const sortBy = $el.data('sort-by') || '';

                if (group.view_type === 'feed') {
                    const feedOptions = {
                        showCitedBy: $el.data('cited-by') !== 0,
                        showCoAuthors: $el.data('co-authors') !== 0,
                        showAuthorPhotos: $el.data('co-author-photos') !== 0,
                        // Group feeds hide article images unless enabled via attribute or group setting.
                        showArticleImage: settings.show_article_image === true || settings.show_article_image === 1 || settings.show_article_image === '1',
                    };
                    // Apply image styling attrs so CSS selectors work on the container.
                    $el.attr('data-image-shadow', $el.data('shadow') === '0' || $el.data('shadow') === 0 ? '0' : '1');
                    $el.attr('data-image-shape',  settings.image_shape || 'circle');
                    initFeedMode($el, groupId, settings, showSearch, feedOptions, sortBy);
                } else {
                    initGridMode($el, groupId, settings, targetPage);
                }
            },
            error: function () {
                $el.html('<p class="scholar-sync-error">Could not load group.</p>');
            }
        });
    }

    // Tags "+N more" toggle (delegated — cards are re-rendered on every page load).
    $(document).on('click', '.scholar-sync-group-card-tags-toggle', function () {
        const $btn = $(this);
        const $tags = $btn.closest('.scholar-sync-group-card-tags');
        const isExpanded = $btn.attr('aria-expanded') === 'true';
        $tags.find('.scholar-sync-group-card-tag-overflow').prop('hidden', isExpanded);
        $btn.attr('aria-expanded', String(!isExpanded));
        $btn.text(isExpanded ? $btn.data('label') : 'Show less');
    });

    $(document).ready(function () {
        $('.scholar-sync-group-shortcode').each(function () {
            loadGroup(this);
        });
    });

}(jQuery));
