(function ( $ ) {
    'use strict';

    // 1) catch clicks on our custom deactivate link
    $(document).on('click', '.verfacto-deactivate-link', function(e){
        e.stopImmediatePropagation();
        e.preventDefault();

        var deactUrl = $(this).data('deact-url');
        $('#verfacto-deactivate-modal')
            .data('deact-url', deactUrl)
            .css('display','flex')
            .hide()
            .fadeIn(200);

        return false;
    });

    // 2) cancel button: hide the modal
    $(document).on('click', '#verfacto-deactivate-cancel', function(){
        $('#verfacto-deactivate-modal').fadeOut(200);
    });

    // 3) Continue: immediate WP-deactivate
    $(document).on('click', '#verfacto-deactivate-continue', function(){
        var $btn = $(this);
        $btn.addClass('loading');

        var deactUrl = $('#verfacto-deactivate-modal').data('deact-url');

        $btn.removeClass('loading');

        window.location = deactUrl;
    });

    // 5) Confirm+delete: schedule & then deactivate
    $(document).on('submit', '#verfacto-deactivate-form', function(e){
        e.preventDefault();

        var $btn = $('#verfacto-deactivate-confirm');
        $btn.addClass('loading');

        var $modal = $('#verfacto-deactivate-modal'),
            deactUrl = $modal.data('deact-url'),
            fd = new FormData(this);

        fd.append('action', 'verfacto_deactivate');
        fd.append('vf_nonce', verfacto_ajax.vf_nonce);

        $modal.find('.verfacto-loader').show();
        $modal.find('.verfacto-error-message').hide().empty();

        $.ajax({
            type:        'POST',
            url:         verfacto_ajax.admin_ajax,
            data:        fd,
            contentType: false,
            processData: false,
            dataType:    'json'
        })
        .done(function(res){
            $btn.removeClass('loading');

            if ( res.success ) {
                window.location = deactUrl;
            }
        })
        .fail(function(jqXHR){
            $btn.removeClass('loading');

            var msg = 'Could not deactivate, please try again.';
            if ( jqXHR.responseJSON && jqXHR.responseJSON.data ) {
                msg = jqXHR.responseJSON.data;
            }

            $modal.find('.verfacto-error-message').text( msg ).show();
        });
    });

  })( jQuery );
