jQuery( document ).ready( function ( $ ) {
	// IP validation and search during typing
	$( 'input.search-ip-input' ).keyup( function () {
		const $this = $( this );
		const ip = $( this ).val();
		const redirect = $( this ).data( 'redirect' ) || window.location.href; // Fallback to current page

		// Clear previous results
		$this.next( '.validation-result' ).html( '' );
		$this.siblings( '.recent-ips-search' ).hide().html( '' );

		if ( ip.length === 0 ) {
			return;
		}

		// Search recent IPs if input length is >= 1
		if ( ip.length >= 1 ) {
			searchRecentIPs( ip, redirect, $this );
		}

		// Only validate if IP is at least 7 characters (minimum valid IP like 1.1.1.1)
		if ( ip.length >= 7 ) {
			const dataJSON = {
				action: 'ultimate_security_ip_validate',
				ip,
				security: ultimate_security_ajax_obj.security,
			};
			$.ajax( {
				cache: false,
				type: 'POST',
				url: ultimate_security_ajax_obj.ajax_url,
				data: dataJSON,
				success( response ) {
					if ( response.success ) {
						$this
							.next( '.validation-result' )
							.html(
								'<div class="valid-ip">' +
									response.data.message +
									' <button class="use-this-ip" data-ip="' +
									ip +
									'" data-redirect="' +
									redirect +
									'">Switch</button></div>'
							);
					} else {
						$this
							.next( '.validation-result' )
							.html( '<div class="invalid-ip">' + response.data.message + '</div>' );
					}
				},
				error( xhr, status, error ) {
					// console.log("Status: " + xhr.status);
					// console.log("Error: " + xhr.responseText);
				},
			} );
		}
	} );

	// Function to search recent IPs
	function searchRecentIPs( searchTerm, redirectUrl, $inputElement ) {
		const dataJSON = {
			action: 'ultimate_security_search_recent_ips',
			search_term: searchTerm,
			redirect_url: redirectUrl,
			security: ultimate_security_ajax_obj.security,
		};

		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			success( response ) {
				if ( response.success && response.data.count > 0 ) {
					$inputElement
						.siblings( '.recent-ips-search' )
						.html( response.data.html )
						.show();
				} else {
					$inputElement.siblings( '.recent-ips-search' ).hide().html( '' );
				}
			},
			error( xhr, status, error ) {
				// console.log("Search Error - Status: " + xhr.status);
				// console.log("Search Error: " + xhr.responseText);
			},
		} );
	}

	// Handle clicking on searched IP option
	$( 'body' ).on( 'click', '.ip-option', function ( e ) {
		e.preventDefault();
		const ip = $( this ).data( 'ip' );
		const redirect = $( this ).data( 'redirect' ) || window.location.href;
		setIP( ip, redirect );
	} );

	// Handle clicking on the "use this IP" button
	$( 'body' ).on( 'click', '.use-this-ip', function ( e ) {
		e.preventDefault();
		const ip = $( this ).data( 'ip' );
		const redirect = $( this ).data( 'redirect' ) || window.location.href;
		setIP( ip, redirect );
	} );

	// Handle clicking on recent IP (both admin bar and frontend)
	$( 'body' ).on( 'click', '.ultimate-security-change-ip', function ( e ) {
		e.preventDefault();
		const ip = $( this ).data( 'ip' );
		let redirect = $( this ).data( 'redirect' );

		// Fallback redirect logic
		if ( ! redirect ) {
			if ( window.location.pathname.indexOf( '/wp-admin/' ) !== -1 ) {
				redirect = ultimate_security_ajax_obj.home_url || window.location.origin;
			} else {
				redirect = window.location.href;
			}
		}

		setIP( ip, redirect );
	} );

	// Function to set IP
	function setIP( ip, redirect ) {
		// Validate redirect URL
		if ( ! redirect || redirect === 'undefined' ) {
			if ( window.location.pathname.indexOf( '/wp-admin/' ) !== -1 ) {
				redirect = ultimate_security_ajax_obj.home_url || window.location.origin;
			} else {
				redirect = window.location.href;
			}
		}

		const dataJSON = {
			action: 'ultimate_security_ip_set',
			security: ultimate_security_ajax_obj.security,
			ip,
		};

		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			success( response ) {
				if ( response.success ) {
					// console.log("Redirecting to: " + redirect); // Debug log
					window.location.href = redirect;
				} else {
					// console.log("IP set failed:", response);
				}
			},
			error( xhr, status, error ) {
				// console.log("Status: " + xhr.status);
				// console.log("Error: " + xhr.responseText);
			},
		} );
	}

	// Switch back to admin
	$( '.ultimate-security-switch-to-main' )
		.find( 'a' )
		.on( 'click', function ( e ) {
			e.preventDefault();
			const redirect = $( this ).data( 'redirect' ) || ultimate_security_ajax_obj.admin_url;
			setCookie( 'ultimate_security_debug_ip', '', 0 );
			setCookie( 'ultimate_security_show_notice', 1, 1 );
			window.location.href = redirect;
		} );

	// Notice dismiss
	$( '.ultimate-security-switch-notice' )
		.find( '.notice-dismiss' )
		.on( 'click', function ( e ) {
			$( this ).closest( '.ultimate-security-switch-notice' ).remove();
			setCookie( 'ultimate_security_show_notice', '', 0 );
		} );

	// Hide search results when clicking outside
	$( document ).on( 'click', function ( e ) {
		if ( ! $( e.target ).closest( '.input-wrap' ).length ) {
			$( '.recent-ips-search' ).hide();
		}
	} );

	// Utility function to set cookies
	function setCookie( name, value, days ) {
		let expires = '';
		if ( days ) {
			const date = new Date();
			date.setTime( date.getTime() + days * 24 * 60 * 60 * 1000 );
			expires = '; expires=' + date.toUTCString();
		}
		document.cookie = name + '=' + ( value || '' ) + expires + '; path=/';
	}

	// Open switching dropdown
	$( '#ultimate-security-open-switching-dropdown' ).on( 'click', function ( e ) {
		e.preventDefault();
		$( '#wp-admin-bar-ultimate-security-switch-to-ip' ).toggleClass( 'hover' );
	} );

	// use this if you are using class to check
	if ( $( '.ultimate-security-user-meta-group' ).length ) {
		let min_refresh_after = 30;
		const refresh_after = $( '#currentTOTPCode' ).data( 'refresh_after' );
		const user_id = $( '#currentTOTPCode' ).data( 'user_id' );

		if ( refresh_after > 0 && refresh_after < min_refresh_after ) {
			min_refresh_after = refresh_after;
		}
		// Update after the given seconds, and then every 30 seconds
		setTimeout( function () {
			setInterval( function () {
				update_totp_otp_code( user_id );
			}, 30000 );
			update_totp_otp_code( user_id );
		}, min_refresh_after * 1000 );
	}
	// change-current-hotp
	$( 'body' ).on( 'click', '.change-current-hotp', function ( e ) {
		e.preventDefault();
		const user_id = $( '#currentHOTPCode' ).data( 'user_id' );
		update_hotp_otp_code( user_id );
	} );
	function update_hotp_otp_code( user_id ) {
		// console.log('Updating...');
		const dataJSON = {
			action: 'ultimate_security_update_hotp_otp_code',
			security: ultimate_security_ajax_obj.security,
			user_id,
		};
		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			beforeSend() {
				$( '#currentHOTPCode' ).html( 'Loading' );
			},
			success( response ) {
				// console.log(response);
				if ( response.success ) {
					$( '#currentHOTPCode' ).html( response?.data?.current_code );
				}
			},
			error( xhr, status, error ) {
				// console.log("Status: " + xhr.status);
				// console.log("Error: " + xhr.responseText);
			},
			complete() {},
		} );
	}
	$( 'body' ).on( 'click', '.change-current-hotp-secret', function ( e ) {
		e.preventDefault();
		const user_id = $( '#currentHOTPCode' ).data( 'user_id' );
		const dataJSON = {
			action: 'ultimate_security_update_hotp_secret_code',
			security: ultimate_security_ajax_obj.security,
			user_id,
		};
		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			beforeSend() {
				$( '#secret_key' ).html( 'Loading' );
			},
			success( response ) {
				// console.log(response);
				if ( response.success ) {
					$( '#secret_key' ).html( response?.data?.hotp_secret );
					$( '#currentHOTPCode' ).html( response?.data?.hotp_code );
					$( '.curent-hotp-qr-code' )
						.find( 'img' )
						.attr( 'src', response?.data?.hotp_qr_code );
					// update_hotp_otp_code(user_id);
				}
			},
			error( xhr, status, error ) {
				// console.log("Status: " + xhr.status);
				// console.log("Error: " + xhr.responseText);
			},
			complete() {},
		} );
	} );
	$( 'body' ).on( 'click', '.change-current-totp', function ( e ) {
		e.preventDefault();
		const user_id = $( '#currentTOTPCode' ).data( 'user_id' );
		update_totp_otp_code( user_id );
	} );

	function update_totp_otp_code( user_id ) {
		// console.log('Updating...');
		const dataJSON = {
			action: 'ultimate_security_update_totp_otp_code',
			security: ultimate_security_ajax_obj.security,
			user_id,
		};
		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			beforeSend() {
				$( '#currentTOTPCode' ).html( 'Loading' );
			},
			success( response ) {
				// console.log(response);
				if ( response.success ) {
					$( '#currentTOTPCode' ).html( response?.data?.current_code );
				}
			},
			error( xhr, status, error ) {
				// console.log("Status: " + xhr.status);
				// console.log("Error: " + xhr.responseText);
			},
			complete() {},
		} );
	}
	$( 'body' ).on( 'click', '.change-current-totp-secret', function ( e ) {
		e.preventDefault();
		const user_id = $( '#currentTOTPCode' ).data( 'user_id' );
		const dataJSON = {
			action: 'ultimate_security_update_totp_secret_code',
			security: ultimate_security_ajax_obj.security,
			user_id,
		};
		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			beforeSend() {
				$( '#secret_key' ).html( 'Loading' );
			},
			success( response ) {
				// console.log(response);
				if ( response.success ) {
					$( '#secret_key' ).html( response?.data?.totp_secret );
					$( '#currentTOTPCode' ).html( response?.data?.totp_code );
					$( '.curent-totp-qr-code' )
						.find( 'img' )
						.attr( 'src', response?.data?.totp_qr_code );
					// update_totp_otp_code(user_id);
				}
			},
			error( xhr, status, error ) {
				// console.log("Status: " + xhr.status);
				// console.log("Error: " + xhr.responseText);
			},
			complete() {},
		} );
	} );
	$( 'body' ).on( 'keyup', '.ultimate-security-2fa-verification-code', function () {
		const $ths = $( this );
		const value = $ths.val();
		const id = $ths.data( 'id' );
		if ( value.length == 6 ) {
			const dataJSON = {
				action: 'ultimate_security_enable_otp_email',
				id,
				value,
				security: ultimate_security_ajax_obj.security,
			};
			$.ajax( {
				cache: false,
				type: 'POST',
				url: ultimate_security_ajax_obj.ajax_url,
				data: dataJSON,
				beforeSend() {
					$ths.next().show();
				},
				success( response ) {
					// console.log(response);
					$ths.next().hide();
					$ths.next().next().fadeIn();
				},
				error( xhr, status, error ) {
					// console.log("Status: " + xhr.status);
					// console.log("Error: " + xhr.responseText);
				},
				complete() {},
			} );
		}
	} );
	$( 'body' ).on( 'click', '.sent-otp-email', function ( e ) {
		e.preventDefault();
		const $ths = $( this );
		const id = $ths.data( 'id' );
		const content = $ths.html();
		const dataJSON = {
			action: 'ultimate_security_sent_otp_email',
			id,
			security: ultimate_security_ajax_obj.security,
		};

		$.ajax( {
			cache: false,
			type: 'POST',
			url: ultimate_security_ajax_obj.ajax_url,
			data: dataJSON,
			beforeSend() {
				$ths.removeClass( 'sent-otp-email' ).prop( 'disabled', true ).html( 'Sending' );
				// $ths.next().show();
			},
			success( response ) {
				// console.log(response);
				$ths.next().hide();
				$ths.next().next().fadeIn();
				if ( response.success ) {
					$ths.html( response?.data?.success_message );
				} else {
					$ths.addClass( 'sent-otp-email' ).html( response?.data?.error_message );
				}
			},
			error( xhr, status, error ) {
				// console.log("Status: " + xhr.status);
				// console.log("Error: " + xhr.responseText);
			},
			complete() {},
		} );
	} );
	$( 'body' ).on( 'click', '.working', function ( e ) {
		e.preventDefault();
	} );
	$( '.ultimate-security-reset-user-2fa' ).on( 'click', function ( e ) {
		e.preventDefault();
		const $ths = $( this );
		// var link = $(this).attr('href');
		if ( confirm( 'Are you sure you want to reset?' ) ) {
			const user_id = $ths.data( 'user_id' );
			const dataJSON = {
				action: 'ultimate_security_user_2fa_reset',
				security: ultimate_security_ajax_obj.security,
				user_id,
			};
			$.ajax( {
				cache: false,
				type: 'POST',
				url: ultimate_security_ajax_obj.ajax_url,
				data: dataJSON,
				beforeSend() {},
				success( response ) {
					// console.log(response);
					if ( response.success ) {
						window.location.reload( true );
					}
				},
				error( xhr, status, error ) {
					// console.log("Status: " + xhr.status);
					// console.log("Error: " + xhr.responseText);
				},
				complete() {},
			} );
		}
	} );
} );
function setCookie( cname, cvalue, exdays ) {
	const d = new Date();
	d.setTime( d.getTime() + exdays * 24 * 60 * 60 * 1000 );
	const expires = 'expires=' + d.toGMTString();
	document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}
