jQuery(document).ready(function ($) {
    'use strict';
    var wpms_dash_widgets = 0;
    var wpms_site_health_data = {
		wpms_overall_progres:[0, "text-red-600", "cancel", "bad"],
		wpms_url_sitemap:[0, "text-red-600", "cancel"],
		wpms_content_optimization:[0, "text-red-600", "cancel"],
		wpms_img_accessibility:[0, "text-red-600", "cancel"],
		wpms_duplicate_category:[0, "text-red-600", "cancel"],
    }
    function dashImgTippy() {
        tippy('.img-infos-tooltip', {
            animation: 'scale',
            duration: 0,
            arrow: false,
            placement: 'top',
            theme: 'wpms-widgets-tippy',
            onShow(instance) {
                instance.popper.hidden = instance.reference.dataset.tippy ? false : true;
                instance.setContent(instance.reference.dataset.tippy);
            }
        });
    }
    function processDashboardCardData (containerClass, progressValue, progressMax, progressText, topicProgress) {
        console.log(progressValue);
		var progressColor = 'text-red-600';
		var progressIcon = 'cancel';
		if (parseInt(progressMax) < 1) {
				progressValue = 100;
				progressMax = 100;
				var percentage = 100;
				progressColor = 'text-green-600';
				progressIcon = 'check_circle';
		} else {
			var percentage = (parseInt(progressValue) / parseInt(progressMax) * 100);
			if (percentage < 90 && percentage >= 35) {
				progressColor = 'text-yellow-600';
				progressIcon = 'warning'
			}
			if (percentage < 35) {
				progressColor = 'text-red-600';
			}
			if (percentage >= 90) {
				progressColor = 'text-green-600';
				progressIcon = 'check_circle';
			}
			if (parseInt(progressValue) >= parseInt(progressMax)) {
				progressMax = parseInt(progressValue);
				percentage = 100;
			}
		}
		$(containerClass).addClass(progressColor)
		$(containerClass + ' .wpms-progress-text').text(progressText)
		$(containerClass + ' .wpms-progress-bar').val(parseInt(progressValue)).attr('max', parseInt(progressMax)).addClass(progressColor)
		$(containerClass + ' .wpms-progress-icon').html('<i class="material-icons">'+progressIcon+'</i>')
		
		var topicTotal = percentage;
		if (wpms_site_health_data[topicProgress][0] > 0) {
			topicTotal = Math.ceil((wpms_site_health_data[topicProgress][0] + percentage) / 2);
		}
		wpms_site_health_data[topicProgress][0] = topicTotal
		wpms_site_health_data["wpms_overall_progres"][0] = Math.ceil((wpms_site_health_data["wpms_url_sitemap"][0] + wpms_site_health_data["wpms_content_optimization"][0] + wpms_site_health_data["wpms_img_accessibility"][0] + wpms_site_health_data["wpms_duplicate_category"][0]) / 4)
		if (wpms_site_health_data[topicProgress][0] >= 35 && wpms_site_health_data[topicProgress][0] < 90) {
			wpms_site_health_data[topicProgress][1] = 'text-yellow-600';
			wpms_site_health_data[topicProgress][2] = 'warning';
		} else if (wpms_site_health_data[topicProgress][0] >= 90) {
			wpms_site_health_data[topicProgress][1] = 'text-green-600';
			wpms_site_health_data[topicProgress][2] = 'check_box';
		} else {
			wpms_site_health_data[topicProgress][1] = 'text-red-600';
			wpms_site_health_data[topicProgress][2] = 'cancel';
		}
		if (wpms_site_health_data["wpms_overall_progres"][0] >= 35 && wpms_site_health_data["wpms_overall_progres"][0] < 90) {
			wpms_site_health_data["wpms_overall_progres"][1] = 'text-yellow-600';
			wpms_site_health_data["wpms_overall_progres"][2] = 'warning';
			wpms_site_health_data["wpms_overall_progres"][3] = 'okay';
		} else if (wpms_site_health_data[topicProgress][0] >= 90) {
			wpms_site_health_data["wpms_overall_progres"][1] = 'text-green-600';
			wpms_site_health_data["wpms_overall_progres"][2] = 'check_box';
			wpms_site_health_data["wpms_overall_progres"][3] = 'excellent';
		} else {
			wpms_site_health_data["wpms_overall_progres"][1] = 'text-red-600';
			wpms_site_health_data["wpms_overall_progres"][2] = 'cancel';
			wpms_site_health_data["wpms_overall_progres"][3] = 'bad';
		}
	}

    // Knob
    $.ajax({
        url: ajaxurl,
        method: 'POST',
        dataType: 'json',
        data: {
            action: 'wpms',
            task: 'dash_permalink',
            wpms_nonce: wpms_localize.wpms_nonce
        },
        success: function (res) {
			var sitemapProgress = parseInt($('.wpms-xml-sitemap .wpms-progress-bar').attr('value'));
            processDashboardCardData('.wpms-url-rewrite', Math.ceil((res + sitemapProgress) / 2), 100, res + '%', "wpms_url_sitemap");
            wpms_site_health_data["wpms_url_sitemap"][0]
            wpms_dash_widgets++;
            if(wpms_dash_widgets === 1){
                wpms_dash_widgets_newcontent();
            }
        }
    });

    function wpms_dash_widgets_newcontent(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'dash_newcontent',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
               // console.log(res);
                if (parseInt(res[1][0]) >= 3) {
					processDashboardCardData('.wpms-fresh-content', 100, 100, res[1][0], "wpms_content_optimization");
                } else if (parseInt(res[1][0]) > 0 && parseInt(res[1][0]) < 3) {
                    processDashboardCardData('.wpms-fresh-content', Math.ceil(res[1][0] / 3 * 100), 100, res[1][0], "wpms_content_optimization");
                } else {
					processDashboardCardData('.wpms-fresh-content', res[1][0], 100, 0, "wpms_content_optimization");
				}
                wpms_dash_widgets++;
                if(wpms_dash_widgets === 2){
                    wpms_dash_widgets_linkmeta();
                }
            }
        });
    }

    function wpms_dash_widgets_linkmeta(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'dash_linkmeta',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
                if (parseInt(res[0]) === 100) {
                    $('.wpms_dash_linkmeta').attr({'src': wpms_localize.images_url + 'checklist/checklist.png', 'data-tippy': wpms_localize.dashboard_tooltips.link_title + res[1][0] + '/' + res[1][1] + ' = 100%'});
                } else {
                    $('.wpms_dash_linkmeta').attr({'src': wpms_localize.images_url + 'icon-info/icon-seo.png', 'data-tippy': wpms_localize.dashboard_tooltips.link_title + res[1][0] + '/' + res[1][1] + ' = ' + res[0] + '%'});
                }
                dashImgTippy();
                wpms_dash_widgets++;
                if(wpms_dash_widgets === 3){
                    wpms_dash_widgets_metatitle();
                }
            }
        });
    }

    function wpms_dash_widgets_metatitle(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'dash_metatitle',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
                processDashboardCardData('.wpms-meta-title', res[0], 100, res[1][0] + '/' + res[1][1] + ' = ' + res[0] + '%', "wpms_content_optimization");
                wpms_dash_widgets++;
                if(wpms_dash_widgets === 4){
                    wpms_dash_widgets_imagemeta(1,0,0,0);
                }
            }
        });
    }

    function wpms_dash_widgets_imagemeta(page,imgs_statis,imgs_meta,imgs_count){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'dash_imgsmeta',
                page : page,
                imgs_statis : imgs_statis,
                imgs_metas_statis : imgs_meta,
                imgs_count : imgs_count,
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
                if(typeof res.status === "undefined"){
                    wpms_dash_widgets_imagemeta(page+1 , res.imgs_statis[0] , res.imgs_metas_statis[0] , res.imgs_count);
                }else{
					processDashboardCardData('.wpms-img-resize', res.imgs_statis[0], res.imgs_statis[1], res.imgs_statis[0], "wpms_img_accessibility");
					processDashboardCardData('.wpms-img-alt-title', res.imgs_statis[0], res.imgs_statis[1], res.imgs_statis[0] + '/' + res.imgs_statis[1] + ' = ' + res.imgs_statis[2] + '%', "wpms_img_accessibility");
                    wpms_dash_widgets++;
                    if(wpms_dash_widgets === 5){
                        if (parseInt(wpms_localize.addon_active) === 0) {
                            wpms_dash_widgets_metadesc();
                        } else {
                            wpms_dash_widgets_duplicate_title();
                        }
                    }
                }
            }
        });
    }

    function wpms_dash_widgets_duplicate_title(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'dash_duplicate_title',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
				processDashboardCardData('.wpms-duplicate-title', res.total_items - res.count_post_duplicate, res.total_items, res.count_post_duplicate, "wpms_duplicate_category");
				wpms_dash_widgets++;
                if(wpms_dash_widgets === 6){
                    wpms_dash_widgets_duplicate_desc();
                }
            }
        });
    }

    function wpms_dash_widgets_duplicate_desc(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'dash_duplicate_desc',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
				processDashboardCardData('.wpms-duplicate-desc', res.total_items - res.count_post_duplicate, res.total_items, res.count_post_duplicate, "wpms_duplicate_category");
                wpms_dash_widgets++;
                if(wpms_dash_widgets === 7){
                    wpms_dash_widgets_metadesc();
                }
            }
        });
    }

    function wpms_dash_widgets_metadesc(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'dash_metadesc',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
                processDashboardCardData('.wpms-meta-desc', res[0], 100, res[1][0] + '/' + res[1][1] + ' = ' + res[0] + '%', "wpms_content_optimization");
                wpms_dash_widgets++;
                if(wpms_dash_widgets === 8){
                    wpms_dash_widgets_metacat();
                }
            }
        });
    }

    function wpms_dash_widgets_metacat(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'dash_metacat',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
				var progressText = wpms_localize.dashboard_tooltips.metatitle + res[0][1] + '/' + res[0][2] + ' = ' + res[0][0] + '%;';
				progressText += "\n";
				progressText += wpms_localize.dashboard_tooltips.metadesc + res[1][1] + '/' + res[1][2] + ' = ' + res[1][0] + '%;'; 
				processDashboardCardData('.wpms-category-meta', Math.ceil((res[0][0] + res[1][0]) / 2), 100, progressText, "wpms_duplicate_category");
				wpms_dash_widgets++;
				$('.wpms-category-meta .wpms-progress-text').css('white-space', 'pre-line');
				
				$('.wpms-seo-health .rdju-radial-progress').css('--rdju-value', wpms_site_health_data["wpms_overall_progres"][0])
				$('.wpms-seo-health .rdju-radial-progress, .wpms-seo-health .wpms-overall-text').addClass(wpms_site_health_data["wpms_overall_progres"][1])
				$('.wpms-seo-health .wpms-overall-progress').text(wpms_site_health_data["wpms_overall_progres"][0])
				$('.wpms-seo-health .wpms-seo-health-text').text(wpms_localize.dashboard_seo_health[wpms_site_health_data["wpms_overall_progres"][3]])
				
				$('.wpms-seo-health .wpms-url-structure-progress').text(wpms_site_health_data["wpms_url_sitemap"][0] + "%")
				$(".wpms-seo-health .wpms-url-structure-icon").addClass(wpms_site_health_data["wpms_url_sitemap"][1]).text(wpms_site_health_data["wpms_url_sitemap"][2])
				
				$('.wpms-seo-health .wpms-content-optimization-progress').text(wpms_site_health_data["wpms_content_optimization"][0] + "%")
				$(".wpms-seo-health .wpms-content-optimization-icon").addClass(wpms_site_health_data["wpms_content_optimization"][1]).text(wpms_site_health_data["wpms_content_optimization"][2])
				
				$('.wpms-seo-health .wpms-img-seo-accessability-progress').text(wpms_site_health_data["wpms_img_accessibility"][0] + "%")
				$(".wpms-seo-health .wpms-img-seo-accessability-icon").addClass(wpms_site_health_data["wpms_img_accessibility"][1]).text(wpms_site_health_data["wpms_img_accessibility"][2])
				
				$('.wpms-seo-health .wpms-duplicate-category-progress').text(wpms_site_health_data["wpms_duplicate_category"][0] + "%")
				$(".wpms-seo-health .wpms-duplicate-category-icon").addClass(wpms_site_health_data["wpms_duplicate_category"][1]).text(wpms_site_health_data["wpms_duplicate_category"][2])
            }
        });
    }

    function reloadWeb(){
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'wpms',
                task: 'reload-web',
                wpms_nonce: wpms_localize.wpms_nonce
            },
            success: function (res) {
                if (res.status) {
                    $('.page-loader').hide();
                    $('.site_img').attr('src', res.link + '?v=' + Math.random());
                }
            }
        });
    }

    $('.wpms-reload-web-btn').on('click', function () {
        $('.page-loader').show();
        reloadWeb();
    });

    dashImgTippy();

    // wpms dashboard redirects
    $('.rdju-dashboard-title').click((e) => {
		var titleEl = $(e.target).closest('.rdju-dashboard-title');
        window.open(titleEl.data('redirect-link'))
    })
});
