(function($) {
    'use strict';

	$(document).ready(function () {
        $('.ays-chatgpt-assistant-gemini-option').prop('disabled', true);
		var toggle_ddmenu = $(document).find('.toggle_ddmenu');
    	toggle_ddmenu.on('click', function () {
    	    var ddmenu = $(this).next();
    	    var state = ddmenu.attr('data-expanded');
    	    switch (state) {
    	        case 'true':
    	            $(this).find('img').css({
    	                transform: 'rotate(0deg)'
    	            });
    	            ddmenu.attr('data-expanded', 'false');
    	            break;
    	        case 'false':
    	            $(this).find('img').css({
    	                transform: 'rotate(90deg)'
    	            });
    	            ddmenu.attr('data-expanded', 'true');
    	            break;
    	    }
    	});

        $(document).on('keydown', function(e){
			var saveButton = $(document).find('input.ays-chatgpt-assistant-general-settings-save');
			if ( saveButton.length > 0 ) {
                if (!(e.which == 83 && e.ctrlKey) && !(e.which == 19)){
                    return true;
                }
                saveButton.trigger("click");
                e.preventDefault();
                return false;
            }
		});

		// Submit buttons disableing with loader
        $(document).find('.ays-chatgpt-assistant-loader-banner').on('click', function () {        
            var $this = $(this);
            submitOnce($this);
        });

        var userRolesTab1 = $(document).find('#ays_user_roles');
        if (userRolesTab1.length > 0) {
            userRolesTab1.select2();
        }
        var userRolesTab2 = $(document).find('#ays-chatgpt-assistant-user-roles');
        if (userRolesTab2.length > 0) {
            userRolesTab2.select2();
        }

        $(document).find('.nav-tab-wrapper a.nav-tab').on('click', function (e) {
		    if(! $(this).hasClass('no-js')){
		        var elemenetID = $(this).attr('href');
		        var active_tab = $(this).attr('data-tab');
		        $(document).find('.nav-tab-wrapper a.nav-tab').each(function () {
		            if ($(this).hasClass('nav-tab-active')) {
		                $(this).removeClass('nav-tab-active');
		            }
		        });
		        $(this).addClass('nav-tab-active');
		        $(document).find('.ays-tab-content').each(function () {
		            $(this).css('display', 'none');
		        });
		        $(document).find("[name='ays_tab']").val(active_tab);
		        $('.ays-tab-content' + elemenetID).css('display', 'block');
		        e.preventDefault();
		    }
		});

		// Replace image to YouTube embed video
        $(document).on('click', '.ays-chatgpt-youtube-placeholder', function() {
            var videoId = $(this).data('video-id');
            var iframe = $('<iframe>', {
                src: 'https://www.youtube.com/embed/' + videoId + '?autoplay=1',
                class: '',
                height: 315,
                frameborder: 0,
                allow: 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture',
                allowfullscreen: true,
				css: {
					width: '100%',
					maxWidth: '560px',
					margin: 'auto',
					display: 'block',
				}
            });
            $(this).replaceWith(iframe);
        });

        // Toggle mobile settings start
        $(document).find('.ays_chatgpt_different_settings_for_mobile').on('change', toggleMobileSettings);
        $(document).find('.ays_chatgpt_option_for_desktop, .ays_chatgpt_option_for_mobile_device_cb').on('click', toggleMobileSettingsCb);

        function toggleMobileSettings() {
            var optionDiv = $(this).parents('.ays_chatgpt_pc_and_mobile_container');
            var deviceNames = optionDiv.find('.ays_chatgpt_current_device_name');
            var mobileOptionDiv = optionDiv.find('.ays_chatgpt_option_for_mobile_device');
            var cbLabel = optionDiv.find('.ays_chatgpt_mobile_settings_container label');

            if ($(this).prop('checked')) {
                deviceNames.addClass('show');
                mobileOptionDiv.addClass('show');
                cbLabel.addClass('active');
            } else {
                deviceNames.removeClass('show');
                mobileOptionDiv.removeClass('show');
                cbLabel.removeClass('active');
            }
        }
        
        function toggleMobileSettingsCb() {
            var mainContainer = $(this).parent();
            var desktopContainer = mainContainer.find('.ays_chatgpt_option_for_desktop');
            var mobileContainer = mainContainer.find('.ays_chatgpt_option_for_mobile_device');
            var desktopCb = desktopContainer.find('.ays-chatgpt-onoffswitch-checkbox');
            var mobileDeviceCb = mobileContainer.find('.ays-chatgpt-onoffswitch-checkbox');
            var deviceNames = mainContainer.find('.ays_chatgpt_current_device_name');
    
            if (desktopCb.is(':checked')) {
                if (!mobileContainer.hasClass('show')) {
                    mobileContainer.addClass('show');
                    mobileDeviceCb.prop('checked', true);
                    deviceNames.show().fadeIn('300');
                }
            } else {
                if (!mobileDeviceCb.is(':checked')) {
                    mobileContainer.removeClass('show');
                    deviceNames.hide().fadeOut('300');
                }
            }
        }

        // Pro features start
            $(document).find(".ays-pro-features-v2-upgrade-button").hover(function() {
                // Code to execute when the mouse enters the element
                var unlockedImg = "Unlocked_24_24.svg";
                var imgBox = $(this).find(".ays-pro-features-v2-upgrade-icon");
                var imgUrl = imgBox.attr("data-img-src");
                var newString = imgUrl.replace("Locked_24x24.svg", unlockedImg);
                
                imgBox.css("background-image", 'url(' + newString + ')');
                imgBox.attr("data-img-src", newString);
            }, function() {
                
                var lockedImg = "Locked_24x24.svg";
                var imgBox = $(this).find(".ays-pro-features-v2-upgrade-icon");
                var imgUrl = imgBox.attr("data-img-src");
                var newString = imgUrl.replace("Unlocked_24_24.svg", lockedImg);
                
                imgBox.css("background-image", 'url(' + newString + ')');
                imgBox.attr("data-img-src", newString);
            });
            
        // Pro features end

        $(document).on('change', '.ays_toggle_checkbox', function (e) {
           
            var parent = $(this).parents('.ays_toggle_parent');
            var onoffswitchCheckbox = parent.find('.ays-chatgpt-onoffswitch-checkbox');
            var state;
            
            if(onoffswitchCheckbox.length > 0){
                state = parent.find('.ays-chatgpt-onoffswitch-checkbox').is(':checked')
            }else {
                state = $(this).prop('checked');
            }

            if($(this).hasClass('ays_toggle_slide')){
                switch (state) {
                    case true:
                        parent.find('.ays_toggle_target').slideDown(250);
                        break;
                    case false:
                        parent.find('.ays_toggle_target').slideUp(250);
                        break;
                }
            }else{
                switch (state) {
                    case true:
                        parent.find('.ays_toggle_target').show(250);
                        break;
                    case false:
                        parent.find('.ays_toggle_target').hide(250);
                        break;
                }
            }
        });
      
        $(document).on("click", ".ays-select-full-width", function(e){
            var optionGemini= $(document).find('.ays-chatgpt-assistant-gemini-option');
            optionGemini.prop('disabled', true);
        });
        
        $(document).on("click", "#ays-chatgpt-dismiss-buttons-content .ays-button, #ays-chatgpt-dismiss-buttons-content-helloween .ays-button-helloween, #ays-chatgpt-dismiss-buttons-content-black-friday .ays-button-black-friday", function(e){
			e.preventDefault();
	
			var $this = $(this);
			var thisParent  = $this.parents("#ays-chatgpt-dismiss-buttons-content");
            // var thisParent  = $this.parents("#ays-chatgpt-dismiss-buttons-content-helloween");
            // var thisParent  = $this.parents("#ays-chatgpt-dismiss-buttons-content-black-friday");
			var mainParent  = $this.parents("div.ays_chatgpt_dicount_info");
			var closeButton = mainParent.find("button.notice-dismiss");
	
			var attr_plugin = $this.attr('data-plugin');
			// var wp_nonce    = thisParent.find('#ays-chatgpt-assistant-gift-banner').val();
			var wp_nonce    = thisParent.find('#ays-chatgpt-assistant-sale-banner').val();
			if(typeof wp_nonce == 'undefined'){
				wp_nonce    = $(document).find('#ays-chatgpt-assistant-sale-banner').val();
        	}
			var data = {
				action: 'ays_chatgpt_dismiss_button',
				_ajax_nonce: wp_nonce,
			};
	
			$.ajax({
				url: aysChatGptAssistantAdminSettings.ajaxUrl,
				method: 'post',
				dataType: 'json',
				data: data,
				success: function (response) {
					if( response.status ){
						closeButton.trigger('click');
					} else {
						swal.fire({
							type: 'info',
							html: "<h2>"+ aysChatGptAssistantAdminSettings.errorMsg +"</h2><br><h6>"+ aysChatGptAssistantAdminSettings.somethingWentWrong +"</h6>"
						}).then(function(res) {
							closeButton.trigger('click');
						});
					}
				},
				error: function(){
					swal.fire({
						type: 'info',
						html: "<h2>"+ aysChatGptAssistantAdminSettings.errorMsg +"</h2><br><h6>"+ aysChatGptAssistantAdminSettings.somethingWentWrong +"</h6>"
					}).then(function(res) {
						closeButton.trigger('click');
					});
				}
			});
		});

        function submitOnce(subButton){
            var subLoader = subButton.parents('div').find('.ays_chatgpt_assistant_loader_box');
            if ( subLoader.hasClass("display_none") ) {
                subLoader.removeClass("display_none");
            }
            subLoader.css({
                "padding-left": "8px",
                "display": "inline-block"
            });

            setTimeout(function() {
                $(document).find('.ays-chatgpt-assistant-loader-banner').attr('disabled', true);
            }, 10);

            setTimeout(function() {
                $(document).find('.ays-chatgpt-assistant-loader-banner').attr('disabled', false);
                subButton.parents('div').find('.ays_chatgpt_assistant_loader_box').css('display', 'none');
            }, 5000);

        }

        var checkCountdownIsExists = $(document).find('#ays-chatgpt-new-mega-bundle-dicount-month-main');
        if ( checkCountdownIsExists.length > 0 ) {
            var second  = 1000,
                minute  = second * 60,
                hour    = minute * 60,
                day     = hour * 24;

            var countdownEndTime = aysChatGptAssistantAdminSettings.chatgptBannerDate,
            // var countdownEndTime = "NOV 28, 2025 23:59:59",
            countDown = new Date(countdownEndTime).getTime(),
            x = setInterval(function() {

                var now = new Date().getTime(),
                    distance = countDown - now;

                var countDownDays    = document.getElementById("ays-chatgpt-countdown-days");
                var countDownHours   = document.getElementById("ays-chatgpt-countdown-hours");
                var countDownMinutes = document.getElementById("ays-chatgpt-countdown-minutes");
                var countDownSeconds = document.getElementById("ays-chatgpt-countdown-seconds");

                if(countDownDays !== null || countDownHours !== null || countDownMinutes !== null || countDownSeconds !== null){
                    countDownDays.innerText = Math.floor(distance / (day)),
                    countDownHours.innerText = Math.floor((distance % (day)) / (hour)),
                    countDownMinutes.innerText = Math.floor((distance % (hour)) / (minute)),
                    countDownSeconds.innerText = Math.floor((distance % (minute)) / second);

                }

                //do something later when date is reached
                if (distance < 0) {
                    var headline  = document.getElementById("ays-chatgpt-countdown-headline"),
                        countdown = document.getElementById("ays-chatgpt-countdown"),
                        content   = document.getElementById("ays-chatgpt-countdown-content");

                  // headline.innerText = "Sale is over!";
                  countdown.style.display = "none";
                  content.style.display = "block";

                  clearInterval(x);
                }
            }, 1000);
        }

        $(document).on("click", ".ays-assistant-cards-block .ays-assistant-card__footer button.status-missing", function(e){
			var $this = $(this);
			var thisParent = $this.parents(".ays-assistant-cards-block");
	
			$this.prop('disabled', true);
			$this.addClass('disabled');
	
			var loader_html = '<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>';
	
			$this.html(loader_html);
	
			var attr_plugin = $this.attr('data-plugin');
			var wp_nonce = thisParent.find('#ays_assistant_ajax_install_plugin_nonce').val();
	       
			var data = {
				action: 'ays_chatgpt_install_plugin',
				_ajax_nonce: wp_nonce,
				plugin: attr_plugin,
				type: 'plugin'
			};
			$.ajax({
				url: aysChatGptAssistantGeneral.ajaxUrl,
				method: 'post',
				dataType: 'json',
				data: data,
				success: function (response) {
					if (response.success) {
						swal.fire({
							type: 'success',
							html: "<h4>"+ response['data']['msg'] +"</h4>"
						}).then( function(res) {
							if ( $this.hasClass('status-missing') ) {
								$this.removeClass('status-missing');
							}
							$this.text(aysChatGptAssistantGeneral.activated);
							$this.addClass('status-active');
						});
					}
					else {
						swal.fire({
							type: 'info',
							html: "<h4>"+ response['data'][0]['message'] +"</h4>"
						}).then( function(res) {
							$this.text(aysChatGptAssistantGeneral.errorMsg);
						});
					}
				},
				error: function(){
					swal.fire({
						type: 'info',
						html: "<h2>"+ aysChatGptAssistantGeneral.loadResource +"</h2><br><h6>"+ aysChatGptAssistantGeneral.somethingWentWrong +"</h6>"
					}).then( function(res) {
						$this.text(aysChatGptAssistantGeneral.errorMsg);
					});
				}
			});
		});
	
		$(document).on("click", ".ays-assistant-cards-block .ays-assistant-card__footer button.status-installed", function(e){
			var $this = $(this);
			var thisParent = $this.parents(".ays-assistant-cards-block");
	
			$this.prop('disabled', true);
			$this.addClass('disabled');
	
			var loader_html = '<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>';
	
			$this.html(loader_html);
	
			var attr_plugin = $this.attr('data-plugin');
			var wp_nonce = thisParent.find('#ays_assistant_ajax_install_plugin_nonce').val();
	
			var data = {
				action: 'ays_chatgpt_activate_plugin',
				_ajax_nonce: wp_nonce,
				plugin: attr_plugin,
				type: 'plugin'
			};
	
			$.ajax({
				url: aysChatGptAssistantGeneral.ajaxUrl,
				method: 'post',
				dataType: 'json',
				data: data,
				success: function (response) {
					if( response.success ){
						swal.fire({
							type: 'success',
							html: "<h4>"+ response['data'] +"</h4>"
						}).then( function(res) {
							if ( $this.hasClass('status-installed') ) {
								$this.removeClass('status-installed');
							}
							$this.text(aysChatGptAssistantGeneral.activated);
							$this.addClass('status-active disabled');
						});
					} else {
						swal.fire({
							type: 'info',
							html: "<h4>"+ response['data'][0]['message'] +"</h4>"
						});
					}
				},
				error: function(){
					swal.fire({
						type: 'info',
						html: "<h2>"+ aysChatGptAssistantGeneral.loadResource +"</h2><br><h6>"+ aysChatGptAssistantGeneral.somethingWentWrong +"</h6>"
					}).then( function(res) {
						$this.text(aysChatGptAssistantGeneral.errorMsg);
					});;
				}
			});
		});
	});

})(jQuery);

