(function ($){
    'use strict';

    $( document ).ready(function() {


        $(document).on('click','#kbx_qc_content_generator', function(){

            //console.log('working');
            $('#kbx_qc_content_generator_modal').modal( { backdrop: 'static', keyboard: false  }, 'show');
            jQuery('#kbx_qc_content_generator_modal').modal('show')
            
        });


        $(document).on('click','#kbx_qc_floating_openai_keyword_suggestion', function(){
            var qcld_keyword_suggestion         = $('#kbx_qc_floating_openai_keyword_suggestion_mf').val();
            var qcld_keyword_number             = $('#qcld_keyword_number').val();
            var kbx_qc_article_language           = $('#kbx_qc_article_language').val();
            var kbx_qc_article_number_of_heading  = $('#kbx_qc_article_number_of_heading').val();
            var kbx_qc_article_heading_tag        = $('#kbx_qc_article_heading_tag').val();
            var kbx_qc_article_heading_style      = $('#kbx_qc_article_heading_style').val();
            var kbx_qc_article_heading_tone       = $('#kbx_qc_article_heading_tone').val();
            var kbx_qc_article_heading_img        = $('#kbx_qc_article_heading_img').val();
            var kbx_qc_article_heading_img        = $("input[name=kbx_qc_article_heading_img]:checked").val();
            var kbx_qc_article_heading_tagline    = $("input[name=kbx_qc_article_heading_tagline]:checked").val();
            var kbx_qc_article_heading_intro      = $("input[name=kbx_qc_article_heading_intro]:checked").val();
            var kbx_qc_article_heading_conclusion = $("input[name=kbx_qc_article_heading_conclusion]:checked").val();
            var kbx_qc_article_label_anchor_text  = $('#kbx_qc_article_label_anchor_text').val();
            var kbx_qc_article_target_url         = $('#kbx_qc_article_target_url').val();
            var kbx_qc_article_target_label_cta   = $('#kbx_qc_article_target_label_cta').val();
            var kbx_qc_article_cta_pos            = $('#kbx_qc_article_cta_pos').val();
            var kbx_qc_article_label_keywords     = $('#kbx_qc_article_label_keywords').val();
            var kbx_qc_article_label_word_to_avoid= $('#kbx_qc_article_label_word_to_avoid').val();
            var kbx_qc_article_label_keywords_bold= $("input[name=kbx_qc_article_label_keywords_bold]:checked").val();
            var kbx_qc_article_heading_faq        = $("input[name=kbx_qc_article_heading_faq]:checked").val();
            var kbx_qc_article_img_size           = $('#kbx_qc_article_img_size').val();

            $('#kbx_qc_floating_openai_keyword_suggestion').addClass('spinning');
            $('#kbx_qc_floating_openai_keyword_suggestion').prop("disabled",true);
            $('#kbx_qc_floating_bait_article_keyword_data').hide();
            $('.qcld_seo-playground-buttons').hide();

            $.ajax({
              url: kbx_qc_floating_ajaxurl,
              method: 'POST',
              data: {
                  'action': 'kbx_qc_floating_openai_keyword_suggestion_content_function',
                  'keyword'                         : qcld_keyword_suggestion,
                  'keyword_number'                  : qcld_keyword_number,
                  'kbx_qc_article_language'           : kbx_qc_article_language,
                  'kbx_qc_article_number_of_heading'  : kbx_qc_article_number_of_heading,
                  'kbx_qc_article_heading_tag'        : kbx_qc_article_heading_tag,
                  'kbx_qc_article_heading_style'      : kbx_qc_article_heading_style,
                  'kbx_qc_article_heading_tone'       : kbx_qc_article_heading_tone,
                  'kbx_qc_article_heading_img'        : kbx_qc_article_heading_img,
                  'kbx_qc_article_heading_tagline'    : kbx_qc_article_heading_tagline,
                  'kbx_qc_article_heading_intro'      : kbx_qc_article_heading_intro,
                  'kbx_qc_article_heading_conclusion' : kbx_qc_article_heading_conclusion,
                  'kbx_qc_article_label_anchor_text'  : kbx_qc_article_label_anchor_text,
                  'kbx_qc_article_target_url'         : kbx_qc_article_target_url,
                  'kbx_qc_article_target_label_cta'   : kbx_qc_article_target_label_cta,
                  'kbx_qc_article_cta_pos'            : kbx_qc_article_cta_pos,
                  'kbx_qc_article_label_keywords'     : kbx_qc_article_label_keywords,
                  'kbx_qc_article_label_word_to_avoid': kbx_qc_article_label_word_to_avoid,
                  'kbx_qc_article_label_keywords_bold': kbx_qc_article_label_keywords_bold,
                  'kbx_qc_article_heading_faq'        : kbx_qc_article_heading_faq,
                  'kbx_qc_article_img_size'           : kbx_qc_article_img_size,
                  'security'                        : kbx_qc_floating_ajax_nonce
                  //'selectedlanguage': selectedlanguage,
              },
              dataType: 'json',
              success: function(response) {
                //$('#kbx_qc_floating_bait_keyword_data').append(response.keywords);
                $('#kbx_qc_floating_openai_keyword_suggestion').prop("disabled",false);
                $('#kbx_qc_floating_openai_keyword_suggestion').removeClass('spinning');
                $('.qcld_seo-playground-buttons').show();
                //$('#kbx_qc_floating_bait_article_keyword_data').html('<div class="qcld_copied-content-wrap"><div class="qcld_copied-content_text btn d-none link-success">Copied</div><a class="btn btn-sm btn-secondary qcld-copied-content_text"><span class="dashicons dashicons-admin-page"></span></a></div><textarea id="kbx_qc_floating_content_result_msg">' + response.keywords +'</textarea>');
                //$('#kbx_qc_floating_bait_article_keyword_data').append('<div class="kbx_qc_floating_content_result_wrap"><div class="kbx_qc_floating_rewrite_result_count">' + response.keywords.length +'</div></div>');
                        // kbx_qc_floating_content_result_msg
                $('#kbx_qc_floating_content_result_msg').focus();
                $('#kbx_qc_floating_content_result_msg').focusout();
                $('#kbx_qc_floating_bait_article_keyword_data').show();
                $('#kbx_qc_floating_content_rewrite_result').show();
                $('.kbx_qc_floating_bait_single_field .kbx_qc_floating_rewrite_result_count').text( response.keywords.length );
                var editor = tinyMCE.get('kbx_qc_floating_content_result_msg');
                var basicEditor = true;
                if ( $('#wp-kbx_qc_floating_content_result_msg-wrap').hasClass('tmce-active') && editor ) {
                    basicEditor = false;
                }
                if(basicEditor){
                    $('#kbx_qc_floating_content_result_msg').val( response.keywords );
                }else{
                    editor.setContent( response.keywords );
                }
              }
            });

        });


        $(document).on('click', '.kbx_qc_floating_openai_article_save', function (e) {
            var kbx_qc_floating_draft_btn = $(this);
            var title = $('#kbx_qc_floating_openai_keyword_suggestion_mf').val();
            var content = $('#kbx_qc_floating_content_result_msg').val();

            var editor = tinyMCE.get('kbx_qc_floating_content_result_msg');
            var basicEditor = true;
            if ( $('#wp-kbx_qc_floating_content_result_msg-wrap').hasClass('tmce-active') && editor ) {
                basicEditor = false;
            }

            if(!basicEditor){
                var content = editor.getContent();

            }

            if(title === ''){
                alert('Please enter title');
            }else if(content === ''){
                alert('Please wait content generated');
            }else{
                $.ajax({
                    url: kbx_qc_floating_ajaxurl,
                    data: {title: title, content: content, action: 'kbx_qc_floating_openai_save_draft_post_extra', security: kbx_qc_floating_ajax_nonce },
                    dataType: 'json',
                    type: 'POST',
                    beforeSend: function (){
                        kbx_qc_floating_draft_btn.attr('disabled','disabled');
                        kbx_qc_floating_draft_btn.append('<span class="spinner"></span>');
                        kbx_qc_floating_draft_btn.find('.spinner').css('visibility','unset');
                    },
                    success: function (res){
                        kbx_qc_floating_draft_btn.removeAttr('disabled');
                        kbx_qc_floating_draft_btn.find('.spinner').remove();
                        if(res.status === 'success'){
                            window.location.replace( res.post_link );
                        }
                        else{
                            alert(res.msg);
                        }
                    },
                    error: function (){
                        kbx_qc_floating_draft_btn.removeAttr('disabled');
                        kbx_qc_floating_draft_btn.find('.spinner').remove();
                        alert('Something went wrong');
                    }
                });
            }
        });

        $(document).on('click','#kbx_qc_floating_openai_keyword_rewrite_article',function(event){
            var kbx_qc_floating_content_rewrite = $('#kbx_qc_floating_content_rewrite').val();
            $('#kbx_qc_floating_openai_keyword_rewrite_article').addClass('spinning');
            $('#kbx_qc_floating_content_rewrite_result').hide();
            $.ajax({
              url: kbx_qc_floating_ajaxurl,
              method: 'POST',
              data: {
                  'action': 'kbx_qc_floating_openai_keyword_rewrite_article',
                  'security': kbx_qc_floating_ajax_nonce,
                  'keyword': kbx_qc_floating_content_rewrite,
              },
              dataType: 'json',
              success: function(response) {
                //$('#kbx_qc_floating_content_rewrite_result').html('<div class="qcld_copied-content-wrap"><div class="qcld_copied-content btn d-none link-success">Copied</div><a class="btn btn-sm btn-secondary qcld-copied-content"><span class="dashicons dashicons-admin-page"></span></a></div><textarea id="kbx_qc_floating_content_rewrite_result_msg">' + response.keywords +'</textarea>');
                //$('#kbx_qc_floating_content_rewrite_result').append('<div class="kbx_qc_floating_rewrite_result_count_wrap"><div class="kbx_qc_floating_rewrite_result_count">' + response.keywords.length +'</div></div>');
                $('#kbx_qc_floating_content_rewrite_result').show();
                var editor = tinyMCE.get('kbx_qc_floating_content_rewrite_result_msg');
                var basicEditor = true;
                if ( $('#wp-kbx_qc_floating_content_rewrite_result_msg-wrap').hasClass('tmce-active') && editor ) {
                    basicEditor = false;
                }
                if(basicEditor){
                    $('#kbx_qc_floating_content_rewrite_result_msg').val( response.keywords );
                }else{
                    editor.setContent( response.keywords );
                }
                var words = $.trim(response.keywords).split(" ");
                //console.log(words.length)
                $('.kbx_qc_floating_rewrite_result_count_wrap .kbx_qc_floating_rewrite_result_count').text( words.length );
                $('#kbx_qc_floating_content_rewrite_result_msg').focus();
                $('#kbx_qc_floating_content_rewrite_result_msg').focusout();
                $('#kbx_qc_floating_openai_keyword_rewrite_article').removeClass('spinning');
              }
            });
          

        });

        $(document).on('click', '.kbx_qc_floating_openai_article_clear', function (e) {

            $('#kbx_qc_floating_openai_keyword_suggestion_mf').val('');
            $('#kbx_qc_floating_content_result_msg').val('');
            $('.qcld_seo-playground-buttons').hide();
            $('.kbx_qc_floating_rewrite_result_count').hide();

        });

        $(document).on('keyup focusout','#kbx_qc_floating_content_rewrite',function(event){
            var currentDom = $(this);
            $('.kbx_qc_floating_content_rewrite_count').remove();
            var words = $.trim(currentDom.val()).split(" ");
            $('.kbx_qc_floating_content_rewrite_count_wrap').html('<span class="kbx_qc_floating_content_rewrite_count">'+words.length+'</span>');
        });

        $(document).on('keyup focusout','#kbx_qc_floating_content_rewrite_result_msg',function(event){
            var currentDomss = $(this);
            var editor = tinyMCE.get('kbx_qc_floating_content_rewrite_result_msg');
            var basicEditor = true;
            if ( $('#wp-kbx_qc_floating_content_rewrite_result_msg-wrap').hasClass('tmce-active') && editor ) {
                basicEditor = false;
            }
            if(basicEditor){
                var wordsss = $.trim(currentDomss.val()).split(" ");
            }else{
                var datasssss = editor.setContent( );
                var wordsss = $.trim(datasssss).split(" ");
            }
            $('.kbx_qc_floating_rewrite_result_count_wrap .kbx_qc_floating_rewrite_result_count').text(wordsss.length);
        });

        $(document).on('keyup focusout','#kbx_qc_floating_content_result_msg',function(event){
            var currentDoms = $(this);
            var wordss = $.trim(currentDoms.val()).split(" ");
            $('.kbx_qc_floating_bait_single_field .kbx_qc_floating_rewrite_result_count').text(wordss.length);
        });

        $(document).on('click','.qcld-copied-content',function(event){
            var currentDom = $(this);
            var copy_con = $('#kbx_qc_floating_content_rewrite_result_msg').val();

            var editor = tinyMCE.get('kbx_qc_floating_content_rewrite_result_msg');
            var basicEditor = true;
            if ( $('#wp-kbx_qc_floating_content_rewrite_result_msg-wrap').hasClass('tmce-active') && editor ) {
                basicEditor = false;
            }

            if(!basicEditor){
                var copy_con = editor.getContent();

            }
            

            $(this).addClass("qcld_copied");

            $(".qcld_copied-content").removeClass("d-none");
            setTimeout(() => {
                $(".qcld_copied-content").addClass("d-none");
            }, 1500);
            var $temp = $("<input>");
            //$("body").append($temp);
            currentDom.append($temp);
            $temp.val( copy_con ).select();
            document.execCommand("copy");
            $temp.remove();

        });
        $(document).on('click','.qcld-copied-content_text',function(event){
            var currentDom = $(this);
            var copy_con = currentDom.parent().parent().parent().find('#kbx_qc_floating_content_result_msg').val();
            var copy_text = (copy_con !== '') ? copy_con : currentDom.parent().parent().parent().find('#kbx_qc_floating_content_result_msg').text();

            var editor = tinyMCE.get('kbx_qc_floating_content_result_msg');
            var basicEditor = true;
            if ( $('#wp-kbx_qc_floating_content_result_msg-wrap').hasClass('tmce-active') && editor ) {
                basicEditor = false;
            }

            if(!basicEditor){
                var copy_text = editor.getContent();
            }

            currentDom.addClass("qcld_copied");

            currentDom.parent().find(".qcld_copied-content_text").removeClass("d-none");
            setTimeout(() => {
            currentDom.parent().find(".qcld_copied-content_text").addClass("d-none");
            }, 1500);

            var $temp = $("<input>");
            currentDom.append($temp);
            $temp.val( copy_text ).select();
            document.execCommand("copy");
            $temp.remove();

        });

        var kbx_qc_floating_generator_working = false;
        var eventGenerator = false;
        var kbx_qc_floating_limitLines = 5;
        function qcld_stopOpenAIGenerator(){
            $('.qcld_seo-playground-buttons').show();
            $('.kbx_qc_floating_openai_generator_stop').hide();
            kbx_qc_floating_generator_working = false;
            $('.kbx_qc_floating_generator_button .spinner').hide();
            $('.kbx_qc_floating_generator_button').removeAttr('disabled');
            //eventGenerator.close();
        }
        $(document).on('click', '.kbx_qc_floating_openai_generator_stop', function (e) {
            qcld_stopOpenAIGenerator();
        });

        $(document).on('click', '.kbx_qc_floating_openai_generator_button', function (e) {
            var btn = $(this);
            var title = $('.kbx_qc_floating_prompt').val();
            if( title !== '' ) {
                var count_line = 0;
                var kbx_qc_floating_generator_result = $('.kbx_qc_floating_generator_result');
                kbx_qc_floating_generator_result.val('');
                $('.kbx_qc_floating_openai_generator_stop').show();
                $('.qcld_seo-playground-buttons').hide();
                $('.kbx_qc_floating_openai_generator_button').addClass('spinning');

                var editor = tinyMCE.get('kbx_qc_floating_generator_result');
                var basicEditor = true;
                if ( $('#wp-kbx_qc_floating_generator_result-wrap').hasClass('tmce-active') && editor ) {
                    basicEditor = false;
                }
                var kbx_qc_floating_currentContent_Text = '';
                //console.log( eventGenerator );

                $.ajax({
                    url: kbx_qc_floating_ajaxurl,
                    data: { title: title, action: 'kbx_qc_floating_openai_kbx_qc_content_generator_by_ajax', security: kbx_qc_floating_ajax_nonce },
                    dataType: 'json',
                    type: 'POST',
                    beforeSend: function (){
                        btn.attr('disabled','disabled');
                        btn.find('.spinner').show();
                        btn.find('.spinner').css('visibility','unset');
                    },
                    success: function (res){
                        btn.removeAttr('disabled');
                        $('.kbx_qc_floating_openai_generator_stop').hide();
                        $('.kbx_qc_floating_openai_generator_button').removeClass('spinning');
                        //console.log( res)
                        if(res.status === 'success'){
                            //window.location.href;
                            $('.qcld_seo-playground-buttons').show();
                            if(basicEditor){
                                kbx_qc_floating_currentContent_Text = $('#kbx_qc_floating_generator_result').val();
                            }else{
                                kbx_qc_floating_currentContent_Text = editor.getContent();
                                kbx_qc_floating_currentContent_Text = kbx_qc_floating_currentContent_Text.replace(/<\/?p(>|$)/g, "");
                            }
                            if(e.data === "[DONE]"){
                                count_line += 1;
                                if(basicEditor) {

                                    $('#kbx_qc_floating_generator_result').val( kbx_qc_floating_currentContent_Text + '<br><br>' );

                                }else{

                                    editor.setContent( kbx_qc_floating_currentContent_Text + '<br><br>' );

                                }
                            } else{
                               

                                if(basicEditor){
                                    
                                    if(res.title){
                                        $('.kbx_qc_floating_prompt').val( res.title );
                                    }
                                    $('#kbx_qc_floating_generator_result').val( res.data );

                                }else{
                                    if(res.title){
                                        $('.kbx_qc_floating_prompt').val( res.title );
                                    }
                                    editor.setContent(kbx_qc_floating_currentContent_Text+  res.data );

                                }


                            }
                            
                            if(count_line === kbx_qc_floating_limitLines){
                                qcld_stopOpenAIGenerator();
                            }




                        }else{
                            alert(res.msg);
                        }
                    },
                    error: function (){
                        btn.removeAttr('disabled');
                        btn.find('.spinner').remove();
                        $('.kbx_qc_floating_openai_generator_stop').hide();
                        alert('Something went wrong');
                    }
                });

            }
        });
    
        $(document).on('click', '.kbx_qc_floating_openai_playground_save', function (e) {
            var kbx_qc_floating_draft_btn = $(this);
            var title = $('.kbx_qc_floating_prompt').val();
            var editor = tinyMCE.get('kbx_qc_floating_generator_result');
            var basicEditor = true;
            if ( $('#wp-kbx_qc_floating_generator_result-wrap').hasClass('tmce-active') && editor ) {
                basicEditor = false;
            }
            var content = '';
            if (basicEditor){
                content = $('#kbx_qc_floating_generator_result').val();
            }else{
                content = editor.getContent();
            }
            if(title === ''){
                alert('Please enter title');
            }
            else if(content === ''){
                alert('Please wait content generated');
            }
            else{
                $.ajax({
                    url: ajaxurl,
                    data: {title: title, content: content, action: 'kbx_qc_floating_openai_save_draft_post_extra', security: kbx_qc_floating_ajax_nonce },
                    dataType: 'json',
                    type: 'POST',
                    beforeSend: function (){
                        kbx_qc_floating_draft_btn.attr('disabled','disabled');
                        kbx_qc_floating_draft_btn.append('<span class="spinner"></span>');
                        kbx_qc_floating_draft_btn.find('.spinner').css('visibility','unset');
                    },
                    success: function (res){
                        kbx_qc_floating_draft_btn.removeAttr('disabled');
                        kbx_qc_floating_draft_btn.find('.spinner').remove();
                        if(res.status === 'success'){
                            //window.location.href;
                            window.location.replace( res.post_link );
                        }
                        else{
                            alert(res.msg);
                        }
                    },
                    error: function (){
                        kbx_qc_floating_draft_btn.removeAttr('disabled');
                        kbx_qc_floating_draft_btn.find('.spinner').remove();
                        alert('Something went wrong');
                    }
                });
            }
        });
        $(document).on('click', '.kbx_qc_floating_openai_playground_clear', function (e) {

            $('.kbx_qc_floating_prompt').val('');
            var editor = tinyMCE.get('kbx_qc_floating_generator_result');
            var basicEditor = true;
            if ( $('#wp-kbx_qc_floating_generator_result-wrap').hasClass('tmce-active') && editor ) {
                basicEditor = false;
            }
            if(basicEditor){
                $('#kbx_qc_floating_generator_result').val('');
            }
            else{
                editor.setContent('');
            }
        });

    });

})(jQuery)