(function () {
	try {
		var cfg = window.thesplColorProbeAdmin || {};
		var pid = parseInt( String( cfg.postId || '' ), 10 ) || 0;
		if ( pid <= 0 ) {
			return;
		}
		var magicBtn = document.getElementById( 'thespl-magic-btn-' + pid );
		var pageBg = document.getElementById( 'thespl-magic-page-bg-' + pid );
		var pageText = document.getElementById( 'thespl-magic-page-text-' + pid );
		var accent1 = document.getElementById( 'thespl-magic-accent1-' + pid );
		var accent2 = document.getElementById( 'thespl-magic-accent2-' + pid );
		if ( ! magicBtn || ! pageBg || ! pageText || ! accent1 || ! accent2 ) {
			return;
		}
		var i18n = cfg.i18n || {};
		var configuredAlgorithm = String( cfg.algorithm || 'auto' );
		var algorithms = cfg.algorithms || {};
		var container = document.createElement( 'div' );
		container.className = 'thespl-color-probe';
		container.style.marginTop = '10px';
		container.style.padding = '10px';
		container.style.border = '1px solid #dcdcde';
		container.style.borderRadius = '6px';
		container.style.background = '#fff';

		var title = document.createElement( 'div' );
		title.textContent = i18n.sectionTitle || 'Live DOM color analysis (Beta)';
		title.style.fontWeight = '600';
		title.style.marginBottom = '8px';
		container.appendChild( title );

		var label = document.createElement( 'label' );
		label.textContent = i18n.urlLabel || 'Target page URL';
		label.style.display = 'block';
		label.style.marginBottom = '6px';
		container.appendChild( label );

		var input = document.createElement( 'input' );
		input.type = 'url';
		input.className = 'regular-text';
		input.placeholder = i18n.urlPlaceholder || 'https://your-site.example/your-player-page/';
		input.value = cfg.homeUrl || '';
		input.style.width = '100%';
		input.style.maxWidth = '700px';
		container.appendChild( input );

		var algoWrap = document.createElement( 'div' );
		algoWrap.style.marginTop = '8px';
		algoWrap.style.maxWidth = '380px';

		var algoLabel = document.createElement( 'label' );
		algoLabel.textContent = i18n.algorithmLabel || 'Palette algorithm';
		algoLabel.style.display = 'block';
		algoLabel.style.marginBottom = '6px';
		algoWrap.appendChild( algoLabel );

		var algoSelect = document.createElement( 'select' );
		algoSelect.className = 'regular-text';
		algoSelect.style.width = '100%';
		var algorithmKeys = Object.keys( algorithms );
		if ( ! algorithmKeys.length ) {
			algorithms = {
				auto: 'Algorithm 1 · Balanced',
				surface_shift: 'Algorithm 2 · Surface Shift',
				vivid_contrast: 'Algorithm 3 · Vivid Contrast'
			};
			algorithmKeys = Object.keys( algorithms );
		}
		for ( var ai = 0; ai < algorithmKeys.length; ai++ ) {
			var key = String( algorithmKeys[ai] || '' );
			if ( ! key ) {
				continue;
			}
			var option = document.createElement( 'option' );
			option.value = key;
			option.textContent = String( algorithms[key] || key );
			algoSelect.appendChild( option );
		}
		algoSelect.value = algorithmKeys.indexOf( configuredAlgorithm ) >= 0 ? configuredAlgorithm : 'auto';
		algoWrap.appendChild( algoSelect );
		container.appendChild( algoWrap );

		var row = document.createElement( 'div' );
		row.style.marginTop = '8px';
		row.style.display = 'flex';
		row.style.gap = '8px';
		row.style.alignItems = 'center';

		var runBtn = document.createElement( 'button' );
		runBtn.type = 'button';
		runBtn.className = 'button button-secondary';
		runBtn.textContent = i18n.runButton || 'Analyze target page';
		row.appendChild( runBtn );

		var status = document.createElement( 'div' );
		status.style.fontSize = '12px';
		status.style.color = '#50575e';
		status.setAttribute( 'aria-live', 'polite' );
		row.appendChild( status );
		container.appendChild( row );

		magicBtn.parentNode.insertBefore( container, magicBtn.parentNode.firstChild );

		var pollTimer = null;
		var pollAttempts = 0;
		var maxAttempts = 60;

		var setStatus = function (msg, isError) {
			status.textContent = String( msg || '' );
			status.style.color = isError ? '#d63638' : '#2271b1';
		};

		var safeHex = function (v) {
			var s = String( v || '' ).trim();
			if ( /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test( s ) ) {
				return s;
			}
			return '';
		};

		var setInputValue = function (el, val) {
			if ( ! el ) {
				return;
			}
			el.value = val;
			try {
				el.dispatchEvent( new Event( 'input', { bubbles: true } ) );
			} catch (e) {
			}
			try {
				el.dispatchEvent( new Event( 'change', { bubbles: true } ) );
			} catch (e2) {
			}
		};

		var stopPolling = function () {
			if ( pollTimer ) {
				clearInterval( pollTimer );
				pollTimer = null;
			}
		};

		var mapStatusMessage = function (payload) {
			if ( ! payload || ! payload.status ) {
				return i18n.failedStatus || 'Failed to read analysis status.';
			}
			if ( payload.status === 'pending' ) {
				return i18n.statusPending || 'Session created. Waiting for frontend…';
			}
			if ( payload.status === 'running' ) {
				return i18n.statusRunning || 'Frontend analysis is running…';
			}
			if ( payload.status === 'failed' && payload.error_code === 'insufficient_signal' ) {
				return i18n.statusInsufficient || 'Not enough visible color signals found on this page.';
			}
			return i18n.waiting || 'Waiting for frontend result…';
		};

		var applyResult = function (result) {
			if ( ! result ) {
				return false;
			}
			var bg = safeHex( result.background );
			var tx = safeHex( result.text_color );
			var a1 = safeHex( result.accent_1 );
			var a2 = safeHex( result.accent_2 ) || a1;
			if ( ! bg || ! tx || ! a1 || ! a2 ) {
				return false;
			}
			setInputValue( pageBg, bg );
			setInputValue( pageText, tx );
			setInputValue( accent1, a1 );
			setInputValue( accent2, a2 );
			return true;
		};

		var pollStatus = function (sessionId, token) {
			var fd = new FormData();
			fd.append( 'action', 'thespl_color_probe_status' );
			fd.append( 'nonce', String( cfg.nonce || '' ) );
			fd.append( 'session_id', sessionId );
			fd.append( 'token', token );
			fetch( String( cfg.ajaxUrl || '' ), { method: 'POST', credentials: 'same-origin', body: fd } )
				.then(function (r) {
					if ( ! r.ok ) {
						throw new Error( String( r.status ) );
					}
					return r.json();
				})
				.then(function (j) {
					if ( ! j || ! j.success || ! j.data ) {
						throw new Error( 'invalid' );
					}
					var d = j.data;
					setStatus( mapStatusMessage( d ), false );
					if ( d.status === 'completed' ) {
						stopPolling();
						if ( applyResult( d.result ) ) {
							setStatus( i18n.completed || 'Colors imported. You can now generate a palette from these values.', false );
						} else {
							setStatus( i18n.failed || 'Analysis failed. Please retry or enter colors manually.', true );
						}
						runBtn.disabled = false;
						return;
					}
					if ( d.status === 'failed' ) {
						stopPolling();
						setStatus( mapStatusMessage( d ), true );
						runBtn.disabled = false;
						return;
					}
					if ( d.status === 'expired' ) {
						stopPolling();
						setStatus( i18n.expired || 'Analysis session expired. Please retry.', true );
						runBtn.disabled = false;
						return;
					}
					pollAttempts += 1;
					if ( pollAttempts >= maxAttempts ) {
						stopPolling();
						setStatus( i18n.expired || 'Analysis session expired. Please retry.', true );
						runBtn.disabled = false;
					}
				})
				.catch(function () {
					stopPolling();
					setStatus( i18n.failedStatus || 'Failed to read analysis status.', true );
					runBtn.disabled = false;
				});
		};

		var isSameSiteUrl = function (raw) {
			try {
				var base = String( cfg.homeUrl || window.location.origin || '' );
				var u = new URL( String( raw || '' ), base );
				var host = String( cfg.homeHost || '' ).toLowerCase();
				if ( ! host ) {
					return false;
				}
				return String( u.hostname || '' ).toLowerCase() === host;
			} catch (e) {
				return false;
			}
		};

		runBtn.addEventListener( 'click', function () {
			stopPolling();
			pollAttempts = 0;
			var targetUrl = String( input.value || '' ).trim();
			if ( ! targetUrl || ! isSameSiteUrl( targetUrl ) ) {
				setStatus( i18n.invalidUrl || 'Please enter a URL from this site.', true );
				return;
			}
			runBtn.disabled = true;
			setStatus( i18n.running || 'Starting analysis session…', false );
			var fd = new FormData();
			fd.append( 'action', 'thespl_color_probe_start' );
			fd.append( 'nonce', String( cfg.nonce || '' ) );
			fd.append( 'playlist_id', String( pid ) );
			fd.append( 'target_url', targetUrl );
			fd.append( 'algorithm', String( algoSelect.value || 'auto' ) );
			fetch( String( cfg.ajaxUrl || '' ), { method: 'POST', credentials: 'same-origin', body: fd } )
				.then(function (r) {
					if ( ! r.ok ) {
						throw new Error( String( r.status ) );
					}
					return r.json();
				})
				.then(function (j) {
					if ( ! j || ! j.success || ! j.data || ! j.data.open_url || ! j.data.session_id || ! j.data.token ) {
						throw new Error( 'invalid' );
					}
					setStatus( i18n.waiting || 'Waiting for frontend result…', false );
					var probeWindow = window.open( String( j.data.open_url ), '_blank' );
					if ( ! probeWindow ) {
						throw new Error( 'popup_blocked' );
					}
					pollTimer = setInterval(function () {
						pollStatus( String( j.data.session_id ), String( j.data.token ) );
					}, 2000);
					pollStatus( String( j.data.session_id ), String( j.data.token ) );
				})
				.catch(function (err) {
					if ( err && String( err.message || '' ) === 'popup_blocked' ) {
						setStatus( i18n.popupBlocked || 'Could not open the target page. Please allow popups and try again.', true );
					} else {
						setStatus( i18n.failedStart || 'Failed to start analysis.', true );
					}
					runBtn.disabled = false;
				});
		});
	} catch (e) {
	}
})();
