/**
 * Admin: Tools Page Logic (Integrity Scanner & Recovery).
 */
(function ($) {
	'use strict';

	function initSystemReportCopy() {
		var btn = document.getElementById('thespl-system-report-copy');
		if (!btn) {
			return;
		}
		var textarea = document.getElementById('thespl-system-report');
		var notice = document.getElementById('thespl-system-report-copied');
		btn.addEventListener(
			'click',
			function () {
				if (!textarea) {
					return;
				}
				var text = textarea.value;
				if (navigator.clipboard && navigator.clipboard.writeText) {
					navigator.clipboard.writeText(text).then(
						function () {
							if (notice) {
								notice.style.display = 'inline';
								setTimeout(
									function () {
										notice.style.display = 'none';
									},
									2000
								);
							}
						}
					);
					return;
				}
				textarea.select();
				try {
					document.execCommand('copy');
				} catch (e) {}
				if (notice) {
					notice.style.display = 'inline';
					setTimeout(
						function () {
							notice.style.display = 'none';
						},
						2000
					);
				}
			}
		);
	}

	function initChangelogModal() {
		var openBtn = document.getElementById('thespl-changelog-open');
		var closeBtn = document.getElementById('thespl-changelog-close');
		var modal = document.getElementById('thespl-changelog-modal');
		if (!modal || !openBtn || !closeBtn) {
			return;
		}
		openBtn.addEventListener(
			'click',
			function () {
				modal.style.display = 'block';
			}
		);
		closeBtn.addEventListener(
			'click',
			function () {
				modal.style.display = 'none';
			}
		);
		modal.addEventListener(
			'click',
			function (event) {
				if (event.target === modal) {
					modal.style.display = 'none';
				}
			}
		);
	}

	function initOnboardingOverlay() {
		var overlay = document.getElementById('thespl-onboarding-overlay');
		if (!overlay) {
			return;
		}
		var closeBtn = document.getElementById('thespl-onboarding-close');
		var disableBtn = document.getElementById('thespl-onboarding-disable');
		var settingsLink = document.getElementById('thespl-onboarding-settings-link');
		var backdrop = overlay.querySelector('.thespl-onboarding-backdrop');
		if (!backdrop) {
			return;
		}
		var ajaxUrl = (typeof thespl_tools_vars !== 'undefined' && thespl_tools_vars && thespl_tools_vars.ajax_url) ? thespl_tools_vars.ajax_url : null;
		var nonce = (typeof thespl_tools_vars !== 'undefined' && thespl_tools_vars && thespl_tools_vars.onboarding_nonce) ? thespl_tools_vars.onboarding_nonce : null;
		var showOverlay = function () {
			var revealOverlay = function () {
				overlay.setAttribute('data-thespl-overlay-state', 'visible');
				overlay.setAttribute('aria-hidden', 'false');
			};
			if (window.requestAnimationFrame) {
				window.requestAnimationFrame(
					function () {
						window.requestAnimationFrame(revealOverlay);
					}
				);
				return;
			}
			window.setTimeout(revealOverlay, 0);
		};
		var hideOverlay = function () {
			var iframe = document.getElementById('thespl-onboarding-video');
			if (iframe && iframe.tagName && iframe.tagName.toLowerCase() === 'iframe') {
				iframe.src = '';
			}
			overlay.setAttribute('data-thespl-overlay-state', 'hidden');
			overlay.setAttribute('aria-hidden', 'true');
			overlay.style.display = 'none';
		};
		var sendDismiss = function () {
			if (!ajaxUrl || !nonce) {
				hideOverlay();
				return;
			}
			if (!window.fetch || !window.FormData) {
				hideOverlay();
				return;
			}
			var formData = new window.FormData();
			formData.append('action', 'thespl_dismiss_onboarding');
			formData.append('nonce', nonce);
			window.fetch(
				ajaxUrl,
				{
					method: 'POST',
					credentials: 'same-origin',
					body: formData
				}
			).then(
				function () {
					hideOverlay();
				}
			).catch(
				function () {
					hideOverlay();
				}
			);
		};
		if (closeBtn) {
			closeBtn.addEventListener(
				'click',
				function () {
					hideOverlay();
				}
			);
		}
		if (disableBtn) {
			disableBtn.addEventListener(
				'click',
				function () {
					sendDismiss();
				}
			);
		}
		backdrop.addEventListener(
			'click',
			function () {
				hideOverlay();
			}
		);
		if (settingsLink) {
			settingsLink.addEventListener(
				'click',
				function () {
					hideOverlay();
				}
			);
		}
		showOverlay();
	}

	function initRemoteBannerDismiss() {
		if (!window.document || !window.document.addEventListener) {
			return;
		}
		if (typeof thespl_tools_vars === 'undefined' || !thespl_tools_vars || !thespl_tools_vars.ajax_url || !thespl_tools_vars.remote_banner_nonce) {
			return;
		}
		document.addEventListener(
			'click',
			function (event) {
				var target = event.target;
				if (!target || !target.classList || !target.classList.contains('notice-dismiss')) {
					return;
				}
				var notice = target.closest('.notice[data-thespl-remote-banner-id]');
				if (!notice) {
					return;
				}
				var bannerId = notice.getAttribute('data-thespl-remote-banner-id');
				if (!bannerId) {
					return;
				}
				var days = notice.getAttribute('data-thespl-dismiss-days') || '0';
				var formData = new window.FormData();
				formData.append('action', 'thespl_remote_dismiss_banner');
				formData.append('banner_id', bannerId);
				formData.append('days', days);
				formData.append('_ajax_nonce', thespl_tools_vars.remote_banner_nonce);
				window.fetch(
					thespl_tools_vars.ajax_url,
					{
						method: 'POST',
						credentials: 'same-origin',
						body: formData
					}
				);
			}
		);
	}

	$(
		function () {
			console.log('THESPL Tools JS loaded');

			initSystemReportCopy();
			initChangelogModal();
			initOnboardingOverlay();
			initRemoteBannerDismiss();

			let toolsBusy = false;

			function toolsBeforeUnload(e) {
				if (! toolsBusy) {
					return;
				}
				e.preventDefault();
				e.returnValue = '';
				return '';
			}

			function attachToolsBeforeUnload() {
				if (toolsBusy) {
					window.addEventListener('beforeunload', toolsBeforeUnload);
				}
			}

			function detachToolsBeforeUnload() {
				window.removeEventListener('beforeunload', toolsBeforeUnload);
			}
			const $sampleInstall = $( '#thespl-sample-install' );
			const $sampleRemove  = $( '#thespl-sample-remove' );
			const $sampleStatus  = $( '#thespl-sample-status' );
			const $sampleMsg     = $sampleStatus.find( '.thespl-sample-message' );
			const $sampleBar     = $sampleStatus.find( '.thespl-progress-bar' );
			const $sampleSuccess = $( '#thespl-sample-success' );

			function resetSampleUI() {
				try {
					if ( $sampleBar.length ) {
						$sampleBar.css( 'width', '0%' );
					}
					if ( $sampleSuccess.length ) {
						$sampleSuccess.hide();
					}
				} catch (e) {}
				toolsBusy = false;
				detachToolsBeforeUnload();
			}

			if ( $sampleInstall.length ) {
				$sampleInstall.on(
					'click',
					function (e) {
						e.preventDefault();

						if ( $sampleStatus.length ) {
							$sampleStatus.show();
						}
						if ( $sampleBar.length ) {
							$sampleBar.css( 'width', '0%' );
						}
						if ( $sampleMsg.length ) {
							$sampleMsg.text( thespl_tools_vars.i18n.samplePreparing );
						}
						toolsBusy = true;
						attachToolsBeforeUnload();

						const fd = new window.FormData();
						fd.append( 'action', 'thespl_sample_import_start' );
						fd.append( '_wpnonce', thespl_tools_vars.sample_import_nonce );

						window.fetch(
							thespl_tools_vars.ajax_url,
							{
								method: 'POST',
								body: fd,
								credentials: 'same-origin'
							}
						)
							.then(
								function (r) {
									return r.json();
								}
							)
							.then(
								function (startRes) {
									if ( ! startRes || ! startRes.success ) {
										if ( $sampleMsg.length ) {
											const msg = startRes && startRes.data && startRes.data.message ? startRes.data.message : thespl_tools_vars.i18n.sampleInitFailed;
											$sampleMsg.text( msg );
										}
										resetSampleUI();
										return;
									}
									const session   = startRes.data.session || '';
									const total     = startRes.data.total_bytes || 0;
									let downloaded  = 0;

									function fetchChunk() {
										const fd2 = new window.FormData();
										fd2.append( 'action', 'thespl_sample_import_fetch' );
										fd2.append( '_wpnonce', thespl_tools_vars.sample_import_nonce );
										fd2.append( 'session', session );

										window.fetch(
											thespl_tools_vars.ajax_url,
											{
												method: 'POST',
												body: fd2,
												credentials: 'same-origin'
											}
										)
											.then(
												function (r) {
													return r.json();
												}
											)
											.then(
												function (f) {
													if ( ! f || ! f.success ) {
														if ( $sampleMsg.length ) {
															const msg = f && f.data && f.data.message ? f.data.message : thespl_tools_vars.i18n.sampleFetchFailed;
															$sampleMsg.text( msg );
														}
														resetSampleUI();
														return;
													}
													downloaded = f.data.downloaded_bytes || downloaded;
													if ( $sampleBar.length && total > 0 ) {
														const pct = Math.min( 100, Math.round( ( downloaded / total ) * 60 ) );
														$sampleBar.css( 'width', pct + '%' );
													}
													const done = f.data.done || false;
													if ( done ) {
														if ( $sampleMsg.length ) {
															$sampleMsg.text( thespl_tools_vars.i18n.sampleVerifying );
														}
														const fd3 = new window.FormData();
														fd3.append( 'action', 'thespl_sample_import_finalize' );
														fd3.append( '_wpnonce', thespl_tools_vars.sample_import_nonce );
														fd3.append( 'session', session );

														window.fetch(
															thespl_tools_vars.ajax_url,
															{
																method: 'POST',
																body: fd3,
																credentials: 'same-origin'
															}
														)
															.then(
																function (r) {
																	return r.json();
																}
															)
															.then(
																function (fin) {
																	if ( ! fin || ! fin.success ) {
																		if ( $sampleMsg.length ) {
																			const msg = fin && fin.data && fin.data.message ? fin.data.message : thespl_tools_vars.i18n.sampleFinalizeFailed;
																			$sampleMsg.text( msg );
																		}
																		resetSampleUI();
																		return;
																	}
																	const totalP = fin.data.total_playlists || 0;
																	let processed = 0;

																	function step() {
																		const fd4 = new window.FormData();
																		fd4.append( 'action', 'thespl_sample_import_step' );
																		fd4.append( '_wpnonce', thespl_tools_vars.sample_import_nonce );
																		fd4.append( 'session', session );

																		window.fetch(
																			thespl_tools_vars.ajax_url,
																			{
																				method: 'POST',
																				body: fd4,
																				credentials: 'same-origin'
																			}
																		)
																			.then(
																				function (r) {
																					return r.json();
																				}
																			)
																			.then(
																				function (s) {
																					if ( ! s || ! s.success ) {
																						if ( $sampleMsg.length ) {
																							const msg = s && s.data && s.data.message ? s.data.message : thespl_tools_vars.i18n.sampleStepFailed;
																							$sampleMsg.text( msg );
																						}
																						resetSampleUI();
																						return;
																					}
																					processed = s.data.processed || processed;
																					const doneS = s.data.done || false;
																					if ( $sampleBar.length && totalP > 0 ) {
																						const pct = 60 + Math.min( 40, Math.round( ( processed / Math.max( 1, totalP ) ) * 40 ) );
																						$sampleBar.css( 'width', pct + '%' );
																					}
																					if ( doneS ) {
																						if ( $sampleBar.length ) {
																							$sampleBar.css( 'width', '100%' );
																						}
																						if ( $sampleMsg.length ) {
																							$sampleMsg.text( thespl_tools_vars.i18n.sampleInstalled );
																						}
																						if ( $sampleSuccess.length ) {
																							$sampleSuccess.show();
																						}
																						toolsBusy = false;
																						detachToolsBeforeUnload();
																					} else {
																						if ( $sampleMsg.length ) {
																							$sampleMsg.text( thespl_tools_vars.i18n.sampleImporting );
																						}
																						step();
																					}
																				}
																			);
																	}

																	if ( totalP === 0 ) {
																		if ( $sampleBar.length ) {
																			$sampleBar.css( 'width', '100%' );
																		}
																		step();
																	} else {
																		step();
																	}
																}
															);
													} else {
														if ( $sampleMsg.length ) {
															$sampleMsg.text( thespl_tools_vars.i18n.sampleDownloading );
														}
														fetchChunk();
													}
												}
											);
									}

									fetchChunk();
								}
							);
					}
				);
			}

			if ( $sampleRemove.length ) {
				$sampleRemove.on(
					'click',
					function (e) {
						e.preventDefault();

						if ( $sampleStatus.length ) {
							$sampleStatus.show();
						}
						if ( $sampleBar.length ) {
							$sampleBar.css( 'width', '0%' );
						}
						if ( $sampleMsg.length ) {
							$sampleMsg.text( thespl_tools_vars.i18n.sampleRemoving );
						}
						toolsBusy = true;
						attachToolsBeforeUnload();

						const fd = new window.FormData();
						fd.append( 'action', 'thespl_sample_remove' );
						fd.append( '_wpnonce', thespl_tools_vars.sample_import_nonce );

						window.fetch(
							thespl_tools_vars.ajax_url,
							{
								method: 'POST',
								body: fd,
								credentials: 'same-origin'
							}
						)
							.then(
								function (r) {
									return r.json();
								}
							)
							.then(
								function (res) {
									if ( ! res || ! res.success ) {
										if ( $sampleMsg.length ) {
											const msg = res && res.data && res.data.message ? res.data.message : thespl_tools_vars.i18n.sampleRemoveFailed;
											$sampleMsg.text( msg );
										}
										resetSampleUI();
										return;
									}
									if ( $sampleBar.length ) {
										$sampleBar.css( 'width', '100%' );
									}
									if ( $sampleMsg.length ) {
										$sampleMsg.text( thespl_tools_vars.i18n.sampleRemoved );
									}
									toolsBusy = false;
									detachToolsBeforeUnload();
								}
							);
					}
				);
			}

			

			// --- Integrity Check Logic ---
			const $integrityBtn       = $( '#thespl-start-integrity' );
			const $streamBtn          = $( '#thespl-start-streaming-check' );
			const $integrityStatus    = $( '#thespl-integrity-status' );
			const $integrityMsg       = $integrityStatus.find( '.thespl-integrity-message' );
			const $integrityReport    = $integrityStatus.find( '.thespl-integrity-report' );
			const $integrityDetails   = $integrityStatus.find( '.thespl-integrity-details-body' );
			const $routeStatsBox      = $integrityStatus.find( '.thespl-status-stats-routes' );
			const $routeStatOk        = $routeStatsBox.find( '.stat-route-ok' );
			const $routeStatDomain    = $routeStatsBox.find( '.stat-route-domain' );
			const $routeStatHttp      = $routeStatsBox.find( '.stat-route-http' );

			if ( $integrityBtn.length ) {
				console.log('Integrity button found');
				let totalIntegrityItems = 0;
				let validCount          = 0;
				let invalidCount        = 0;
				let missingCount        = 0;
				let unprotectedCount    = 0;
				let duplicateCount      = 0;
				let routeOk             = 0;
				let routeDomain         = 0;
				let routeHttp           = 0;
				let routeError          = 0;

				$integrityBtn.on(
					'click',
					function (e) {
						e.preventDefault();
						console.log('Integrity clicked');

						validCount       = 0;
						invalidCount     = 0;
						missingCount     = 0;
						unprotectedCount = 0;
						duplicateCount   = 0;
						routeOk          = 0;
						routeDomain      = 0;
						routeHttp        = 0;
						routeError       = 0;

						$integrityBtn.prop( 'disabled', true ).addClass( 'button-disabled' );
						if ( $streamBtn.length ) {
							$streamBtn.prop( 'disabled', true ).addClass( 'button-disabled' );
						}
						$integrityStatus.show();
						$integrityMsg.text( thespl_tools_vars.i18n.verifying + '...' );
						$integrityReport.hide();
						$integrityDetails.empty();
						if ( $routeStatsBox.length ) {
							$routeStatsBox.hide();
							$routeStatOk.text( '0 ' + thespl_tools_vars.i18n.streamingRouteOk );
							$routeStatDomain.text( '0 ' + thespl_tools_vars.i18n.streamingRouteDomain );
							$routeStatHttp.text( '0 ' + thespl_tools_vars.i18n.streamingRouteHttp );
						}

						startIntegrityPhase( 'index', 0 );
					}
				);

				function startIntegrityPhase(phase, offset) {
					console.log('Starting Integrity phase:', phase, 'offset:', offset);
					$.ajax(
						{
							url: thespl_tools_vars.ajax_url,
							type: 'POST',
							data: {
								action: 'thespl_integrity_check',
								nonce: thespl_tools_vars.nonce,
								phase: phase,
								offset: offset
							},
							success: function (response) {
								console.log('Integrity response:', response);
								if (response.success) {
									if (phase === 'index') {
										totalIntegrityItems = response.data.total;
										console.log('Total items to scan:', totalIntegrityItems);
										startIntegrityPhase( 'process', 0 );
									} else {
										validCount       += (parseInt(response.data.valid) || 0);
										invalidCount     += (parseInt(response.data.invalid) || 0);
										missingCount     += (parseInt(response.data.missing) || 0);
										unprotectedCount += (parseInt(response.data.unprotected) || 0);
										duplicateCount   += (parseInt(response.data.duplicate) || 0);

										if (response.data.details && response.data.details.length > 0) {
											$integrityReport.show();
											response.data.details.forEach(
												function (item) {
													let color        = '#646970';
													let icon         = 'dashicons-yes';
													let label        = item.status;
													let displayTitle = item.title;
													let info         = '';

													if (item.status === 'corrupted') {
														color = '#d63638';
														icon  = 'dashicons-warning';
														label = thespl_tools_vars.i18n.invalid;
													} else if (item.status === 'missing') {
														color = '#d63638';
														icon  = 'dashicons-no';
														label = thespl_tools_vars.i18n.missing;
													} else if (item.status === 'unprotected') {
														color = '#dba617';
														icon  = 'dashicons-lock';
														label = thespl_tools_vars.i18n.unprotected;
													} else if (item.status === 'duplicate') {
														color = '#b32d2e';
														icon  = 'dashicons-admin-links';
														label = thespl_tools_vars.i18n.duplicate;
													} else if (item.status === 'valid') {
														color = '#00a32a';
														icon  = 'dashicons-yes';
														label = thespl_tools_vars.i18n.valid;
													}

													if (item.extension) {
														displayTitle += '.' + item.extension;
													}
													info = ' <small style="color:#a7aaad;">(ID: ' + item.id + ')</small>';
													if (item.status === 'duplicate' && item.duplicate_count) {
														info += ' <small style="color:#a7aaad;">(' + item.duplicate_count + 'x)</small>';
													}

													$integrityDetails.append(
														'<tr>' +
														'<td><strong>' + displayTitle + '</strong>' + info + '</td>' +
														'<td style="color:' + color + '; font-weight: 600;">' +
														'<span class="dashicons ' + icon + '" style="font-size:18px; width:18px; height:18px; vertical-align:middle; margin-right:5px;"></span>' +
														label +
														'</td>' +
														'<td class="thespl-route-cell" data-id="' + item.id + '">-</td>' +
														'</tr>'
													);
												}
											);
										}

										let progressText = thespl_tools_vars.i18n.verifying + ': ' + response.data.offset + ' / ' + totalIntegrityItems;
										$integrityMsg.text( progressText );
										
										// Progress-Bar aktualisieren
										const progress = totalIntegrityItems > 0 ? (response.data.offset / totalIntegrityItems) * 100 : 0;
										$integrityStatus.find('.thespl-progress-bar').css('width', progress + '%');

										if (response.data.is_done) {
											let finalMsg = '<strong>' + thespl_tools_vars.i18n.integrityComplete + ":</strong><br>";
											finalMsg    += '<span style="color:#00a32a;">✅ ' + validCount + " " + thespl_tools_vars.i18n.valid + "</span> | ";
											finalMsg    += '<span style="color:#b32d2e;">⛓️ ' + duplicateCount + " " + thespl_tools_vars.i18n.duplicate + "</span> | ";
											finalMsg    += '<span style="color:#dba617;">⚠️ ' + unprotectedCount + " " + thespl_tools_vars.i18n.unprotected + "</span> | ";
											finalMsg    += '<span style="color:#d63638;">❌ ' + invalidCount + " " + thespl_tools_vars.i18n.invalid + "</span> | ";
											finalMsg    += '<span style="color:#d63638;">🚫 ' + missingCount + " " + thespl_tools_vars.i18n.missing + "</span>";

											$integrityMsg.html( finalMsg );
											$integrityBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );
											if ( $streamBtn.length ) {
												$streamBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );
												if ( $routeStatsBox.length ) {
													$routeStatsBox.show();
												}
											}

											if (invalidCount > 0 || missingCount > 0 || unprotectedCount > 0 || duplicateCount > 0) {
												alert( thespl_tools_vars.i18n.integrityWarning );
											}
										} else {
											startIntegrityPhase( 'process', response.data.offset );
										}
									}
								} else {
									$integrityMsg.text( response.data.message || thespl_tools_vars.i18n.error );
									$integrityBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );
									if ( $streamBtn.length ) {
										$streamBtn.prop( 'disabled', true ).addClass( 'button-disabled' );
									}
									alert( response.data.message || thespl_tools_vars.i18n.error );
								}
							},
							error: function () {
								$integrityMsg.text( thespl_tools_vars.i18n.networkError );
								$integrityBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );
								if ( $streamBtn.length ) {
									$streamBtn.prop( 'disabled', true ).addClass( 'button-disabled' );
								}
								alert( thespl_tools_vars.i18n.networkError );
							}
						}
					);
				}

				let httpCodeCounts = {};

				if ( $streamBtn.length ) {
					$streamBtn.on(
						'click',
						function ( e ) {
							e.preventDefault();
							if ( $streamBtn.prop( 'disabled' ) ) {
								return;
							}
							routeOk     = 0;
							routeDomain = 0;
							routeHttp   = 0;
							routeError  = 0;
							httpCodeCounts = {};

							$streamBtn.prop( 'disabled', true ).addClass( 'button-disabled' );
							if ( $routeStatsBox.length ) {
								$routeStatsBox.show();
								$routeStatOk.text( '0 ' + thespl_tools_vars.i18n.streamingRouteOk );
								$routeStatDomain.text( '0 ' + thespl_tools_vars.i18n.streamingRouteDomain );
								$routeStatHttp.text( '0 ' + thespl_tools_vars.i18n.streamingRouteHttp );
							}

							$integrityMsg.text( thespl_tools_vars.i18n.streamingChecking + '...' );
							startStreamingCheck( 0, totalIntegrityItems );
						}
					);
				}

				function describeHttpRouteIssue( httpCode ) {
					if ( ! httpCode ) {
						return thespl_tools_vars.i18n.streamingRouteHttpSingle;
					}
					if ( httpCode === 403 ) {
						return thespl_tools_vars.i18n.streamingHttp403;
					}
					if ( httpCode === 404 ) {
						return thespl_tools_vars.i18n.streamingHttp404;
					}
					if ( httpCode === 429 ) {
						return thespl_tools_vars.i18n.streamingHttp429;
					}
					if ( httpCode >= 500 && httpCode < 600 ) {
						return thespl_tools_vars.i18n.streamingHttp5xx + ' (' + httpCode + ')';
					}
					return thespl_tools_vars.i18n.streamingRouteHttpSingle + ' (' + httpCode + ')';
				}

				function startStreamingCheck( offset, total ) {
					$.ajax(
						{
							url: thespl_tools_vars.ajax_url,
							type: 'POST',
							data: {
								action: 'thespl_streaming_route_check',
								nonce: thespl_tools_vars.nonce,
								offset: offset
							},
							success: function ( response ) {
								if ( response.success && response.data ) {
									const data = response.data;
									if ( Array.isArray( data.details ) ) {
										data.details.forEach(
											function ( item ) {
												const id        = parseInt( item.id ) || 0;
												const status    = item.route_status || 'error';
												const httpCode  = item.http_status || 0;
												const $routeCell = $integrityDetails.find( '.thespl-route-cell[data-id="' + id + '"]' );
												if ( ! $routeCell.length ) {
													return;
												}
												let label = '';
												let color = '#646970';

												if ( status === 'ok' ) {
													label = thespl_tools_vars.i18n.streamingRouteOkSingle;
													color = '#00a32a';
													routeOk++;
												} else if ( status === 'domain_mismatch' ) {
													label = thespl_tools_vars.i18n.streamingRouteDomainSingle;
													color = '#dba617';
													routeDomain++;
												} else if ( status === 'http_4xx' || status === 'http_5xx' ) {
													label = describeHttpRouteIssue( httpCode );
													color = '#d63638';
													routeHttp++;
													if ( httpCode ) {
														const key = String( httpCode );
														httpCodeCounts[ key ] = ( httpCodeCounts[ key ] || 0 ) + 1;
													}
												} else if ( status === 'redirect' ) {
													label = thespl_tools_vars.i18n.streamingRouteRedirect;
													if ( httpCode ) {
														label += ' (' + httpCode + ')';
													}
													color = '#646970';
												} else if ( status === 'meta_only' ) {
													label = thespl_tools_vars.i18n.streamingRouteMeta;
													color = '#646970';
												} else if ( status === 'no_url' ) {
													label = thespl_tools_vars.i18n.streamingRouteNoUrl;
													color = '#646970';
												} else {
													label = thespl_tools_vars.i18n.streamingRouteErrorSingle;
													color = '#d63638';
													routeError++;
												}

												$routeCell
													.text( label )
													.css( 'color', color );
											}
										);
									}

									if ( data.stats ) {
										if ( typeof data.stats.ok === 'number' ) {
											routeOk = data.stats.ok;
										}
										if ( typeof data.stats.domain_mismatch === 'number' ) {
											routeDomain = data.stats.domain_mismatch;
										}
										if ( typeof data.stats.http_4xx === 'number' || typeof data.stats.http_5xx === 'number' ) {
											const four = parseInt( data.stats.http_4xx || 0 );
											const five = parseInt( data.stats.http_5xx || 0 );
											routeHttp = four + five;
										}
									}

									if ( $routeStatsBox.length ) {
										$routeStatOk.text( routeOk + ' ' + thespl_tools_vars.i18n.streamingRouteOk );
										$routeStatDomain.text( routeDomain + ' ' + thespl_tools_vars.i18n.streamingRouteDomain );
										$routeStatHttp.text( routeHttp + ' ' + thespl_tools_vars.i18n.streamingRouteHttp );
									}

									const newOffset = parseInt( data.offset ) || 0;
									const done      = !! data.is_done;
									const totalVal  = total > 0 ? total : totalIntegrityItems;

									if ( totalVal > 0 ) {
										const progress = ( newOffset / totalVal ) * 100;
										$integrityStatus.find( '.thespl-progress-bar' ).css( 'width', progress + '%' );
									}

									if ( done ) {
										$integrityMsg.text( thespl_tools_vars.i18n.streamingComplete );
										$streamBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );

										if ( routeDomain > 0 || routeHttp > 0 || routeError > 0 ) {
											let summary = thespl_tools_vars.i18n.streamingWarning + '\n\n';
											if ( routeDomain > 0 ) {
												summary += '- ' + routeDomain + ' ' + thespl_tools_vars.i18n.streamingRouteDomain + '\n';
											}
											if ( routeHttp > 0 ) {
												summary += '- ' + routeHttp + ' ' + thespl_tools_vars.i18n.streamingRouteHttp + '\n';
											}
											if ( routeError > 0 ) {
												summary += '- ' + routeError + ' ' + thespl_tools_vars.i18n.streamingRouteErrorSingle + '\n';
											}
											alert( summary );
										}

										startPlaylistRouteCheck();
									} else {
										startStreamingCheck( newOffset, totalVal );
									}
								} else {
									const msg = response.data && response.data.message ? response.data.message : thespl_tools_vars.i18n.error;
									$integrityMsg.text( msg );
									$streamBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );
									alert( msg );
								}
							},
							error: function () {
								$integrityMsg.text( thespl_tools_vars.i18n.networkError );
								$streamBtn.prop( 'disabled', false ).removeClass( 'button-disabled' );
								alert( thespl_tools_vars.i18n.networkError );
							}
						}
					);
				}

				function startPlaylistRouteCheck() {
					if ( ! thespl_tools_vars || ! thespl_tools_vars.ajax_url ) {
						return;
					}

					$integrityMsg.text( thespl_tools_vars.i18n.playlistRouteChecking + '...' );

					$.ajax(
						{
							url: thespl_tools_vars.ajax_url,
							type: 'POST',
							data: {
								action: 'thespl_playlist_route_check',
								nonce: thespl_tools_vars.nonce
							},
							success: function ( response ) {
								if ( response.success && response.data ) {
									const data = response.data;
									let httpErrors = 0;
									let genericErrors = 0;

									if ( data.stats ) {
										const four = parseInt( data.stats.http_4xx || 0 );
										const five = parseInt( data.stats.http_5xx || 0 );
										httpErrors = four + five;
										genericErrors = parseInt( data.stats.error || 0 );
									}

									if ( httpErrors > 0 || genericErrors > 0 ) {
										let summary = thespl_tools_vars.i18n.playlistRouteWarning + '\n\n';

										if ( Array.isArray( data.details ) ) {
											data.details.forEach(
												function ( item ) {
													const status   = item.route_status || 'error';
													const code     = item.http_status || 0;
													const title    = item.title || '';
													const id       = item.id || 0;
													if ( status === 'ok' ) {
														return;
													}
													let line = '- #' + id + ' ' + title + ': ';
													if ( status === 'http_4xx' || status === 'http_5xx' ) {
														line += describeHttpRouteIssue( code );
													} else if ( status === 'redirect' ) {
														line += thespl_tools_vars.i18n.streamingRouteRedirect;
														if ( code ) {
															line += ' (' + code + ')';
														}
													} else {
														line += thespl_tools_vars.i18n.streamingRouteErrorSingle;
														if ( code ) {
															line += ' (' + code + ')';
														}
													}
													summary += line + '\n';
												}
											);
										}

										alert( summary );
									} else {
										$integrityMsg.text( thespl_tools_vars.i18n.playlistRouteComplete );
									}
								} else {
									const msg = response.data && response.data.message ? response.data.message : thespl_tools_vars.i18n.error;
									$integrityMsg.text( msg );
								}
							},
							error: function () {
								$integrityMsg.text( thespl_tools_vars.i18n.networkError );
							}
						}
					);
				}
			}
		}
	);
})( jQuery );
