(function($){

	"use strict";

	$( document ).ready(function() {

		/**
		* General Functions
		*/

		// Initialize SemanticUI Menu Functions

		// radio buttons
		$('.ui.checkbox').checkbox();

		// accordions
		$('.ui.accordion').not('.b2bking_settings_accordion').accordion();
		var otherSettingsAccordion = $('.b2bking_settings_accordion');
		otherSettingsAccordion.accordion({ exclusive: false });
		var settingsAccordionStorageKey = 'b2bking_settings_accordion_state_' + window.location.pathname;
		var settingsSavedNoticeKey = 'b2bking_settings_saved_notice';

		function rememberB2BKingSettingsAccordionState(){
			var state = [];

			otherSettingsAccordion.each(function(){
				var accordion = $(this);
				var openPanels = [];

				accordion.children('.title.active').each(function(){
					openPanels.push($(this).prevAll('.title').length);
				});

				state.push(openPanels);
			});

			sessionStorage.setItem(settingsAccordionStorageKey, JSON.stringify(state));
		}

		function restoreB2BKingSettingsAccordionState(){
			var state = JSON.parse(sessionStorage.getItem(settingsAccordionStorageKey) || '[]');
			if (!Array.isArray(state)){
				return;
			}

			otherSettingsAccordion.each(function(accordionIndex){
				var accordion = $(this);
				var openPanels = state[accordionIndex];

				if (!Array.isArray(openPanels)){
					return;
				}

				openPanels.forEach(function(index){
					if (accordion.children('.title').eq(index).length){
						accordion.accordion('open', index);
					}
				});
			});
		}

		function updateOtherSettingsAccordionButton(){
			var toggle = $('.b2bking_settings_accordion_toggle_all');
			var titles = otherSettingsAccordion.children('.title:visible');
			var expanded = titles.length && titles.length === titles.filter('.active').length;

			if (expanded){
				toggle.text(toggle.data('collapse-label'));
			} else {
				toggle.text(toggle.data('expand-label'));
			}
		}

		$('.b2bking_settings_accordion_toggle_all').on('click', function(){
			var titles = otherSettingsAccordion.children('.title:visible');

			if (titles.length === titles.filter('.active').length){
				titles.filter('.active').trigger('click');
			} else {
				titles.not('.active').trigger('click');
			}
		});

		otherSettingsAccordion.children('.title').on('click', function() {
			setTimeout(function(){
				updateOtherSettingsAccordionButton();
				rememberB2BKingSettingsAccordionState();
			}, 10);
		});

		restoreB2BKingSettingsAccordionState();
		updateOtherSettingsAccordionButton();

		function updateB2BKingEmailCustomEditors(){
			$('.b2bking_email_custom_toggle').each(function(){
				var enabled = $(this).is(':checked');
				var box = $(this).closest('.b2bking_email_custom_box');
				box.toggleClass('b2bking_email_custom_enabled', enabled);
				box.find('.b2bking_email_custom_content').prop('readonly', !enabled);
				var status = box.find('.b2bking_email_custom_status');
				status.text(enabled ? status.data('custom-label') : status.data('default-label'));
			});
		}

		$(document).on('change', '.b2bking_email_custom_toggle', updateB2BKingEmailCustomEditors);
		updateB2BKingEmailCustomEditors();

		$(document).on('click', '.b2bking_email_reset_default', function(){
			var textarea = $(this).closest('.b2bking_email_custom_box').find('.b2bking_email_custom_content');
			textarea.val(textarea.attr('data-default-content')).trigger('input');
		});

		$(document).on('click', '.b2bking_email_send_test', function(){
			var button = $(this);
			if (button.prop('disabled')) return;
			var emailId = button.data('email-id');
			var recipient = window.prompt(b2bking.send_test_email_prompt, b2bking.user_email || '');
			if (!recipient) return;
			button.prop('disabled', true);
			$.post(b2bking.admin_url + 'admin-ajax.php', {
				action: 'b2bking_send_test_email',
				security: b2bking.security,
				email_id: emailId,
				recipient: recipient
			}).done(function(response){
				window.alert((response && response.data && response.data.message) || b2bking.send_test_email_done);
			}).fail(function(){
				window.alert(b2bking.send_test_email_failed);
			}).always(function(){
				button.prop('disabled', false);
			});
		});

		$('.b2bking_email_title_toggle').on('mousedown mouseup', function(e){
			e.stopPropagation();
		});

		$('.b2bking_email_title_toggle').on('mousedown', function(){
			$(this).data('b2bking-was-checked', $(this).find('.b2bking_email_title_enabled').is(':checked'));
		});

		$('.b2bking_email_title_toggle').on('click', function(e){
			e.preventDefault();
			e.stopPropagation();

			var input = $(this).find('.b2bking_email_title_enabled');
			var wasChecked = $(this).data('b2bking-was-checked');
			if (typeof wasChecked === 'undefined'){
				wasChecked = input.is(':checked');
			}

			input.prop('checked', !wasChecked).trigger('change');
			return false;
		});

		$(document).on('change', '.b2bking_email_title_enabled', function(){
			var emailId = $(this).data('email-id');
			var checked = $(this).is(':checked');
			$('.b2bking_email_panel_enabled[data-email-id="' + emailId + '"]').prop('checked', checked);
		});

		$(document).on('change', '.b2bking_email_panel_enabled', function(){
			var emailId = $(this).data('email-id');
			var checked = $(this).is(':checked');
			$('.b2bking_email_title_enabled[data-email-id="' + emailId + '"]').prop('checked', checked);
		});

		//Whitelabel Logo
		$('#b2bking-logo-upload-btn-whitelabel').on('click', function(e) {
	       e.preventDefault();

	       var image = wp.media({ 
	           title: 'Upload Image',
	           multiple: false
	       }).open()
	       .on('select', function(e){
	           // This will return the selected image from the Media Uploader, the result is an object
	           var uploaded_image = image.state().get('selection').first();
	           // Convert uploaded_image to a JSON object 
	           var b2bking_image_url = uploaded_image.toJSON().url;
	           // Assign the url value to the input field
	           $('#b2bking_whitelabel_logo_setting').val(b2bking_image_url).trigger('change');
	       });
	   	});

   		//Whitelabel Icon
   		$('#b2bking-logo-upload-btn-whitelabelicon').on('click', function(e) {
   	       e.preventDefault();

   	       var image = wp.media({ 
   	           title: 'Upload Image',
   	           multiple: false
   	       }).open()
   	       .on('select', function(e){
   	           // This will return the selected image from the Media Uploader, the result is an object
   	           var uploaded_image = image.state().get('selection').first();
   	           // Convert uploaded_image to a JSON object 
   	           var b2bking_image_url = uploaded_image.toJSON().url;
   	           // Assign the url value to the input field
   	           $('#b2bking_whitelabel_icon_setting').val(b2bking_image_url).trigger('change');
   	       });
   	   	});

		// Logo Upload
		$('#b2bking-logo-upload-btn').on('click', function(e) {
	       e.preventDefault();

	       var image = wp.media({ 
	           title: 'Upload Image',
	           multiple: false
	       }).open()
	       .on('select', function(e){
	           // This will return the selected image from the Media Uploader, the result is an object
	           var uploaded_image = image.state().get('selection').first();
	           // Convert uploaded_image to a JSON object 
	           var b2bking_image_url = uploaded_image.toJSON().url;
	           // Assign the url value to the input field
	           $('#b2bking_offers_logo_setting').val(b2bking_image_url).trigger('change');
	       });
	   	});
   		// Offers IMG Upload
   		$('#b2bking-logoimg-upload-btn').on('click', function(e) {
   	       e.preventDefault();

   	       var image = wp.media({ 
   	           title: 'Upload Image',
   	           multiple: false
   	       }).open()
   	       .on('select', function(e){
   	           // This will return the selected image from the Media Uploader, the result is an object
   	           var uploaded_image = image.state().get('selection').first();
   	           // Convert uploaded_image to a JSON object 
   	           var b2bking_image_url = uploaded_image.toJSON().url;
   	           // Assign the url value to the input field
   	           $('#b2bking_offers_image_setting').val(b2bking_image_url).trigger('change');
   	       });
   	   	});
		
		// Tab transition effect
		var previous = $('.ui.tab.segment.active');
	    $(".menu .item").tab({
	        onVisible: function (e) {
	            var current = $('.ui.tab.segment.active');
	            // hide the current and show the previous, so that we can animate them
	            previous.show();
	            current.hide();

	            // hide the previous tab - once this is done, we can show the new one
	            previous.find('.b2bking_attached_content_wrapper').css('opacity','0');
	            current.find('.b2bking_attached_content_wrapper').css('opacity','0');
	            setTimeout(function(){
	            	previous.hide();
	            	current.show();
	            	setTimeout(function(){
		            	current.find('.b2bking_attached_content_wrapper').css('opacity','1');
		            	// remember the current tab for next change
		            	previous = current;
		            },10);
	            },150);
	            
	        }
	    });
	    
		$('.ui.dropdown').dropdown();
		$('.b2bking_purchase_lists_language_setting').dropdown('set selected', b2bking.purchase_lists_language_option);
	
		$('.message .close').on('click', function() {
		    $(this).closest('.message').transition('fade');
		});

		// hide or show force login
		hideShowForceLogin();

		// On Product Visibility option change, update product visibility options 
		$('input[name=b2bking_guest_access_restriction_setting]').change(function() {
			hideShowForceLogin();
		});

		// Checks the selected Product Visibility option and hides or shows Automatic / Manual visibility options
		function hideShowForceLogin(){
			let selectedValue = $("input[name=b2bking_guest_access_restriction_setting]:checked").val();
			if(selectedValue === "hide_website") {
		      	$("#b2bking_access_restriction_force_redirect").css("display","block");
		   	} else {
				$("#b2bking_access_restriction_force_redirect").css("display","none");
			}
		}

		// On Submit (Save Settings), Get Current Tab and Pass The Tab as a Setting. 
		$('#b2bking_admin_form').on('submit', function() {
			let tabInput = document.querySelector('#b2bking_current_tab_setting_input');
		    tabInput.value = document.querySelector('.item.active').dataset.tab;
		    rememberB2BKingSettingsAccordionState();
		    sessionStorage.setItem(settingsSavedNoticeKey, '1');
		    return true; 
		});

		// URL params after save or direct tab links
		const urlParams = new URLSearchParams(window.location.search);
		if ((urlParams.get('settings-updated') === 'true' || sessionStorage.getItem(settingsSavedNoticeKey) === '1') && typeof Swal !== 'undefined'){
			sessionStorage.removeItem(settingsSavedNoticeKey);
			const Toast = Swal.mixin({
			  toast: true,
			  position: 'bottom-end',
			  showConfirmButton: false,
			  timer: 1000,
			  timerProgressBar: false,
			  customClass: {
			    title: 'b2bking_settings_saved_swal_title'
			  },
			  didOpen: (toast) => {
			    toast.addEventListener('mouseenter', Swal.stopTimer)
			    toast.addEventListener('mouseleave', Swal.resumeTimer)
			  }
			})

			Toast.fire({
			  icon: 'success',
			  title: b2bking.settings_saved
			});
		}

		const myParam = urlParams.get('tab');
		if (myParam === 'activate'){
			$('.b2bking_license').click();
		} else if (myParam === 'main'){
			$('#b2bking_admin_menu .item[data-tab="mainsettings"]').click();
		}

		function showHideCreamSetting(){
			let setting = $('#b2bking_order_form_theme_setting_select').val();
			if (setting === 'cream'){
				$('#b2bking_order_form_creme_cart_button_setting_select').parent().parent().css('display','table-row');
				$('#b2bking_order_form_cream_multiselect_container').parent().parent().css('display','table-row');
			} else {
				$('#b2bking_order_form_creme_cart_button_setting_select').parent().parent().css('display','none');
				$('#b2bking_order_form_cream_multiselect_container').parent().parent().css('display','none');
			}

			if (setting === 'cream' || setting === 'indigo'){
				$('#b2bking_order_form_sortby_setting_select').parent().parent().css('display','table-row');
			} else {
				$('#b2bking_order_form_sortby_setting_select').parent().parent().css('display','none');
			}
		}

		showHideCreamSetting();
		$('#b2bking_order_form_theme_setting_select').on('change', showHideCreamSetting);


		function showHideVisibilitySettings(){
			let selectedValue = jQuery("input[name=b2bking_all_products_visible_all_users_setting]").is(':checked');
			var advancedTitle = otherSettingsAccordion.children('.title.b2bking_advanced_visibility');
			var advancedContent = otherSettingsAccordion.children('.content.b2bking_advanced_visibility');
			if(selectedValue) {
		      	$("input[name=b2bking_hidden_has_priority_setting], input[name=b2bking_product_visibility_cache_setting]").parent().parent().parent().hide();
		      	$('.b2bking_visibility_instructions_message').hide();
		      	advancedTitle.removeClass('active').hide();
		      	advancedContent.removeClass('active').hide();

		   	} else {
		   		$("input[name=b2bking_hidden_has_priority_setting], input[name=b2bking_product_visibility_cache_setting]").parent().parent().parent().show();
		   		$('.b2bking_visibility_instructions_message').show();
		   		advancedTitle.show();
		   		advancedContent.hide();
			}
			updateOtherSettingsAccordionButton();
		}
		showHideVisibilitySettings();
		updateOtherSettingsAccordionButton();
		$('input[name=b2bking_all_products_visible_all_users_setting]').on('change', showHideVisibilitySettings);

		function showHideTurnstileFields(){
			let selectedValue = $('#b2bking_captcha_provider_setting_select').val();
			if (selectedValue === 'cloudflare'){
				$('#b2bking_captcha_cloudflare_fields').removeClass('b2bking_hidden');
			} else {
				$('#b2bking_captcha_cloudflare_fields').addClass('b2bking_hidden');
			}
		}
		showHideTurnstileFields();
		$('#b2bking_captcha_provider_setting_select').on('change', showHideTurnstileFields);


		// Settings search
		(function(){
			var searchInput = $('#b2bking_settings_search');
			var lastFocusedElement = null;

			if (!searchInput.length){
				return;
			}

			function normalizeText(text){
				return $.trim(String(text || '').toLowerCase().replace(/\s+/g, ' '));
			}

			function getSearchText($element){
				var text = $element.text() || '';
				$element.find('[data-tip]').each(function(){
					text += ' ' + ($(this).attr('data-tip') || '');
				});
				return normalizeText(text);
			}

				function getSearchTargets(){
					var targets = [];

					$('#b2bking_tabs_wrapper .ui.tab.segment').each(function(){
						var $tab = $(this);

					$tab.find('table.form-table tr').each(function(){
						targets.push({
							$element: $(this),
							$tab: $tab
						});
					});

					$tab.find('.ui.large.form.b2bking_plugin_status_container').each(function(){
						targets.push({
							$element: $(this),
							$tab: $tab
						});
					});

						$tab.find('.b2bking_settings_accordion > .title').each(function(){
							targets.push({
								$element: $(this),
								$tab: $tab
							});
						});

						$tab.find('.b2bking_color_design_intro, .b2bking_color_design_group_header, .b2bking_color_design_row').each(function(){
							targets.push({
								$element: $(this),
								$tab: $tab
							});
						});
					});

					return targets;
				}

			function clearHighlights(){
				$('.b2bking_settings_search_match').removeClass('b2bking_settings_search_match');
				$('.b2bking_menu_item_search_match').removeClass('b2bking_menu_item_search_match');
			}

			function focusFirstMatch(firstMatch){
				var $tab = firstMatch.$tab;
				var tabName = $tab.data('tab');
				var $menuItem = $('#b2bking_admin_menu .item[data-tab="' + tabName + '"]');
				var $element = firstMatch.$element;
				var $accordionTitle = $element.hasClass('title') ? $element : $element.closest('.b2bking_settings_accordion > .content').prev('.title');

				if ($menuItem.length){
					$menuItem.trigger('click');
				}

				setTimeout(function(){
					if ($tab.data('tab') === 'othersettings' && $accordionTitle.length){
						otherSettingsAccordion.children('.title.active').not($accordionTitle).trigger('click');
						if (!$accordionTitle.hasClass('active')){
							$accordionTitle.trigger('click');
						}
						updateOtherSettingsAccordionButton();
					}

					if ($element.length){
						$element[0].scrollIntoView({
							behavior: 'smooth',
							block: 'center'
						});
					}
				}, 190);
			}

				function applySearch(term){
					var normalizedTerm = normalizeText(term);
					var targets;
					var matches = [];
					var tabsWithMatches = {};

						clearHighlights();

						if (normalizedTerm.length < 3){
							lastFocusedElement = null;
							return;
						}

					targets = getSearchTargets();

						targets.forEach(function(target){
							var $accordionTitle;

							if (getSearchText(target.$element).indexOf(normalizedTerm) === -1){
							return;
						}

						target.$element.addClass('b2bking_settings_search_match');
						$accordionTitle = target.$element.hasClass('title') ? target.$element : target.$element.closest('.b2bking_settings_accordion > .content').prev('.title');
						if ($accordionTitle.length){
							$accordionTitle.addClass('b2bking_settings_search_match');
						}
						matches.push(target);

						if (target.$tab && target.$tab.length){
							tabsWithMatches[target.$tab.data('tab')] = true;
						}
				});

				Object.keys(tabsWithMatches).forEach(function(tabName){
						$('#b2bking_admin_menu .item[data-tab="' + tabName + '"]').addClass('b2bking_menu_item_search_match');
					});

					if (matches.length){
						if (lastFocusedElement !== matches[0].$element[0]){
							focusFirstMatch(matches[0]);
							lastFocusedElement = matches[0].$element[0];
						}
					} else {
						lastFocusedElement = null;
					}
				}

			searchInput.on('keydown', function(e){
				if (e.key === 'Enter'){
					e.preventDefault();
				}
			});

			searchInput.on('input', function(){
				applySearch($(this).val());
			});
		})();



		// settings block
		jQuery('.b2bking_setting_block').on('click', function(){
			var val = $(this).attr('data-value');
			var setting = $(this).attr('data-setting');
			jQuery('#'+setting).val(val).trigger('change');

			if (val === 'enabled'){
				var check = true;
			} else {
				var check = false;
			}

			jQuery('input[name="'+setting+'"]').prop('checked', check).trigger('change');

			jQuery(this).addClass('active');
			$('.b2bking_setting_block').each(function(i){
				if ($(this).attr('data-setting') === setting){
					if ($(this).attr('data-value') !== val){
						$(this).removeClass('active');
					}
				}
			});
		});

		// if user switches from B2B to b2b/b2c hybrid, set guest access restricrtion to "none"
		$('input[name="b2bking_plugin_status_setting"]').change(function() {
	        // Check if the selected radio button has the value "hybrid"
	        if ($(this).val() === "hybrid") {
	            // Set the radio input with the name "b2bking_guest_access_restriction_setting" to "none"
	            $('input[name="b2bking_guest_access_restriction_setting"][value="none"]').prop('checked', true);
	        }
	    });

		// existing users apply wanring, move first
		jQuery('input[name="b2bking_registration_loggedin_setting"]').parent().parent().parent().after('<tr><td colspan="2" id="b2bking_existing_users_apply_warning_row"></td></tr>');
		jQuery('#b2bking_existing_users_apply_warning_row').append(jQuery('.b2bking_existing_users_apply_warning').detach());
		
		function showHideExistingWarning(){
			let selectedValue = jQuery("input[name=b2bking_registration_loggedin_setting]").is(':checked');
			if(selectedValue) {
		      	$('#b2bking_existing_users_apply_warning_row, .b2bking_existing_users_apply_warning').show();
		   	} else {
		      	$('#b2bking_existing_users_apply_warning_row, .b2bking_existing_users_apply_warning').hide();
			}
		}
		showHideExistingWarning();
		$('input[name=b2bking_registration_loggedin_setting]').on('change', showHideExistingWarning);


	});

})(jQuery);
