jQuery( document ).ready(
	function ($) {

		// Track Impression — once per browser session to avoid hammering the server
		var impressionKey = 'wawp_impression_sent';
		if (wawp_ajax_obj.rest_url && ! sessionStorage.getItem( impressionKey )) {
			var impressionPayload = JSON.stringify(
				{
					page_id: wawp_ajax_obj.current_pid,
					device: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? 'Mobile' : 'Desktop',
					os: getOS()
				}
			);
			var impressionUrl = wawp_ajax_obj.rest_url + '/impression';
			var sent          = false;
			if (navigator.sendBeacon) {
				var blob = new Blob( [impressionPayload], {type: 'application/json'} );
				sent     = navigator.sendBeacon( impressionUrl, blob );
			}
			if ( ! sent) {
				fetch(
					impressionUrl,
					{
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'X-WP-Nonce': wawp_ajax_obj.nonce
						},
						body: impressionPayload
					}
				);
			}
			sessionStorage.setItem( impressionKey, '1' );
		}

		function getOS() {
			let userAgent    = window.navigator.userAgent,
			platform         = window.navigator.platform,
			macosPlatforms   = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
			windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
			iosPlatforms     = ['iPhone', 'iPad', 'iPod'],
			os               = null;

			if (macosPlatforms.indexOf( platform ) !== -1) {
				os = 'Mac OS';
			} else if (iosPlatforms.indexOf( platform ) !== -1) {
				os = 'iOS';
			} else if (windowsPlatforms.indexOf( platform ) !== -1) {
				os = 'Windows';
			} else if (/Android/.test( userAgent )) {
				os = 'Android';
			} else if ( ! os && /Linux/.test( platform )) {
				os = 'Linux';
			}
			return os || 'Unknown';
		}

		$( document ).on(
			'click',
			'#wawp-whatsapp-button',
			function () {
				if (wawp_ajax_obj.rest_url) {
					fetch(
						wawp_ajax_obj.rest_url + '/increment-clicks',
						{
							method: 'POST',
							headers: {
								'Content-Type': 'application/json',
								'X-WP-Nonce': wawp_ajax_obj.nonce
							},
							body: JSON.stringify(
								{
									page_id: wawp_ajax_obj.current_pid
								}
							)
						}
					);
				}
				$( '#wawp-chat-window' ).toggleClass( 'scale-toggle' );
			}
		);

		$( document ).on(
			'click',
			'#wawp-minimize-icon',
			function () {
				$( '#wawp-chat-window' ).toggleClass( 'scale-toggle' );
			}
		);

		let originalIconHTML = null;
		$( document ).on(
			'mouseenter',
			'#wawp-whatsapp-button',
			function () {
				let $btn  = $( this );
				let $icon = $btn.find( 'i, svg, .wawp-custom-svg, img' );
				if ($icon.length) {
					originalIconHTML = $icon[0].outerHTML;
					$icon.remove();
				}
				if ( ! $btn.find( '.wawp-typing-dots' ).length) {
						$btn.append(
						`<div class="wawp-typing-dots">
							<span class="dot"></span>
							<span class="dot"></span>
							<span class="dot"></span>
						</div>`
					);
				}
			}
		);

		$( document ).on(
			'mouseleave',
			'#wawp-whatsapp-button',
			function () {
				let $btn = $( this );
				$btn.find( '.wawp-typing-dots' ).remove();
				if (originalIconHTML) {
					$btn.append( originalIconHTML );
				}
			}
		);

		$( document ).on(
			'click touchstart',
			'.wawp-qr-chat-icon',
			function (e) {
				e.preventDefault();
				let waLink = $( this ).data( 'wawp-link' );
				if ( ! waLink) {
					return;
				}
				let phoneMatch = waLink.match( /phone=(\d+)/ );
				let phone      = phoneMatch ? phoneMatch[1] : '';
				let name       = $( this ).find( '.wawp-contact-name' ).text() || 'Unknown';
				if (wawp_ajax_obj.rest_url) {
					fetch(
						wawp_ajax_obj.rest_url + '/contact-click',
						{
							method: 'POST',
							headers: {
								'Content-Type': 'application/json',
								'X-WP-Nonce': wawp_ajax_obj.nonce
							},
							body: JSON.stringify(
								{
									phone: phone,
									name: name,
									page_id: wawp_ajax_obj.current_pid
								}
							)
						}
					);
				}
				$( '#wawp-contact-list' ).hide();
				$( '.wawp-social-container' ).hide();
				$( '#wawp-qr-card' ).css( 'display', 'flex' ).show();
				$( '#wawp-dynamic-qr' ).empty();
				setTimeout( function () {
					if (typeof QRCode !== 'undefined') {
						try {
							new QRCode(
								"wawp-dynamic-qr",
								{
									text: waLink,
									width: 150,
									height: 150,
									colorDark: "#000000",
									colorLight: "#ffffff",
									correctLevel: QRCode.CorrectLevel.H
								}
							);
						} catch (e) {
							console.error("QR Error:", e);
						}
					}
				}, 100 );
				$( '#wawp-open-whatsapp' ).attr( 'href', waLink ).data( 'phone', phone );
			}
		);

		$( document ).on(
			'click',
			'#wawp-open-whatsapp',
			function () {
				let phone = $( this ).data( 'phone' ) || '';
				if (phone) {
					if (wawp_ajax_obj.rest_url) {
						fetch(
							wawp_ajax_obj.rest_url + '/open-whatsapp',
							{
								method: 'POST',
								headers: {
									'Content-Type': 'application/json',
									'X-WP-Nonce': wawp_ajax_obj.nonce
								},
								body: JSON.stringify(
									{
										phone: phone,
										page_id: wawp_ajax_obj.current_pid
									}
								)
							}
						);
					}
				}
			}
		);

		// Track Social Link Clicks
		$( document ).on(
			'click',
			'.wawp-social-link',
			function () {
				let icon = $( this ).find( 'i' ).attr( 'class' );
				if (wawp_ajax_obj.rest_url) {
					fetch(
						wawp_ajax_obj.rest_url + '/social-click',
						{
							method: 'POST',
							headers: {
								'Content-Type': 'application/json',
								'X-WP-Nonce': wawp_ajax_obj.nonce
							},
							body: JSON.stringify(
								{
									icon: icon
								}
							)
						}
					);
				}
			}
		);

		$( document ).on(
			'click',
			'#wawp-qr-back',
			function () {
				$( '#wawp-qr-card' ).hide();
				$( '.wawp-chat-header' ).show();
				$( '#wawp-contact-list' ).show();
				$( '.wawp-social-container' ).show();
			}
		);
	}
);
