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

    /* ── Dual listbox (group edit page) ────────────────────────── */

    // Persists manually entered link values across add/remove/reorder cycles.
    var savedLinks = {};

    function serializeSelected() {
        var ids = [];
        $('#scholar-sync-selected option').each(function () {
            ids.push($(this).val());
        });
        $('#group_author_ids').val(ids.join(','));
    }

    function updateLinksTable() {
        var $section = $('#scholar-sync-member-links-section');
        var $tbody   = $('#scholar-sync-member-links-body');
        if ( ! $section.length ) { return; }

        // Capture any values the user has typed before rebuilding.
        $tbody.find('tr').each(function () {
            var aid = String($(this).data('author-id'));
            savedLinks[aid] = $(this).find('input[type="url"]').val();
        });

        $tbody.empty();
        var i = 1;
        $('#scholar-sync-selected option').each(function () {
            var aid     = String($(this).val());
            var name    = $.trim($(this).text());
            var dirLink = $(this).data('dir-link') || '';
            // Priority: value user typed → directory_link fallback
            var linkVal = savedLinks[aid] !== undefined ? savedLinks[aid] : dirLink;

            var $row = $('<tr>').attr('data-author-id', aid);
            $row.append($('<td>').text(i++));
            $row.append($('<td>').text(name));
            var $input = $('<input>').attr({
                type:        'url',
                name:        'member_links[' + aid + ']',
                placeholder: 'https://',
                'class':     'regular-text'
            }).val(linkVal);
            $row.append($('<td>').append($input));
            $tbody.append($row);
        });

        if ($('#scholar-sync-selected option').length > 0) {
            $section.show();
        } else {
            $section.hide();
        }
    }

    function moveOptions(fromId, toId) {
        $(fromId).find('option:selected').appendTo($(toId));
        serializeSelected();
        updateLinksTable();
    }

    function moveUp() {
        var $sel  = $('#scholar-sync-selected');
        $sel.find('option:selected').each(function () {
            var $prev = $(this).prev('option');
            if ($prev.length) { $(this).insertBefore($prev); }
        });
        serializeSelected();
        updateLinksTable();
    }

    function moveDown() {
        var $opts = $('#scholar-sync-selected').find('option:selected').toArray().reverse();
        $.each($opts, function (i, opt) {
            var $next = $(opt).next('option');
            if ($next.length) { $(opt).insertAfter($next); }
        });
        serializeSelected();
        updateLinksTable();
    }

    // Live filter for the available list.
    $('#scholar-sync-author-filter').on('input', function () {
        var term = $(this).val().toLowerCase();
        $('#scholar-sync-available option').each(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(term) !== -1);
        });
    });

    $('#scholar-sync-add-member').on('click',    function () { moveOptions('#scholar-sync-available', '#scholar-sync-selected'); });
    $('#scholar-sync-remove-member').on('click', function () { moveOptions('#scholar-sync-selected',  '#scholar-sync-available'); });
    $('#scholar-sync-move-up').on('click',   moveUp);
    $('#scholar-sync-move-down').on('click', moveDown);

    // Double-click shortcuts.
    $('#scholar-sync-available').on('dblclick', 'option', function () {
        $(this).prop('selected', true);
        moveOptions('#scholar-sync-available', '#scholar-sync-selected');
    });
    $('#scholar-sync-selected').on('dblclick', 'option', function () {
        $(this).prop('selected', true);
        moveOptions('#scholar-sync-selected', '#scholar-sync-available');
    });

    // Make sure hidden field is populated on submit even without JS interaction.
    $('#group-edit-form').on('submit', function () {
        serializeSelected();
    });

    /* ── View-type icon toggle (group edit page) ─────────────── */

    $('input[name="view_type"]').on('change', function () {
        $('.scholar-sync-view-option').removeClass('active');
        $(this).closest('.scholar-sync-view-option').addClass('active');
        // Reordering members only applies to the grid (Staff Directory) view.
        var isGrid = $(this).val() === 'grid';
        $('.scholar-sync-members-ui').toggleClass('is-grid', isGrid).toggleClass('is-feed', !isGrid);
        $('.scholar-sync-view-only-grid').toggle(isGrid);
        $('.scholar-sync-view-only-feed').toggle(!isGrid);
    });

    /* ── Preview sidebar — real-time group preview ───────────── */

    var previewTimer = null;

    // Render the grid view (grid-type groups only).
    function refreshPreview() {
        var $container = $('#scholar-sync-group-preview-container');
        if (!$container.length) { return; }

        var groupId  = $container.data('group-id');
        var restBase = scholar_sync_ajax_object.rest + 'group-display';
        var params = {
            id:                groupId,
            columns:           $('#preview-columns').val()     || 3,
            image_shape:       $('#preview-image-shape').val() || 'circle',
            authors_per_page:  48, // preview shows everything on one page, not paginated
            show_position:     $('#preview-show-position').is(':checked')     ? 1 : 0,
            show_institution:  $('#preview-show-institution').is(':checked')  ? 1 : 0,
            show_tags:         $('#preview-show-tags').is(':checked')         ? 1 : 0,
            max_tags:          parseInt($('#preview-max-tags').val(), 10)     || 3,
            show_publications: $('#preview-show-publications').is(':checked') ? 1 : 0,
            show_profile_link: $('#preview-show-profile-link').is(':checked') ? 1 : 0,
            shadow:            $('#preview-shadow').is(':checked')            ? 1 : 0,
        };

        $container.css('opacity', '0.5');

        $.ajax({
            url:     restBase,
            type:    'GET',
            data:    params,
            headers: { 'X-WP-Nonce': scholar_sync_ajax_object.rest_nonce },
            success: function (data) {
                var authors = data.authors || [];
                var settings = {
                    columns:            params.columns,
                    image_shape:        params.image_shape,
                    show_position:      params.show_position === 1,
                    show_institution:   params.show_institution === 1,
                    show_tags:          params.show_tags === 1,
                    max_tags:           params.max_tags,
                    show_publications:  params.show_publications === 1,
                    show_profile_link:  params.show_profile_link === 1,
                    shadow:             params.shadow === 1,
                };
                $container.css('opacity', '1');
                if (!authors.length) {
                    $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(' + (parseInt(settings.columns, 10) || 2) + ',minmax(260px,1fr))">';
                $.each(authors, function (i, a) {
                    html += scholarSyncRenderGroupCard(a, settings, '');
                });
                html += '</div>';
                $container.html(html);
            },
            error: function () {
                $container.css('opacity', '1').html('<p>Preview unavailable.</p>');
            }
        });
    }

    // Build the shortcode string from the current panel state.
    // group ID and view type are set as window vars by group_preview.php.
    function buildShortcode() {
        if ( ! $('#group-shortcode-display').length ) { return; }

        var groupId = window.scholarSyncGroupId   || 0;
        var isFeed  = window.scholarSyncViewType  === 'feed';

        var sc = '[scholar-sync-group id="' + groupId + '"';
        if ( isFeed ) {
            if ( ! $('#preview-show-search').is(':checked') )       { sc += ' search="0"'; }
            if ( ! $('#preview-show-cited-by').is(':checked') )     { sc += ' cited-by="0"'; }
            if ( ! $('#preview-show-co-authors').is(':checked') )   { sc += ' co-authors="0"'; }
            if ( ! $('#preview-show-co-author-photos').is(':checked') ) { sc += ' co-author-photos="0"'; }
            // Group feeds default to no article images, so the attribute is emitted when ON.
            if ( $('#preview-show-article-image').is(':checked') )  { sc += ' article-image="1"'; }
            var feedSortBy = $('#preview-sort-by').val();
            if ( feedSortBy && feedSortBy !== 'year' )              { sc += ' sort_by="' + feedSortBy + '"'; }
            if ( ! $('#preview-show-image-shadow').is(':checked') ) { sc += ' shadow="0"'; }
            var feedShape = $('#preview-image-shape').val();
            if ( feedShape && feedShape !== 'circle' )              { sc += ' image_shape="' + feedShape + '"'; }
        } else {
            var cols            = parseInt( $('#preview-columns').val(), 10 ) || 2;
            var shape           = $('#preview-image-shape').val() || 'circle';
            var showShadow      = $('#preview-shadow').is(':checked');
            var showPosition    = $('#preview-show-position').is(':checked');
            var showInstitution = $('#preview-show-institution').is(':checked');
            var showTags        = $('#preview-show-tags').is(':checked');
            var maxTags         = parseInt( $('#preview-max-tags').val(), 10 ) || 3;
            var showPubs        = $('#preview-show-publications').is(':checked');
            var showProfileLink = $('#preview-show-profile-link').is(':checked');
            if ( cols !== 2 )          { sc += ' columns="'     + cols  + '"'; }
            if ( shape !== 'circle' )  { sc += ' image_shape="' + shape + '"'; }
            if ( ! showShadow )        { sc += ' shadow="0"'; }
            if ( ! showPosition )      { sc += ' show_position="0"'; }
            if ( ! showInstitution )   { sc += ' show_institution="0"'; }
            if ( ! showTags )          { sc += ' show_tags="0"'; }
            if ( maxTags !== 3 )       { sc += ' max_tags="' + maxTags + '"'; }
            if ( ! showPubs )          { sc += ' show_publications="0"'; }
            if ( ! showProfileLink )   { sc += ' show_profile_link="0"'; }
        }
        sc += ']';

        $('#group-shortcode-display').val( sc );
    }

    function scheduleRefresh() {
        buildShortcode();
        clearTimeout(previewTimer);
        previewTimer = setTimeout(refreshPreview, 350);
    }

    // Bind all preview sidebar controls.
    $(document).on('change input', '.scholar-sync-preview-control', scheduleRefresh);

    // Build shortcode on initial load (works for both feed and grid preview pages).
    if ($('#group-shortcode-display').length) {
        buildShortcode();
    }

    // Initial grid render.
    if ($('#scholar-sync-group-preview-container').length) {
        refreshPreview();
    }

    // Shortcode copy button.
    $(document).on('click', '#copy-group-shortcode', function () {
        var val = $('#group-shortcode-display').val();
        if (navigator.clipboard) {
            navigator.clipboard.writeText(val);
        } else {
            var $tmp = $('<input>').val(val).appendTo('body').select();
            document.execCommand('copy');
            $tmp.remove();
        }
        $(this).text('Copied!');
        setTimeout(function () { $('#copy-group-shortcode').text('Copy'); }, 2000);
    });

}(jQuery));
