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

    var $container = $('.scholar-sync-container[data-author-id], .scholar-sync-container[data-entity-id]').first();
    if (!$container.length) { return; }

    var authorId      = $container.data('author-id') || $container.data('entity-id');
    var showCitedBy   = String($container.data('display-cited-by'))   !== '0';
    var showCoAuthors = String($container.data('display-co-authors')) !== '0';
    var showAuthorPhotos = String($container.data('display-co-author-photos')) !== '0';
    var showArticleImage = String($container.data('display-article-image')) !== '0';
    var restBase      = $container.data('rest-url') || (scholar_sync_public_object.rest + 'display');
    var pluginUrl   = scholar_sync_public_object.plugin_url || '';
    var scholarId   = '';
    var sortBy      = $container.data('sort-by') || '';

    var $feedList  = $container.find('.wps-feed-list');
    var $pagDiv    = $container.find('.wps-author-pagination');
    var $info      = $container.find('.scholar-sync-results-info');
    var $search    = $container.find('#scholar-sync-search');
    var $searchBtn = $container.find('#scholar-sync-search-btn');
    var $clearBtn  = $container.find('#scholar-sync-clear-search');
    var $perPage   = $container.find('#scholar-sync-per-page');

    /* ── Preview sidebar JS (only on admin preview page) ───── */
    (function initPreviewPanel() {
        var panel = document.getElementById('wps-panel');
        if (!panel) { return; }

        var toggle   = document.getElementById('wps-toggle');
        var closeBtn = document.getElementById('wps-panel-close');

        function openPanel()  { panel.classList.remove('is-closed'); if (toggle) { toggle.classList.remove('is-visible'); } }
        function closePanel() { panel.classList.add('is-closed');    if (toggle) { toggle.classList.add('is-visible'); } }

        if (closeBtn) { closeBtn.addEventListener('click', closePanel); }
        if (toggle)   { toggle.addEventListener('click', openPanel); }

        var headerChk       = document.getElementById('preview-show-header');
        var searchChk       = document.getElementById('preview-show-search');
        var citedByChk      = document.getElementById('preview-show-cited-by');
        var coAuthorsChk    = document.getElementById('preview-show-co-authors');
        var coAuthorPhotosChk = document.getElementById('preview-show-co-author-photos');
        var articleImageChk = document.getElementById('preview-show-article-image');
        var sortBySel       = document.getElementById('preview-sort-by');
        var imageShadowChk  = document.getElementById('preview-show-image-shadow');
        var imageShapeSel   = document.getElementById('preview-image-shape');

        function updateDisplay() {
            if (headerChk) {
                $container.find('.scholar-sync-user-profile').toggle(headerChk.checked);
            }
            if (searchChk) {
                $container.find('.scholar-sync-search-row, .scholar-sync-controls-bar').toggle(searchChk.checked);
            }
            if (citedByChk) {
                showCitedBy = citedByChk.checked;
                $container.find('.scholar-sync-cited-by')[showCitedBy ? 'removeAttr' : 'attr']('hidden', '');
            }
            if (coAuthorsChk) {
                showCoAuthors = coAuthorsChk.checked;
                $container.find('.scholar-sync-article-authors')[showCoAuthors ? 'removeAttr' : 'attr']('hidden', '');
            }
            if (coAuthorPhotosChk && showAuthorPhotos !== coAuthorPhotosChk.checked) {
                showAuthorPhotos = coAuthorPhotosChk.checked;
                // Photo markup is omitted (not hidden) when off, so re-render.
                loadPage(1);
            }
            if (articleImageChk && showArticleImage !== articleImageChk.checked) {
                showArticleImage = articleImageChk.checked;
                // Image markup is omitted (not hidden) when off, so re-render.
                loadPage(1);
            }
            if (imageShadowChk) {
                $container.attr('data-image-shadow', imageShadowChk.checked ? '1' : '0');
            }
            if (imageShapeSel) {
                $container.attr('data-image-shape', imageShapeSel.value);
            }
            updateShortcode();
        }

        function updateShortcode() {
            var sc = '[scholar-sync-scholar id="' + authorId + '"';
            if (headerChk    && !headerChk.checked)    { sc += ' header="0"'; }
            if (searchChk    && !searchChk.checked)    { sc += ' search="0"'; }
            if (citedByChk   && !citedByChk.checked)   { sc += ' cited-by="0"'; }
            if (coAuthorsChk && !coAuthorsChk.checked) { sc += ' co-authors="0"'; }
            if (coAuthorPhotosChk && !coAuthorPhotosChk.checked) { sc += ' co-author-photos="0"'; }
            if (articleImageChk && !articleImageChk.checked) { sc += ' article-image="0"'; }
            if (sortBySel    && sortBySel.value !== 'cited_by') { sc += ' sort_by="' + sortBySel.value + '"'; }
            if (imageShadowChk && !imageShadowChk.checked) { sc += ' shadow="0"'; }
            if (imageShapeSel && imageShapeSel.value !== 'circle') { sc += ' image_shape="' + imageShapeSel.value + '"'; }
            sc += ']';
            var display = document.getElementById('author-shortcode-display');
            if (display) { display.value = sc; }
        }

        if (headerChk)      { headerChk.addEventListener('change', updateDisplay); }
        if (searchChk)      { searchChk.addEventListener('change', updateDisplay); }
        if (citedByChk)     { citedByChk.addEventListener('change', updateDisplay); }
        if (coAuthorsChk)   { coAuthorsChk.addEventListener('change', updateDisplay); }
        if (coAuthorPhotosChk) { coAuthorPhotosChk.addEventListener('change', updateDisplay); }
        if (articleImageChk) { articleImageChk.addEventListener('change', updateDisplay); }
        if (sortBySel)      { sortBySel.addEventListener('change', function () { loadPage(1); updateShortcode(); }); }
        if (imageShadowChk) { imageShadowChk.addEventListener('change', updateDisplay); }
        if (imageShapeSel)  { imageShapeSel.addEventListener('change', updateDisplay); }

        var copyBtn = document.getElementById('copy-author-shortcode');
        if (copyBtn) {
            copyBtn.addEventListener('click', function () {
                var display = document.getElementById('author-shortcode-display');
                if (display && navigator.clipboard) {
                    navigator.clipboard.writeText(display.value).then(function () {
                        copyBtn.textContent = 'Copied!';
                        setTimeout(function () { copyBtn.textContent = 'Copy Shortcode'; }, 2000);
                    }).catch(function () {});
                }
            });
        }
    }());


    /* ── Render article cards ────────────────────────────── */
    function renderArticles(articles, authorPhotos) {
        $feedList.empty();

        if (!articles || articles.length === 0) {
            $feedList.html('<p class="scholar-sync-group-empty">No articles found.</p>');
            return;
        }

        authorPhotos = authorPhotos || {};
        var $feedContainer = $('<div class="scholar-sync-feed-container">');

        var cardOptions = { showCitedBy: showCitedBy, showCoAuthors: showCoAuthors, showAuthorPhotos: showAuthorPhotos, showArticleImage: showArticleImage };

        for (var i = 0; i < articles.length; i++) {
            // The link (including the fallback derived from raw scrape data) is
            // resolved server-side; the REST response never ships the raw all_data blob.
            $feedContainer.append(scholarSyncRenderArticleCard(articles[i], i, authorPhotos, pluginUrl, cardOptions));
        }

        $feedList.append($feedContainer);

        // Store articles on container for lazy APA7 generation; wire events once.
        var containerEl = $feedList[0];
        containerEl._feedArticles = articles;
        if (!containerEl._feedEventsWired) {
            containerEl._feedEventsWired = true;
            scholarSyncWireFeedEvents(containerEl);
        }
    }

    /* ── AJAX load ─────────────────────────────────────────── */
    function loadPage(page) {
        var perPage = parseInt($perPage.length ? $perPage.val() : 20, 10) || 20;
        var search  = $search.length ? $.trim($search.val()) : '';

        $feedList.html('<p style="text-align:center;color:#888;">Loading\u2026</p>');

        var sortByEl = document.getElementById('preview-sort-by');
        var currentSortBy = sortByEl ? sortByEl.value : sortBy;

        $.ajax({
            url:     restBase,
            type:    'GET',
            data:    { id: authorId, page: page, per_page: perPage, search: search, sort_by: currentSortBy },
            headers: { 'X-WP-Nonce': scholar_sync_public_object.rest_nonce },
            success: function (data) {
                scholarId = data.scholar_id || '';
                renderArticles(data.articles || [], data.author_photos || {});
                if ($info.length)   { ScholarSyncPagination.renderInfo($info, data); }
                if ($pagDiv.length) { ScholarSyncPagination.render($pagDiv, data, loadPage); }
            },
            error: function () {
                $feedList.html('<p style="text-align:center;color:#c00;">Error loading articles.</p>');
            }
        });
    }

    /* ── Search controls ───────────────────────────────────── */
    function doSearch() {
        var query = $search.length ? $.trim($search.val()) : '';
        if ($clearBtn.length) { $clearBtn.toggle(query !== ''); }
        loadPage(1);
    }

    if ($searchBtn.length) { $searchBtn.on('click', doSearch); }

    if ($search.length) {
        $search.on('keydown', function (e) {
            if (e.key === 'Enter') { doSearch(); }
        });
        $search.on('input', function () {
            if ($clearBtn.length) { $clearBtn.toggle($.trim($(this).val()) !== ''); }
        });
    }

    if ($clearBtn.length) {
        $clearBtn.on('click', function () {
            if ($search.length) { $search.val(''); }
            $(this).hide();
            loadPage(1);
        });
    }

    if ($perPage.length) {
        $perPage.on('change', function () { loadPage(1); });
    }

    /* ── Initial load ───────────────────────────────────────── */
    $(document).ready(function () {
        loadPage(1);
    });

}(jQuery));