document.addEventListener("DOMContentLoaded", function() {
    var startDate = new Date("2025-09-24");
    var endDate = new Date("2025-10-25");
    var totalLicenses = 50;
    var progressionPattern = new Array(3, 2, 1, 4, 2, 3, 1, 2, 4, 3, 2, 1, 3, 2, 4, 1, 3, 2, 2, 3, 1, 2);
    function getCurrentProgress() {
        var today = new Date();
        var daysPassed = Math.floor((today - startDate) / (1000 * 60 * 60 * 24));
        var usedLicenses = 0;
        for (var i = 0; i < Math.min(daysPassed, progressionPattern.length); i++) {
            usedLicenses += progressionPattern[i];
        }
        return Math.min(usedLicenses, totalLicenses);
    }
    function updateProgress() {
        var usedLicenses = getCurrentProgress();
        var remainingLicenses = totalLicenses - usedLicenses;
        var progressPercentage = (usedLicenses / totalLicenses) * 100;
        var remainingElement = document.getElementById("remaining-licenses");
        var progressElement = document.getElementById("progress-fill");
        if (remainingElement) remainingElement.textContent = remainingLicenses;
        if (progressElement) progressElement.style.width = progressPercentage + "%";
    }
    updateProgress();
});

// Copy to clipboard function
function chatgptCopyToClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(function() {
            chatgptShowCopyNotification(aysChatGptAssistantAdminSettings.successCopyCoupon);
        }).catch(function() {
            fallbackCopyTextToClipboard(text);
        });
    } else {
        fallbackCopyTextToClipboard(text);
    }
}

function fallbackCopyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.top = "-9999px";
    textArea.style.left = "-9999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
        var successful = document.execCommand("copy");
        if (successful) {
            chatgptShowCopyNotification(aysChatGptAssistantAdminSettings.successCopyCoupon);
        } else {
            chatgptShowCopyNotification(aysChatGptAssistantAdminSettings.failedCopyCoupon);
        }
    } catch (err) {
        chatgptShowCopyNotification(aysChatGptAssistantAdminSettings.failedCopyCoupon);
    }
    document.body.removeChild(textArea);
}

function chatgptShowCopyNotification(message) {
    var notification = document.createElement("div");
    notification.className = "ays-chatgpt-copy-notification show";
    console.log(notification);
    notification.textContent = message;
    document.body.appendChild(notification);
    setTimeout(function() {
        notification.classList.remove("show");
        setTimeout(function() {
            document.body.removeChild(notification);
        }, 300);
    }, 2000);
}
