'use strict';
document.addEventListener( 'DOMContentLoaded', ( event ) => {
	/*Welcome page FAQ*/
	var nxtPanelFaq = document.querySelectorAll(
		'.nxt-welcome-faq .nxt-faq-section .faq-title'
	);
	if ( nxtPanelFaq ) {
		nxtPanelFaq.forEach( function ( ele ) {
			ele.addEventListener( 'click', ( event ) => {
				event.preventDefault();
				var faqSec = event.currentTarget.nextElementSibling;
				if ( ! faqSec.classList.contains( 'active' ) ) {
					event.currentTarget.parentElement.classList.add(
						'faq-active'
					);
					faqSec.classList.add( 'active' );
					faqSec.style.height = 'auto';

					var height = faqSec.clientHeight + 'px';
					faqSec.style.height = '0px';
					setTimeout( function () {
						faqSec.style.height = height;
					}, 0 );
				} else {
					faqSec.style.height = '0px';
					faqSec.addEventListener(
						'transitionend',
						function () {
							faqSec.parentElement.classList.remove(
								'faq-active'
							);
							faqSec.classList.remove( 'active' );
						},
						{
							once: true,
						}
					);
				}
			} );
		} );
	}
	/*Welcome page FAQ*/
	/*welcome support*/
	var nxtSupport = document.querySelector( '.nxt-welcome-support-toggle' );
	if ( nxtSupport ) {
		nxtSupport.addEventListener( 'click', ( event ) => {
			event.preventDefault();
			var supportContent = document.querySelector(
				'.nxt-welcome-support-content'
			);
			if (
				supportContent &&
				! supportContent.classList.contains( 'active-sup' )
			) {
				supportContent.classList.add( 'active-sup' );
				nxtSupport.classList.add( 'active-toggle' );
				nxtSupport.innerHTML =
					'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M315.3 411.3c-6.253 6.253-16.37 6.253-22.63 0L160 278.6l-132.7 132.7c-6.253 6.253-16.37 6.253-22.63 0c-6.253-6.253-6.253-16.37 0-22.63L137.4 256L4.69 123.3c-6.253-6.253-6.253-16.37 0-22.63c6.253-6.253 16.37-6.253 22.63 0L160 233.4l132.7-132.7c6.253-6.253 16.37-6.253 22.63 0c6.253 6.253 6.253 16.37 0 22.63L182.6 256l132.7 132.7C321.6 394.9 321.6 405.1 315.3 411.3z"/></svg>';
			} else {
				supportContent.classList.remove( 'active-sup' );
				nxtSupport.classList.remove( 'active-toggle' );
				nxtSupport.innerHTML =
					'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M202.021 0C122.202 0 70.503 32.703 29.914 91.026c-7.363 10.58-5.093 25.086 5.178 32.874l43.138 32.709c10.373 7.865 25.132 6.026 33.253-4.148 25.049-31.381 43.63-49.449 82.757-49.449 30.764 0 68.816 19.799 68.816 49.631 0 22.552-18.617 34.134-48.993 51.164-35.423 19.86-82.299 44.576-82.299 106.405V320c0 13.255 10.745 24 24 24h72.471c13.255 0 24-10.745 24-24v-5.773c0-42.86 125.268-44.645 125.268-160.627C377.504 66.256 286.902 0 202.021 0zM192 373.459c-38.196 0-69.271 31.075-69.271 69.271 0 38.195 31.075 69.27 69.271 69.27s69.271-31.075 69.271-69.271-31.075-69.27-69.271-69.27z"></path></svg>';
			}
		} );
	}
	/*welcome support*/
	/*welcome Stay Updated*/
	var nxtSendEmail = document.querySelector( '.nxt-send-email-update' );
	if ( nxtSendEmail ) {
		var error_notice_Icon =
			'<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="16" r="15.75" stroke="#FC4032" stroke-width="0.5"/><circle cx="16" cy="16" r="12" fill="#FC4032"/><rect x="15" y="9" width="2" height="10" rx="1" fill="white"/><rect x="15" y="20" width="2" height="2" rx="1" fill="white"/></svg>';
		nxtSendEmail.addEventListener( 'click', ( event ) => {
			event.preventDefault();
			var nxtEmail = document.querySelector( '#stay-update-email' );
			if ( nxtEmail && nxtEmail.value != '' ) {
				const validateEmail = ( email ) => {
					return email.match(
						/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
					);
				};
				if ( validateEmail( nxtEmail.value ) ) {
					const webhookBody = {
						email: nxtEmail.value,
					};
					const welcomeEmailUrl =
						'https://store.posimyth.com/wp-admin/?fluentcrm=1&route=contact&hash=f415f1ff-50d7-4783-9e86-66f96e75c495';
					const response = fetch( welcomeEmailUrl, {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'Access-Control-Allow-Origin': 'http://localhost/',
						},
						mode: 'no-cors',
						body: JSON.stringify( webhookBody ),
					} ).then( ( response ) => {
						if ( response.ok ) {
							var wrong_ID_msg =
								'<div class="nxt-wrong-msg-notice"><svg xmlns="http://www.w3.org/2000/svg" width="22" height="16" fill="none"><path d="M2.297 9.135L7.162 14l12-12" stroke="#14c38e" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path></svg> Successfully send mail.</div>';
							var mailSel = document.querySelector(
								'.nxt-welcome-stay-update'
							);
							nxt_message_notice( wrong_ID_msg, mailSel, true );
						} else {
							var wrong_ID_msg =
								'<div class="nxt-wrong-msg-notice">' +
								error_notice_Icon +
								' There was an error! Try again later!</div>';
							var mailSel = document.querySelector(
								'.nxt-welcome-stay-update'
							);
							nxt_message_notice( wrong_ID_msg, mailSel );
						}
					} );
				} else {
					var wrong_ID_msg =
						'<div class="nxt-wrong-msg-notice">' +
						error_notice_Icon +
						' Please Check Email ID</div>';
					var mailSel = document.querySelector(
						'.nxt-welcome-stay-update'
					);
					nxt_message_notice( wrong_ID_msg, mailSel );
				}
			} else {
				var wrong_ID_msg =
					'<div class="nxt-wrong-msg-notice">' +
					error_notice_Icon +
					' Please Enter Email Id</div>';
				var mailSel = document.querySelector(
					'.nxt-welcome-stay-update'
				);
				nxt_message_notice( wrong_ID_msg, mailSel );
			}
		} );
	}

	/*welcome Stay Updated*/

	function nxt_message_notice( msg = '', wrapSel ) {
		if ( msg && wrapSel ) {
			if ( wrapSel ) {
				wrapSel.insertAdjacentHTML( 'beforeend', msg );
				var notice_data = wrapSel.querySelector(
					'.nxt-wrong-msg-notice'
				);
				if ( notice_data ) {
					setTimeout( function () {
						notice_data.classList.add( 'active-notice' );
					}, 50 );
					setTimeout( function () {
						notice_data.remove();
					}, 3000 );
				}
			}
		}
	}

	/*welcome sys req copy*/
	var nxtCopy = document.querySelector(
		'.sys-copy-download-btn .nxt-copy-btn'
	);
	if ( nxtCopy ) {
		nxtCopy.addEventListener( 'click', ( event ) => {
			event.preventDefault();
			var copyText = nxtCopy.parentElement.getAttribute(
				'data-clipboard-text'
			);
			var textArea = document.createElement( 'textarea' );
			textArea.value = copyText;
			textArea.style.opacity = 0;
			textArea.style.width = 0;
			textArea.style.height = 0;
			document.body.appendChild( textArea );
			textArea.select();
			try {
				var successful = document.execCommand( 'copy' );
				if ( successful ) {
					nxtCopy.innerHTML = 'Copied';
					setTimeout( () => {
						nxtCopy.innerHTML = 'Copy Info';
					}, 2000 );
				} else {
				}
			} catch ( err ) {
				console.log( 'Oops, unable to copy' );
			}
			document.body.removeChild( textArea );
		} );
	}
	var nxtDownload = document.querySelector(
		'.sys-copy-download-btn .nxt-download-btn'
	);
	if ( nxtDownload ) {
		nxtDownload.addEventListener( 'click', ( event ) => {
			event.preventDefault();
			var copyText = nxtDownload.parentElement.getAttribute(
				'data-clipboard-text'
			);
			var filename = 'nexter-system-info.txt';
			nxt_Download( filename, copyText );
		} );
	}

	function nxt_Download( filename, text ) {
		var element = document.createElement( 'a' );
		element.setAttribute(
			'href',
			'data:text/plain;charset=utf-8,' + encodeURIComponent( text )
		);
		element.setAttribute( 'download', filename );

		element.style.display = 'none';
		document.body.appendChild( element );

		element.click();

		document.body.removeChild( element );
	}

	/*welcome sys req copy*/
	/* Extra Option */
	document.addEventListener( 'click', ( e ) => {
		const isSupTop = e.target.closest( '.nxt-sup-top' );
		const isSupInner = e.target.closest( '.nxt-support-inner' );
		const isSupBottom = e.target.closest( '.nxt-support-bottom' );
		const isSupToggleClosest = e.target.closest(
			'.nxt-welcome-support-toggle'
		);
		if (
			! isSupTop &&
			! isSupInner &&
			! isSupBottom &&
			! isSupToggleClosest &&
			e.target.nodeName != 'path' &&
			e.target.nodeName != 'svg'
		) {
			const supToggle = document.querySelector(
				'.nxt-welcome-support-toggle'
			);
			const supportContent = document.querySelector(
				'.nxt-welcome-support-content'
			);
			if (
				supToggle &&
				supToggle.classList.contains( 'active-toggle' )
			) {
				supportContent.classList.remove( 'active-sup' );
				supToggle.classList.remove( 'active-toggle' );
				supToggle.innerHTML =
					'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M202.021 0C122.202 0 70.503 32.703 29.914 91.026c-7.363 10.58-5.093 25.086 5.178 32.874l43.138 32.709c10.373 7.865 25.132 6.026 33.253-4.148 25.049-31.381 43.63-49.449 82.757-49.449 30.764 0 68.816 19.799 68.816 49.631 0 22.552-18.617 34.134-48.993 51.164-35.423 19.86-82.299 44.576-82.299 106.405V320c0 13.255 10.745 24 24 24h72.471c13.255 0 24-10.745 24-24v-5.773c0-42.86 125.268-44.645 125.268-160.627C377.504 66.256 286.902 0 202.021 0zM192 373.459c-38.196 0-69.271 31.075-69.271 69.271 0 38.195 31.075 69.27 69.271 69.27s69.271-31.075 69.271-69.271-31.075-69.27-69.271-69.27z"></path></svg>';
			}
		}
	} );
	document.addEventListener( 'keydown', ( e ) => {
		if ( e.keyCode == 27 ) {
			var pop = document.querySelector( '.nxt-ext-setting-pop' );
			if ( pop ) {
				pop.remove();
			}
			const supToggle = document.querySelector(
				'.nxt-welcome-support-toggle'
			);
			const supportContent = document.querySelector(
				'.nxt-welcome-support-content'
			);
			if (
				supToggle &&
				supToggle.classList.contains( 'active-toggle' )
			) {
				supportContent.classList.remove( 'active-sup' );
				supToggle.classList.remove( 'active-toggle' );
				supToggle.innerHTML =
					'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M202.021 0C122.202 0 70.503 32.703 29.914 91.026c-7.363 10.58-5.093 25.086 5.178 32.874l43.138 32.709c10.373 7.865 25.132 6.026 33.253-4.148 25.049-31.381 43.63-49.449 82.757-49.449 30.764 0 68.816 19.799 68.816 49.631 0 22.552-18.617 34.134-48.993 51.164-35.423 19.86-82.299 44.576-82.299 106.405V320c0 13.255 10.745 24 24 24h72.471c13.255 0 24-10.745 24-24v-5.773c0-42.86 125.268-44.645 125.268-160.627C377.504 66.256 286.902 0 202.021 0zM192 373.459c-38.196 0-69.271 31.075-69.271 69.271 0 38.195 31.075 69.27 69.271 69.27s69.271-31.075 69.271-69.271-31.075-69.27-69.271-69.27z"></path></svg>';
			}
		}
	} );

	/* Extra Option */
	/*Import Data*/
	nexterInstallBuilder();

	function nexterInstallBuilder() {
		/*Install Plugin Builder Event*/
		var nxtPanelInstallBuilderBtn = document.querySelectorAll(
			'.nxt-import-data-content .nxt-install-builder-plugin'
		);
		if ( nxtPanelInstallBuilderBtn ) {
			nxtPanelInstallBuilderBtn.forEach( function ( ele ) {
				ele.addEventListener( 'click', ( event ) => {
					event.preventDefault();
					var builderSlug = ele.dataset.slug;
					ele.innerHTML = ele.dataset.builderProcess;
					/*Wp Install Plugin Event*/
					wp.updates.installPlugin( {
						slug: builderSlug,
					} );
				} );
			} );

			/*Wp Install Success trigger Message*/
			jQuery( document ).on(
				'wp-plugin-install-success',
				( event, response ) => {
					if ( response ) {
						var builderSlug = response.slug ? response.slug : '';
						var installedBuilder = document.querySelector(
							'.nxt-import-data-content .nxt-install-builder-plugin[data-slug=' +
								builderSlug +
								']'
						);
						if ( installedBuilder ) {
							var file = installedBuilder.dataset.file;
							setTimeout( function () {
								var request = new XMLHttpRequest();

								request.open(
									'POST',
									nexter_admin_config.ajaxurl,
									true
								);
								request.setRequestHeader(
									'Content-Type',
									'application/x-www-form-urlencoded;'
								);
								request.onload = function () {
									if (
										request.status >= 200 &&
										request.status < 400
									) {
										var response = JSON.parse(
											request.response
										);
										if (
											response.data.success == true &&
											response.data.content != ''
										) {
											installedBuilder.innerHTML =
												response.data.content;
											if ( nxtPanelImportBtn ) {
												nxtPanelImportBtn.setAttribute(
													'data-step',
													'step-3'
												);
											}
										} else {
											installedBuilder.innerHTML =
												response.data.content;
										}
									}
								};
								installedBuilder.innerHTML = 'Activating..';
								request.send(
									'action=nexter_import_activate_builder&nexter_nonce=' +
										nexter_admin_config.ajax_nonce +
										'&file=' +
										file
								);
							}, 1200 );
						}
					}
				}
			);

			/*Wp Install Error trigger Message*/
			jQuery( document ).on(
				'wp-plugin-install-error',
				( event, response ) => {
					var installedBuilder = document.querySelector(
						'.nxt-import-data-content .nxt-install-builder-plugin'
					);
					if ( installedBuilder ) {
						installedBuilder.innerHTML =
							wp.updates.l10n.installFailedShort;
					}
				}
			);
		}

		/*Activate Plugin Builder Event*/
		var nxtActiveBuilderBtn = document.querySelectorAll(
			'.nxt-import-data-content .nxt-active-builder-plugin'
		);
		if ( nxtActiveBuilderBtn ) {
			nxtActiveBuilderBtn.forEach( function ( ele ) {
				ele.addEventListener( 'click', ( event ) => {
					event.preventDefault();

					var builder = ele.dataset.builder,
						processText = ele.dataset.builderProcess,
						file = ele.dataset.file;

					if ( builder != '' && ele.innerHTML != 'Activated' ) {
						var request = new XMLHttpRequest();

						request.open(
							'POST',
							nexter_admin_config.ajaxurl,
							true
						);
						request.setRequestHeader(
							'Content-Type',
							'application/x-www-form-urlencoded;'
						);
						request.onload = function () {
							if (
								request.status >= 200 &&
								request.status < 400
							) {
								var response = JSON.parse( request.response );
								if (
									response.data.success == true &&
									response.data.content != ''
								) {
									ele.innerHTML = response.data.content;
									ele.classList.remove(
										'nxt-active-builder-plugin'
									);
									ele.classList.add(
										'nxt-activated-builder-plugin'
									);
									if ( nxtPanelImportBtn ) {
										nxtPanelImportBtn.setAttribute(
											'data-step',
											'step-3'
										);
									}
								} else {
									ele.innerHTML = response.data.content;
								}
							}
						};

						ele.innerHTML = processText;
						request.send(
							'action=nexter_import_activate_builder&nexter_nonce=' +
								nexter_admin_config.ajax_nonce +
								'&builder=' +
								builder +
								'&file=' +
								file
						);
					}
				} );
			} );
		}
	}

	/*Import Data*/
	/* White Label Start */
	let wlMain = document.querySelector( '.nxt-white-label' );

	if ( wlMain ) {
		let saveFile = [ 'theme_screenshot', 'theme_logo' ];
		saveFile.forEach( function ( sf ) {
			let mainF = wlMain.querySelector( '.' + sf );
			let fileUp = mainF.querySelector( '.nxt-wl-save-file' );
			var sBtn = mainF.querySelector( '.nxt-wl-save-file' ),
				removeBtn = mainF.querySelector( '.nxt-wl-remove-file' ),
				fileN = mainF.querySelector( '.nxt-wl-file-name' );
			if ( removeBtn ) {
				removeBtn.addEventListener( 'click', ( rem ) => {
					fileN.innerHTML = 'Drag & Drop your file here';
					sBtn.value = '';
					sBtn.innerHTML = 'Browse';
					sBtn.dataset.src = '';
					rem.currentTarget.classList.remove( 'active' );
				} );
			}

			fileUp.addEventListener( 'click', ( e ) => {
				var button = e.currentTarget,
					custom_uploader = wp
						.media( {
							title: 'Insert image',
							library: {
								type: 'image',
							},
							multiple: false,
						} )
						.on( 'select', function () {
							var attachment = custom_uploader
								.state()
								.get( 'selection' )
								.first()
								.toJSON();
							button.value = attachment.id;
							button.dataset.src = attachment.url;
							button.innerHTML = 'Change';
							if ( fileN ) {
								fileN.innerHTML = attachment.filename;
							}
							removeBtn.classList.add( 'active' );
						} )
						.open();
			} );
		} );

		let saveBtn = wlMain.querySelector( '.nxt-wl-save-btn' );

		saveBtn.addEventListener( 'click', ( s ) => {
			let wpWLSet = {};
			let allWlOp = [
				'brand_name',
				'theme_name',
				'theme_desc',
				'author_name',
				'author_uri',
				'theme_screenshot',
				'theme_logo',
				'nxt_free_plugin_name',
				'nxt_pro_plugin_name',
				'nxt_free_plugin_desc',
				'nxt_pro_plugin_desc',
			];
			var arrWlValue = [];
			var validation = true;
			allWlOp.forEach( function ( all ) {
				let allInput = wlMain.querySelector( '.' + all + ' input' ),
					allTextArea = wlMain.querySelector(
						'.' + all + ' textarea'
					),
					allLabel = wlMain.querySelector( '.' + all + ' label' );

				if ( allInput && allInput.value ) {
					arrWlValue[ all ] = allInput.value;
					var regexp =
						/^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
					if (
						all == 'author_uri' &&
						! regexp.test( allInput.value )
					) {
						validation = false;
						delete arrWlValue[ all ];
					}
				}
				if ( allTextArea && allTextArea.value ) {
					arrWlValue[ all ] = allTextArea.value;
				}
				if ( allLabel ) {
					let fileBtn = allLabel.querySelector( '.nxt-wl-save-file' ),
						file_id = all + '_id';
					if ( fileBtn.value ) {
						arrWlValue[ all ] = fileBtn.getAttribute( 'data-src' );
						arrWlValue[ file_id ] = fileBtn.value;
					}
				}
			} );

			arrWlValue = Object.assign( {}, arrWlValue );

			let twoForce = wlMain.querySelector( '#nxt-wl-two-force' );
			if ( twoForce && twoForce.checked ) {
				arrWlValue = Object.assign(
					{ nxt_hidden_label: 'on' },
					arrWlValue
				);
			}
			wpWLSet = Object.assign( arrWlValue, wpWLSet );
			var wpWLSetN = JSON.stringify( wpWLSet );
			if ( validation ) {
				var request = new XMLHttpRequest();
				request.open( 'POST', nexter_admin_config.ajaxurl, true );
				request.setRequestHeader(
					'Content-Type',
					'application/x-www-form-urlencoded;'
				);
				saveBtn.innerHTML = 'Saving...';
				request.onload = function () {
					if ( request.status >= 200 && request.status < 400 ) {
						var response = JSON.parse( request.response );
						if ( response.success == true ) {
							saveBtn.innerHTML = 'Saved';
							setTimeout( function () {
								saveBtn.innerHTML =
									'<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="#fff" stroke-width=".781" stroke-linejoin="round" xmlns:v="https://vecta.io/nano"><path d="M15.833 17.5H4.167c-.442 0-.866-.176-1.179-.488s-.488-.736-.488-1.179V4.167c0-.442.176-.866.488-1.179S3.725 2.5 4.167 2.5h9.167L17.5 6.667v9.167c0 .442-.176.866-.488 1.179s-.736.488-1.179.488z"/><path d="M14.167 17.5v-6.667H5.833V17.5m0-15v4.167H12.5" stroke-linecap="round"/></svg>Save';
							}, 2000 );
						}
					}
				};
				request.send(
					'action=nexter_ext_save_data&nexter_nonce=' +
						nexter_admin_config.ajax_nonce +
						'&wpWLSet=' +
						wpWLSetN +
						'&extension_type=white-label'
				);
			} else {
				var wrong_ID_msg =
					'<div class="nxt-wrong-msg-notice"><svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="16" r="15.75" stroke="#FC4032" stroke-width="0.5"/><circle cx="16" cy="16" r="12" fill="#FC4032"/><rect x="15" y="9" width="2" height="10" rx="1" fill="white"/><rect x="15" y="20" width="2" height="2" rx="1" fill="white"/></svg> Website URL not a valid</div>';
				var WLSel = document.querySelector( '.nxt-white-label' );
				if ( WLSel ) {
					WLSel.insertAdjacentHTML( 'beforeend', wrong_ID_msg );
					var notice_data = WLSel.querySelector(
						'.nxt-wrong-msg-notice'
					);
					if ( notice_data ) {
						setTimeout( function () {
							notice_data.classList.add( 'active-notice' );
						}, 50 );
						setTimeout( function () {
							notice_data.remove();
						}, 3000 );
					}
				}
			}
		} );
	}
	/* White Label End */
} );
