/**
 * DESCRIPTION: Handles the WPUF View Control bulk edit panel interaction on the Posts list table.
 * Intercepts the bulk action, shows/hides the panel, and submits restriction settings.
 */

/* global wp, inlineEditPost */
( function( $ ) {
    'use strict';

    $( function() {
        var $panel = $( '#wpuf-view-control-edit' );
        var i18n   = window.wpufBulkViewControl || {};

        // Intercept the "Apply" button click for our bulk action
        $( '#doaction, #doaction2' ).on( 'click', function( e ) {
            var selectName = $( this ).attr( 'id' ) === 'doaction' ? 'action' : 'action2';
            var action = $( 'select[name="' + selectName + '"]' ).val();

            if ( 'wpuf_view_control' !== action ) {
                return;
            }

            e.preventDefault();

            var $checkedPosts = $( 'tbody th.check-column input[type="checkbox"]:checked' );

            if ( $checkedPosts.length < 1 ) {
                return;
            }

            // Close any existing inline editors
            if ( typeof inlineEditPost !== 'undefined' ) {
                inlineEditPost.revert();
            }

            // Build the titles list
            var titlesHtml = '';
            $checkedPosts.each( function() {
                var id = $( this ).val();
                var theTitle = $( '#inline_' + id + ' .post_title' ).html() || wp.i18n.__( '(no title)' );
                var buttonText = wp.i18n.sprintf(
                    /* translators: %s: Post title. */
                    wp.i18n.__( 'Remove "%s" from WPUF View Control' ),
                    theTitle
                );

                titlesHtml += '<li class="ntdelitem">' +
                    '<button type="button" id="wpuf-vc-_' + id + '" class="button-link ntdelbutton">' +
                        '<span class="screen-reader-text">' + buttonText + '</span>' +
                    '</button>' +
                    '<span class="ntdeltitle" aria-hidden="true">' + theTitle + '</span>' +
                '</li>';
            });

            $( '#wpuf-vc-bulk-titles' ).html( '<ul id="wpuf-vc-bulk-titles-list" role="list">' + titlesHtml + '</ul>' );

            // Update colspan to match visible columns
            var colCount = $( 'th:visible, td:visible', '.widefat:first thead' ).length;
            $panel.find( 'td' ).attr( 'colspan', colCount );

            // Insert the panel at the top of the table
            $( 'table.widefat tbody' ).prepend( $panel ).prepend( '<tr class="hidden"></tr>' );
            $panel.addClass( 'inline-editor' ).show();

            // Reset form fields
            $( '#wpuf-vc-display' ).val( '' );
            $( '#wpuf-vc-roles-wrap' ).hide();
            $( '#wpuf-vc-subscriptions-wrap' ).hide();
            $( '#wpuf-vc-no-selection-msg' ).show();
            $panel.find( 'input[type="checkbox"]' ).prop( 'checked', false );

            // Focus and scroll
            $panel.find( '.inline-edit-wrapper' ).attr( 'tabindex', '-1' ).trigger( 'focus' );
            $( 'html, body' ).animate( { scrollTop: 0 }, 'fast' );
        });

        // Toggle roles/subscriptions based on visibility selection
        $( document ).on( 'change', '#wpuf-vc-display', function() {
            var val = $( this ).val();
            $( '#wpuf-vc-roles-wrap' ).toggle( val === 'loggedin' );
            $( '#wpuf-vc-subscriptions-wrap' ).toggle( val === 'subscription' );
            $( '#wpuf-vc-no-selection-msg' ).toggle( val === '' );
        });

        // Remove post from titles list
        $( document ).on( 'click', '#wpuf-vc-bulk-titles .ntdelbutton', function() {
            var $btn = $( this );
            var id = $btn.attr( 'id' ).replace( 'wpuf-vc-_', '' );
            var $prev = $btn.parent().prev().children( '.ntdelbutton' );
            var $next = $btn.parent().next().children( '.ntdelbutton' );

            // Uncheck the corresponding post checkbox
            $( 'table.widefat input[value="' + id + '"]' ).prop( 'checked', false );
            $btn.parent().remove();

            if ( $next.length ) {
                $next.trigger( 'focus' );
            } else if ( $prev.length ) {
                $prev.trigger( 'focus' );
            } else {
                wpufVcRevert();
            }
        });

        // Cancel button
        $( document ).on( 'click', '#wpuf-vc-bulk-cancel', function() {
            wpufVcRevert();
        });

        // Escape key
        $panel.on( 'keyup', function( e ) {
            if ( e.which === 27 ) {
                wpufVcRevert();
            }
        });

        // Update button — submit the form
        $( document ).on( 'click', '#wpuf-vc-bulk-update', function() {
            var display = $( '#wpuf-vc-display' ).val();

            if ( ! display ) {
                window.alert( i18n.selectVisibility || 'Please select a visibility option.' );
                return;
            }

            if ( 'loggedin' === display && $( 'input[name="wpuf_res_loggedin[]"]:checked' ).length < 1 ) {
                window.alert( i18n.selectRole || 'Please select at least one user role.' );
                return;
            }

            if ( 'subscription' === display && $( 'input[name="wpuf_res_subscription[]"]:checked' ).length < 1 ) {
                window.alert( i18n.selectSubscription || 'Please select at least one subscription plan.' );
                return;
            }

            $panel.find( '.spinner' ).addClass( 'is-active' );

            var $form = $( '#posts-filter' );

            // Set the bulk action value so handle_bulk_actions fires
            $form.find( 'select[name="action"]' ).val( 'wpuf_view_control' );

            // Append our fields to the form before submitting
            var $hiddenFields = $( '<div id="wpuf-vc-hidden-fields"></div>' );
            $hiddenFields.append( '<input type="hidden" name="wpuf_res_display" value="' + display + '" />' );
            $hiddenFields.append( $panel.find( 'input[name="wpuf_vc_nonce"]' ).clone() );

            if ( 'loggedin' === display ) {
                $( 'input[name="wpuf_res_loggedin[]"]:checked' ).each( function() {
                    $hiddenFields.append( '<input type="hidden" name="wpuf_res_loggedin[]" value="' + $( this ).val() + '" />' );
                });
            }

            if ( 'subscription' === display ) {
                $( 'input[name="wpuf_res_subscription[]"]:checked' ).each( function() {
                    $hiddenFields.append( '<input type="hidden" name="wpuf_res_subscription[]" value="' + $( this ).val() + '" />' );
                });
            }

            $form.append( $hiddenFields );
            $form.trigger( 'submit' );
        });

        /**
         * Hide and reset the WPUF View Control panel
         */
        function wpufVcRevert() {
            $panel.removeClass( 'inline-editor' ).hide().siblings( '.hidden' ).remove();
            $( '#wpuf-vc-bulk-titles' ).empty();
            $panel.find( '.spinner' ).removeClass( 'is-active' );

            // Move the panel back to a safe hidden location
            if ( ! $( '#wpuf-view-control-edit' ).closest( 'table' ).length ) {
                $( '<table style="display:none;"><tbody></tbody></table>' ).append( $panel ).appendTo( 'body' );
            }
        }

    }); // end document ready
} )( jQuery );
