

(function(){
	var fadeDurations = {
		inMs: 25,
		outMs: 250
	};
	var BINAURAL_STATUS_DURATION_MS = 8000;
	var ensureStatusEl = function(root){
		if (!root) return null;
		var statusEl = root.querySelector('.thespl-player__status');
		if (!statusEl) {
			statusEl = document.createElement('div');
			statusEl.className = 'thespl-player__status';
			statusEl.setAttribute('role', 'status');
			statusEl.setAttribute('aria-live', 'polite');
			var variantsWrap = root.querySelector('.thespl-player__variants');
			var controlsWrap = root.querySelector('.thespl-player__controls');
			if (variantsWrap && variantsWrap.parentNode) {
				variantsWrap.parentNode.insertBefore(statusEl, variantsWrap);
			} else if (controlsWrap && controlsWrap.parentNode) {
				controlsWrap.parentNode.insertBefore(statusEl, controlsWrap);
			} else {
				root.appendChild(statusEl);
			}
		}
		return statusEl;
	};
	var triggerBinauralStatus = function(root, durationMs){
		if (!root) {
			return;
		}
		var text = getStatusText(root, 'binaural', 'Binaural audio - use headphones');
		if (!text || !text.length) {
			return;
		}
		var now = Date.now();
		var duration = (typeof durationMs === 'number' && durationMs > 0) ? durationMs : BINAURAL_STATUS_DURATION_MS;
		var until = now + duration;
		root._thesplBinauralStatusText = text;
		root._thesplBinauralStatusUntil = until;
		try {
			root.setAttribute('data-thespl-display-status', '1');
		} catch (e) {}
		if (typeof window.THESPL_Player_UI !== 'undefined' && window.THESPL_Player_UI && typeof window.THESPL_Player_UI.renderStatus === 'function') {
			try {
				window.THESPL_Player_UI.renderStatus(root);
			} catch (e) {}
		}
		setTimeout(function(){
			try {
				if (root && root._thesplBinauralStatusUntil && root._thesplBinauralStatusUntil <= Date.now()) {
					root._thesplBinauralStatusText = '';
					root._thesplBinauralStatusUntil = 0;
					if (window.THESPL_Player_UI && typeof window.THESPL_Player_UI.renderStatus === 'function') {
						window.THESPL_Player_UI.renderStatus(root);
					}
				}
			} catch (e) {}
		}, duration);
	};
	var ensureStatusChildren = function(root){
		var statusEl = ensureStatusEl(root);
		if (!statusEl) return null;
		if (statusEl.style.minHeight !== '22px') {
			statusEl.style.minHeight = '22px';
		}
		if (statusEl.style.display === 'none') {
			statusEl.style.display = 'block';
		}
		if (!statusEl._text) {
			var text = document.createElement('span');
			text.className = 'thespl-status-text';
			text.style.opacity = '1';
			// Transition managed by applyStatusText
			var dots = document.createElement('span');
			dots.className = 'thespl-status-dots';
			for (var i = 0; i < 3; i++) {
				var d = document.createElement('span');
				dots.appendChild(d);
			}
			statusEl.appendChild(text);
			statusEl.appendChild(dots);
			statusEl._text = text;
			statusEl._dots = dots;
		}
		return statusEl;
	};
	var applyStatusText = function(statusEl, nextText){
		if (!statusEl || !statusEl._text) return;
		var el = statusEl._text;
		var currentPending = (typeof el._pendingText === 'string') ? el._pendingText : null;
		var currentVisual = el.textContent || '';
		var target = nextText || '';
		var isHidden = statusEl.style.visibility === 'hidden';
		
		// If we are already heading towards this text, do nothing
		if (currentPending === target) return;
		// If no pending text, but visual is already target
		if (currentPending === null && currentVisual === target) {
			if (isHidden && target.length > 0) {
				// Was hidden, but has text? Show it.
				el.style.opacity = '0';
				statusEl.style.visibility = 'visible';
				void el.offsetWidth; // Force reflow
				el.style.opacity = '1';
			} else if (target.length > 0 && el.style.opacity === '0') {
				el.style.opacity = '1';
			}
			return;
		}

		el._pendingText = target;
		var fadeIn = fadeDurations.inMs;
		var fadeOut = fadeDurations.outMs;

		// Case 1: Initial load or currently hidden/empty -> Show immediately (fade in)
		if (isHidden || (currentVisual.length === 0 && el.style.opacity !== '1')) {
			if (isHidden) {
				el.style.opacity = '0';
				statusEl.style.visibility = 'visible';
			}
			el.textContent = target;
			el.style.transition = 'opacity ' + fadeIn + 'ms ease';
			
			// If we just set text, wait a tick to fade in
			requestAnimationFrame(function(){
				el.style.opacity = target.length > 0 ? '1' : '0';
				delete el._pendingText;
			});
			return;
		}

		// Case 2: Standard cross-fade (Fade Out -> Swap -> Fade In)
		el.style.transition = 'opacity ' + fadeOut + 'ms ease';
		el.style.opacity = '0';
		
		if (el._thesplFadeTimer) {
			clearTimeout(el._thesplFadeTimer);
		}
		
		el._thesplFadeTimer = setTimeout(function(){
			el.textContent = target;
			requestAnimationFrame(function(){
				el.style.transition = 'opacity ' + fadeIn + 'ms ease';
				el.style.opacity = target.length > 0 ? '1' : '0';
				el._thesplFadeTimer = null;
				delete el._pendingText;
			});
		}, fadeOut);
	};
	var ensureStatusCss = function(){};
	var ensureBinauralIconCss = function(){};
	var ensureBinauralBlinkCss = function(){};
	var ensurePlaylistCss = function(){};
	var setBinauralOverlay = function(root, isOn){
		if (!root) return;
		ensureStatusCss();
		ensureBinauralIconCss();
		var statusEl = ensureStatusChildren(root);
		if (!statusEl) return;
		if (!isOn) {
			root.removeAttribute('data-thespl-binaural-overlay');
			return;
		}
		root.setAttribute('data-thespl-binaural-overlay', '1');
	};
	var getStatusText = function(root, key, fallback){
		var val = '';
		try {
			if (root && root.getAttribute) {
				if (key === 'binaural') {
					val = root.getAttribute('data-thespl-i18n-binaural-message') || '';
				} else {
					val = root.getAttribute('data-thespl-i18n-status-' + key) || '';
				}
			}
			if (!val || !val.length) {
				var cfg = window.thesplPlayer || {};
				var l10n = cfg.l10n || {};
				if (key === 'binaural' && typeof l10n.binaural === 'string') {
					val = l10n.binaural;
				} else if (typeof l10n[key] === 'string') {
					val = l10n[key];
				}
			}
		} catch (e) {}
		if (!val || !val.length) {
			val = fallback || '';
		}
		return val;
	};
	var computeDisplayStatus = function(root){
		if (!root || !window.THESPL_Player_Store || typeof window.THESPL_Player_Store.getUiState !== 'function') {
			return null;
		}
		var state = window.THESPL_Player_Store.getUiState(root) || {};
		var phase = typeof state.uiPhase === 'string' && state.uiPhase.length ? state.uiPhase : '';
		if (!phase && typeof state.phase === 'string' && state.phase.length) {
			phase = state.phase;
		}
		var error = typeof state.error === 'string' ? state.error : '';
		var isBinaural = !!state.isBinaural;
		var hasPlayedOnce = !!state.hasPlayedOnce;
		var key = '';
		var showDots = false;
		var showHeadphones = false;
		var now = Date.now();
		if (root && root._thesplBinauralStatusText && root._thesplBinauralStatusUntil) {
			if (root._thesplBinauralStatusUntil > now) {
				return {
					key: 'binaural',
					textKey: 'binaural',
					showDots: false,
					showHeadphones: false,
					state: state
				};
			}
			root._thesplBinauralStatusText = '';
			root._thesplBinauralStatusUntil = 0;
		}
		if (error && error.length) {
			key = 'error';
		} else if (!hasPlayedOnce && !error) {
			key = '';
		} else if (phase === 'buffering') {
			key = 'buffering';
			showDots = true;
		} else if (phase === 'paused') {
			key = 'paused';
		} else if (phase === 'stopped') {
			key = 'stopped';
		}
		if (isBinaural && (phase === 'playing' || phase === 'ready' || phase === 'paused' || phase === 'stopped')) {
			showHeadphones = true;
		}
		if (!key && !error && !isBinaural) {
			return {
				key: '',
				textKey: '',
				showDots: false,
				showHeadphones: false,
				state: state
			};
		}
		var textKey = key;
		if (key === 'error' && !error) {
			textKey = '';
		}
		return {
			key: key,
			textKey: textKey,
			showDots: showDots,
			showHeadphones: showHeadphones,
			state: state
		};
	};
	var UI = {
		getText: function(root, key, fallback){
			return getStatusText(root, key, fallback);
		},
		renderVariants: function(wrap, variants, onSelect){
			if (!wrap || !Array.isArray(variants) || !variants.length) return;
			wrap.innerHTML = '';
			for (var i = 0; i < variants.length; i++) {
				var btn = document.createElement('button');
				btn.type = 'button';
				btn.className = 'thespl-player__variant';
				btn.setAttribute('role', 'tab');
				btn.setAttribute('aria-selected', i === 0 ? 'true' : 'false');
				btn.textContent = variants[i] || ('Variant ' + (i + 1));
				btn.addEventListener('click', (function(i, btn){
					return function(){
						var all = wrap.querySelectorAll('.thespl-player__variant');
						all.forEach(function(b){ b.setAttribute('aria-selected', 'false'); });
						btn.setAttribute('aria-selected', 'true');
						onSelect(i);
					};
				})(i, btn));
				wrap.appendChild(btn);
			}
		},
		renderPlaylist: function(wrap, tracks, onSelect, fallbackCoverUrl){
			if (!wrap || !Array.isArray(tracks)) return;
			wrap.innerHTML = '';
		},
		setTrackPlayableState: function(root, index, isPlayable, reasonKey){
			if (!root) return;
			var wrap = root.querySelector('.thespl-player__playlist');
			if (!wrap) return;
			var items = wrap.querySelectorAll('.thespl-player__track');
			if (!items || !items.length) return;
			var idx = Number(index);
			if (!Number.isFinite(idx)) return;
			if (idx < 0 || idx >= items.length) return;
			var item = items[idx];
			if (!item) return;
			try {
				var attrKey = 'data-thespl-unplayable-' + String(idx);
				if (isPlayable) {
					try {
						wrap.removeAttribute(attrKey);
					} catch (e) {}
				} else {
					try {
						wrap.setAttribute(attrKey, reasonKey && typeof reasonKey === 'string' ? reasonKey : '');
					} catch (e) {}
				}
				var titleEl = item.querySelector('.thespl-player__track-title');
				var baseTitle = '';
				if (titleEl) {
					baseTitle = titleEl.getAttribute('data-thespl-base-title') || titleEl.textContent || '';
					if (!titleEl.hasAttribute('data-thespl-base-title')) {
						titleEl.setAttribute('data-thespl-base-title', baseTitle);
					}
				}
				if (isPlayable) {
					item.classList.remove('thespl-player__track--unplayable');
					item.removeAttribute('aria-disabled');
					if (titleEl) {
						titleEl.style.fontWeight = '';
						titleEl.textContent = baseTitle;
					}
				} else {
					item.classList.add('thespl-player__track--unplayable');
					item.setAttribute('aria-disabled', 'true');
					if (titleEl) {
						var label = '';
						if (reasonKey && typeof reasonKey === 'string' && reasonKey.length) {
							label = getStatusText(root, reasonKey, '');
						}
						if (!label || !label.length) {
							label = 'Media file not available.';
						}
						while (titleEl.firstChild) {
							titleEl.removeChild(titleEl.firstChild);
						}
						titleEl.style.fontWeight = '400';
						if (baseTitle) {
							var titleSpan = document.createElement('span');
							titleSpan.textContent = baseTitle;
							titleSpan.style.fontWeight = '600';
							titleEl.appendChild(titleSpan);
							titleEl.appendChild(document.createTextNode(' – '));
						}
						var warnSpan = document.createElement('span');
						warnSpan.textContent = label;
						warnSpan.style.color = '#f97373';
						warnSpan.style.fontWeight = '400';
						titleEl.appendChild(warnSpan);
					}
				}
			} catch (e) {}
		},
		setTrackWaveformNotice: function(root, index, reasonKey){
			if (!root) return;
			var wrap = root.querySelector('.thespl-player__playlist');
			if (!wrap) return;
			var items = wrap.querySelectorAll('.thespl-player__track');
			if (!items || !items.length) return;
			var idx = Number(index);
			if (!Number.isFinite(idx)) return;
			if (idx < 0 || idx >= items.length) return;
			var item = items[idx];
			if (!item) return;
			if (item.classList.contains('thespl-player__track--unplayable')) {
				return;
			}
			var titleEl = item.querySelector('.thespl-player__track-title');
			if (!titleEl) return;
			var baseTitle = titleEl.getAttribute('data-thespl-base-title') || titleEl.textContent || '';
			if (!titleEl.hasAttribute('data-thespl-base-title')) {
				titleEl.setAttribute('data-thespl-base-title', baseTitle);
			}
			var label = getStatusText(root, reasonKey, '');
			if (!label || !label.length) {
				label = 'Waveform file not found (404).';
			}
			if (baseTitle) {
				titleEl.textContent = baseTitle + ' – ' + label;
			} else {
				titleEl.textContent = label;
			}
		},
		statusStart: function(root){
			if (root && window.THESPL_Player_Store && typeof window.THESPL_Player_Store.getUiState === 'function') {
				try {
					var state = window.THESPL_Player_Store.getUiState(root) || {};
					var phase = typeof state.phase === 'string' ? state.phase : '';
					if (typeof state.uiPhase === 'string' && state.uiPhase.length) {
						phase = state.uiPhase;
					}
					var hasPlayedOnce = !!state.hasPlayedOnce;
					if (!hasPlayedOnce && !state.error) {
						return;
					}
					if (phase !== 'buffering') {
						return;
					}
				} catch (e) {}
			}
			ensureStatusCss();
			var el = ensureStatusChildren(root);
			if (!el) return;
			if (root && root.getAttribute && root.getAttribute('data-thespl-binaural-overlay') === '1') return;
			el.style.visibility = 'visible';
			var msg = getStatusText(root, 'buffering', 'Buffering');
			applyStatusText(el, msg);
			if (el._dots) el._dots.style.opacity = '1';
		},
		statusReady: function(root){
			if (root && window.THESPL_Player_Store && typeof window.THESPL_Player_Store.getUiState === 'function') {
				try {
					var state = window.THESPL_Player_Store.getUiState(root) || {};
					var hasPlayedOnce = !!state.hasPlayedOnce;
					if (!hasPlayedOnce && !state.error) {
						return;
					}
				} catch (e) {}
			}
			ensureStatusCss();
			var el = ensureStatusChildren(root);
			if (!el) return;
			if (root && root.getAttribute && root.getAttribute('data-thespl-binaural-overlay') === '1') return;
			if (el._dots) el._dots.style.opacity = '0';
			el.style.visibility = 'visible';
		},
		setInfotextMode: function(root, mode){
			if (!root) return;
			var m = mode === 'scroll' ? 'scroll' : 'rotate';
			try {
				root.setAttribute('data-thespl-infotext-mode', m);
			} catch (e) {}
		},
		statusHide: function(root){
			ensureStatusCss();
			var el = ensureStatusChildren(root); // Use ensureStatusChildren to get _text/_dots access
			if (!el) return;
			if (root && root.getAttribute && root.getAttribute('data-thespl-binaural-overlay') === '1') return;
			if (el._dots) el._dots.style.opacity = '0';
			el.style.visibility = 'visible';
		},
		statusPaused: function(root){
			ensureStatusCss();
			var el = ensureStatusChildren(root);
			if (!el) return;
			if (root && root.getAttribute && root.getAttribute('data-thespl-binaural-overlay') === '1') return;
			el.style.visibility = 'visible';
			var msg = getStatusText(root, 'paused', 'Paused');
			applyStatusText(el, msg);
			if (el._dots) el._dots.style.opacity = '0';
		},
		statusStopped: function(root){
			ensureStatusCss();
			var el = ensureStatusChildren(root);
			if (!el) return;
			if (root && root.getAttribute && root.getAttribute('data-thespl-binaural-overlay') === '1') return;
			el.style.visibility = 'visible';
			var msg = getStatusText(root, 'stopped', 'Stopped');
			applyStatusText(el, msg);
			if (el._dots) el._dots.style.opacity = '0';
		},
		renderStatus: function(root){
			var model = computeDisplayStatus(root);
			if (!model) {
				return;
			}
			ensureStatusCss();
			var statusEl = ensureStatusChildren(root);
			if (!statusEl) {
				return;
			}
			var key = model.key;
			var textKey = model.textKey;
			var showDots = !!model.showDots;
			var hasInfotext = false;
			try {
				if (root && root.getAttribute) {
					hasInfotext = root.getAttribute('data-thespl-infotext-bound') === '1';
				}
			} catch (e) {}
			var text = '';
			var uiMessageKey = model.state && typeof model.state.uiMessageKey === 'string' ? model.state.uiMessageKey : '';
			if (key === 'error') {
				if (uiMessageKey && uiMessageKey.length) {
					text = getStatusText(root, uiMessageKey, 'Unexpected player error. Please try again.');
				}
				if ((!text || !text.length) && model.state && typeof model.state.error === 'string' && model.state.error.length) {
					text = model.state.error;
				}
			} else if (textKey) {
				var fallback = '';
				if (textKey === 'buffering') {
					fallback = 'Buffering';
				} else if (textKey === 'ready') {
					fallback = 'Ready';
				} else if (textKey === 'paused') {
					fallback = 'Paused';
				} else if (textKey === 'stopped') {
					fallback = 'Stopped';
				} else if (textKey === 'binaural') {
					fallback = 'Binaural audio - use headphones';
				}
				text = getStatusText(root, textKey, fallback);
			}
			if (!text || !text.length) {
				var stateObj = model.state || {};
				var phase = '';
				if (typeof stateObj.uiPhase === 'string' && stateObj.uiPhase.length) {
					phase = stateObj.uiPhase;
				} else if (typeof stateObj.phase === 'string' && stateObj.phase.length) {
					phase = stateObj.phase;
				}
				var hasPlayedOnce = !!stateObj.hasPlayedOnce;
				var isPlaybackPhase = phase === 'playing' || phase === 'ready' || phase === 'paused' || phase === 'stopped';
				if ((!key || !key.length) && (!textKey || !textKey.length) && hasPlayedOnce && isPlaybackPhase) {
					var meta = null;
					if (window.THESPL_Player_Store && typeof window.THESPL_Player_Store.getMeta === 'function') {
						try {
							meta = window.THESPL_Player_Store.getMeta(root) || {};
						} catch (e) {}
					}
					var tvTrack = meta && typeof meta.track === 'string' ? meta.track : '';
					var tvVariant = meta && typeof meta.variant === 'string' ? meta.variant : '';
					var tv = '';
					if (tvTrack && tvVariant) {
						tv = tvTrack + ' \u2013 ' + tvVariant;
					} else {
						tv = tvTrack || tvVariant || '';
					}
					if (tv && tv.length) {
						text = tv;
					}
				}
			}
			if (!text || !text.length) {
				text = '';
				if (!model.showHeadphones) {
					if (statusEl._dots) {
						statusEl._dots.style.opacity = '0';
						statusEl._dots.style.display = 'none';
					}
					try {
						if (root && root.removeAttribute) {
							root.removeAttribute('data-thespl-display-status');
						}
					} catch (e) {}
				}
			}
			try {
				var linkEl = statusEl.querySelector('.thespl-infotext-link');
				if (linkEl) {
					linkEl.textContent = '';
					linkEl.removeAttribute('href');
					linkEl.style.display = 'none';
				}
			} catch (e) {}
			applyStatusText(statusEl, text);
			try {
				var isBinauralStatus = textKey === 'binaural' || key === 'binaural';
				var textEl = statusEl._text;
				if (textEl && textEl.classList) {
					if (isBinauralStatus && text && text.length) {
						textEl.classList.add('thespl-status-text--binaural');
						ensureBinauralBlinkCss();
					} else {
						textEl.classList.remove('thespl-status-text--binaural');
					}
				}
			} catch (e) {}
			statusEl.style.visibility = 'visible';
			try {
				if (root) {
					root.setAttribute('data-thespl-display-status', '1');
				}
			} catch (e) {}
			if (statusEl._dots) {
				if (showDots) {
					statusEl._dots.style.display = 'inline-flex';
					statusEl._dots.style.opacity = '1';
				} else {
					statusEl._dots.style.opacity = '0';
					statusEl._dots.style.display = 'none';
				}
			}
		},
		bindAudioInfo: function(root){
			if (!root || !window.THESPL_Player_Store) return function(){};
			var store = window.THESPL_Player_Store;
			var wrap = root.querySelector('.thespl-player__audio-info');
			if (!wrap) return function(){};
			var setField = function(key, value){
				var el = wrap.querySelector('[data-thespl-audio-info="' + key + '"]');
				if (el) {
					el.textContent = value || '';
				}
			};
			var formatSampleRateValue = function(value){
				var str = '';
				if (typeof value === 'number' && isFinite(value)) {
					str = String(value);
				} else if (typeof value === 'string') {
					str = value;
				}
				if (!str) {
					return '';
				}
				var out = str;
				try {
					var cleaned = str.replace(/,/g, '.').replace(/[^0-9.]+/g, '');
					var num = parseFloat(cleaned);
					if (!isFinite(num) || num <= 0) {
						return out;
					}
					if (num >= 1000) {
						var khzFromHz = num / 1000;
						if (Math.abs(num % 1000) < 0.0001) {
							out = String(khzFromHz.toFixed(0)) + ' kHz';
						} else {
							out = String(khzFromHz.toFixed(1)) + ' kHz';
						}
						return out;
					}
					if (num < 1000) {
						if (Math.abs(num - Math.round(num)) < 0.0001) {
							out = String(num.toFixed(0)) + ' kHz';
						} else {
							out = String(num.toFixed(1)) + ' kHz';
						}
						return out;
					}
				} catch (e) {}
				return out;
			};
			var formatAudioContextValue = function(value){
				if (!value) {
					return '';
				}
				var str = String(value);
				try {
					var matches = str.match(/([0-9]+(?:[.,][0-9]+)?)(\s*Hz)?/g);
					if (!matches || !matches.length) {
						return str;
					}
					var last = matches[matches.length - 1];
					var numMatch = last.match(/([0-9]+(?:[.,][0-9]+)?)/);
					if (!numMatch) {
						return str;
					}
					var formatted = formatSampleRateValue(numMatch[1]);
					if (!formatted) {
						return str;
					}
					return str.replace(last, formatted);
				} catch (e) {}
				return str;
			};
			var levelsWrap = wrap.querySelector('[data-thespl-audio-info-levels]');
			var levelRows = [];
			var ensureLevelRows = function(levels){
				if (!levelsWrap) return;
				var desired = levels.length;
				if (levelRows.length === desired) {
					for (var i = 0; i < desired; i++) {
						var label = levels[i] && typeof levels[i].label === 'string' ? levels[i].label : '';
						levelRows[i].labelEl.textContent = label || ('Variant ' + (i + 1));
					}
					return;
				}
				levelsWrap.innerHTML = '';
				levelRows = [];
				for (var i = 0; i < desired; i++) {
					var row = document.createElement('div');
					row.className = 'thespl-player__audio-info-level-row';
					row.setAttribute('data-active', '0');
					var labelEl = document.createElement('div');
					labelEl.className = 'thespl-player__audio-info-level-label';
					var labelText = levels[i] && typeof levels[i].label === 'string' ? levels[i].label : '';
					labelEl.textContent = labelText || ('Variant ' + (i + 1));
					var rmsEl = document.createElement('div');
					rmsEl.className = 'thespl-player__audio-info-level-val';
					var rmsKeyEl = document.createElement('span');
					rmsKeyEl.className = 'thespl-player__audio-info-level-key';
					rmsKeyEl.textContent = 'RMS';
					var rmsNumEl = document.createElement('span');
					rmsNumEl.className = 'thespl-player__audio-info-level-num';
					var rmsUnitEl = document.createElement('span');
					rmsUnitEl.className = 'thespl-player__audio-info-level-unit';
					rmsEl.appendChild(rmsKeyEl);
					rmsEl.appendChild(rmsNumEl);
					rmsEl.appendChild(rmsUnitEl);
					var peakEl = document.createElement('div');
					peakEl.className = 'thespl-player__audio-info-level-val';
					var peakKeyEl = document.createElement('span');
					peakKeyEl.className = 'thespl-player__audio-info-level-key';
					peakKeyEl.textContent = 'Peak';
					var peakNumEl = document.createElement('span');
					peakNumEl.className = 'thespl-player__audio-info-level-num';
					var peakUnitEl = document.createElement('span');
					peakUnitEl.className = 'thespl-player__audio-info-level-unit';
					peakEl.appendChild(peakKeyEl);
					peakEl.appendChild(peakNumEl);
					peakEl.appendChild(peakUnitEl);
					row.appendChild(labelEl);
					row.appendChild(rmsEl);
					row.appendChild(peakEl);
					levelsWrap.appendChild(row);
					levelRows.push({
						row: row,
						labelEl: labelEl,
						rmsNumEl: rmsNumEl,
						rmsUnitEl: rmsUnitEl,
						peakNumEl: peakNumEl,
						peakUnitEl: peakUnitEl
					});
				}
			};
			var render = function(){
				try {
					var meta = store.getMeta(root) || {};
					var live = store.getLive(root) || {};
					var levels = store.getLevels(root) || [];
					setField('plugin_version', meta.plugin_version || '');
					setField('plugin_codename', meta.plugin_codename || '');
					setField('plugin_build', meta.plugin_build || '');
					setField('track', meta.track || '');
					setField('variant', meta.variant || '');
					var formattedSr = formatSampleRateValue(meta.sample_rate || '');
					setField('sample_rate', formattedSr);
					setField('bit_depth', meta.bit_depth || '');
					setField('channels', meta.channels || '');
					var acRaw = live.audiocontext || meta.audiocontext || '';
					var acFormatted = formatAudioContextValue(acRaw);
					setField('audiocontext', acFormatted);
					setField('playback', live.playback || '');
					setField('buffer', live.buffer || '');
					if (levelsWrap && levels.length) {
						ensureLevelRows(levels);
						for (var i = 0; i < levels.length; i++) {
							var rowInfo = levelRows[i];
							if (!rowInfo) continue;
							var item = levels[i] || {};
							var isActive = item && (item.active === 1 || item.active === true);
							rowInfo.row.setAttribute('data-active', isActive ? '1' : '0');
							rowInfo.rmsNumEl.textContent = item.rms || '';
							if (rowInfo.rmsUnitEl) {
								rowInfo.rmsUnitEl.textContent = 'dBFS';
							}
							rowInfo.peakNumEl.textContent = item.peak || '';
							if (rowInfo.peakUnitEl) {
								rowInfo.peakUnitEl.textContent = 'dBFS';
							}
						}
					}
				} catch (e) {}
			};
			render();
			var unsubscribe = store.subscribe(root, render);
			try {
				root.setAttribute('data-thespl-audio-info-bound', '1');
			} catch (e) {}
			return function(){
				try {
					unsubscribe();
				} catch (e) {}
			};
		},
		bindPlaylist: function(root, api){
			if (!root || !window.THESPL_Player_Store) return function(){};
			var store = window.THESPL_Player_Store;
			var wrap = root.querySelector('.thespl-player__playlist');
			if (!wrap) return function(){};
			ensurePlaylistCss();
			var lastTracksKey = '';
			var render = function(){
				try {
					var state = store.getPlaylist(root) || {};
					var sel = store.getSelection(root) || {};
					var tracks = Array.isArray(state.tracks) ? state.tracks : [];
					var trackIndex = Number.isFinite(sel.trackIndex) ? sel.trackIndex : (Number.isFinite(state.currentTrackIndex) ? state.currentTrackIndex : 0);
					var variantIndex = Number.isFinite(sel.variantIndex) ? sel.variantIndex : (Number.isFinite(state.currentVariantIndex) ? state.currentVariantIndex : 0);
					if (trackIndex < 0) {
						trackIndex = 0;
					}
					if (trackIndex >= tracks.length) {
						trackIndex = tracks.length ? (tracks.length - 1) : 0;
					}
					var keyParts = [String(tracks.length)];
					for (var i = 0; i < tracks.length; i++) {
						var tKey = tracks[i] || {};
						var id = '';
						if (typeof tKey.id === 'string' && tKey.id) {
							id = tKey.id;
						} else if (tKey.cover && typeof tKey.cover.url === 'string' && tKey.cover.url) {
							id = tKey.cover.url;
						} else if (typeof tKey.coverUrl === 'string' && tKey.coverUrl) {
							id = tKey.coverUrl;
						} else if (typeof tKey.title === 'string' && tKey.title) {
							id = tKey.title;
						} else {
							id = String(i);
						}
						keyParts.push(id);
					}
					var tracksKey = keyParts.join('|');
					var needsRebuild = tracksKey !== lastTracksKey || !wrap.firstChild;
					if (needsRebuild) {
						lastTracksKey = tracksKey;
						wrap.innerHTML = '';
						for (var j = 0; j < tracks.length; j++) {
							var t = tracks[j] || {};
							var item = document.createElement('div');
							item.className = 'thespl-player__track';
							item.setAttribute('role', 'listitem');
							item.setAttribute('tabindex', '0');
							item.setAttribute('aria-current', j === trackIndex ? 'true' : 'false');
							var img = document.createElement('img');
							img.className = 'thespl-player__cover';
							img.alt = '';
							var cover = '';
							if (t.cover && typeof t.cover.url === 'string' && t.cover.url) {
								cover = t.cover.url;
							} else if (typeof t.coverUrl === 'string' && t.coverUrl) {
								cover = t.coverUrl;
							} else {
								try {
									var cfg = window.thesplPlayer || {};
									if (typeof cfg.defaultCoverUrl === 'string') {
										cover = cfg.defaultCoverUrl;
									}
								} catch (e) {}
							}
							if (cover) {
								img.src = cover;
							}
							var meta = document.createElement('div');
							var title = document.createElement('div');
							title.className = 'thespl-player__track-title';
							var titleText = t && typeof t.title === 'string' ? t.title : '';
							var creditsText = t && typeof t.credits === 'string' ? t.credits : '';
							if (titleText) {
								title.appendChild(document.createTextNode(titleText));
							}
							if (creditsText) {
								if (titleText) {
									title.appendChild(document.createTextNode(' | '));
								}
								var creditsEl = document.createElement('span');
								creditsEl.className = 'thespl-player__track-credits';
								creditsEl.textContent = creditsText;
								title.appendChild(creditsEl);
							}
							var artist = document.createElement('div');
							artist.className = 'thespl-player__track-artist';
							artist.textContent = t.artist || '';
							meta.appendChild(title);
							meta.appendChild(artist);
							item.appendChild(img);
							item.appendChild(meta);
							(function(index, element){
								var select = function(){
									var all = wrap.querySelectorAll('.thespl-player__track');
									all.forEach(function(n){ n.setAttribute('aria-current', 'false'); });
									element.setAttribute('aria-current', 'true');
									try {
										store.setSelection(root, {
											trackIndex: index,
											variantIndex: variantIndex
										});
									} catch (e) {}
									var tries = 0;
									var maxTries = 20;
									var delayMs = 100;
									var invokePlay = function(){
										var inst = null;
										try {
											inst = api || root._thesplPlayerApi || null;
										} catch (e) {}
										if (inst && typeof inst.playTrack === 'function') {
											try { inst.playTrack(index); } catch (e) {}
											return;
										}
										if (tries >= maxTries) {
											return;
										}
										tries++;
										try { window.setTimeout(invokePlay, delayMs); } catch (e) {}
									};
									invokePlay();
								};
								element.addEventListener('click', function(){ select(); });
								element.addEventListener('keydown', function(e){
									var key = e && e.key;
									if (key === 'Enter' || key === ' ') {
										e.preventDefault();
										select();
									}
								});
							})(j, item);
							wrap.appendChild(item);
							try {
								var attrKey = 'data-thespl-unplayable-' + String(j);
								var reasonKey = '';
								try {
									reasonKey = wrap.getAttribute(attrKey) || '';
								} catch (e) {}
								if (reasonKey && window.THESPL_Player_UI && typeof window.THESPL_Player_UI.setTrackPlayableState === 'function') {
									try {
										window.THESPL_Player_UI.setTrackPlayableState(root, j, false, reasonKey);
									} catch (e) {}
								}
							} catch (e) {}
						}
					} else {
						var allItems = wrap.querySelectorAll('.thespl-player__track');
						allItems.forEach(function(node, idx){
							node.setAttribute('aria-current', idx === trackIndex ? 'true' : 'false');
						});
					}
				} catch (e) {}
			};
			render();
			var unsubscribe = function(){};
			try {
				unsubscribe = store.subscribe(root, render);
			} catch (e) {}
			return function(){
				try {
					unsubscribe();
				} catch (e) {}
			};
		},
		bindInfotext: function(root){
			if (!root || !window.THESPL_Player_Store) return function(){};
			var store = window.THESPL_Player_Store;
			ensureStatusCss();
			var statusEl = ensureStatusChildren(root);
			if (!statusEl) return function(){};
			var wrap = root.querySelector('.thespl-player__infotext');
			if (!wrap) {
				wrap = document.createElement('div');
				wrap.className = 'thespl-player__infotext';
				statusEl.appendChild(wrap);
			}
			try {
				if (wrap && wrap.style) {
					wrap.style.overflowX = 'hidden';
					wrap.style.overflowY = 'hidden';
					wrap.style.display = 'block';
					wrap.style.width = '100%';
					wrap.style.maxWidth = '360px';
					wrap.style.marginLeft = 'auto';
					wrap.style.marginRight = 'auto';
					wrap.style.marginTop = '2px';
					wrap.style.marginBottom = '8px';
				}
			} catch (e) {}
			var innerEl = wrap.querySelector('.thespl-infotext-inner');
			if (!innerEl) {
				innerEl = document.createElement('span');
				innerEl.className = 'thespl-infotext-inner';
				if (innerEl.style) {
					innerEl.style.display = 'inline-block';
					innerEl.style.whiteSpace = 'nowrap';
					innerEl.style.maxWidth = 'none';
					innerEl.style.willChange = 'transform';
				}
				if (wrap.firstChild) {
					wrap.insertBefore(innerEl, wrap.firstChild);
				} else {
					wrap.appendChild(innerEl);
				}
			}
			var bandEl = innerEl.querySelector('.thespl-infotext-band');
			if (!bandEl) {
				bandEl = document.createElement('span');
				bandEl.className = 'thespl-infotext-band';
				if (bandEl.style) {
					bandEl.style.display = 'inline-block';
					bandEl.style.whiteSpace = 'nowrap';
					bandEl.style.maxWidth = 'none';
				}
				innerEl.appendChild(bandEl);
			}
			var gapEl = bandEl.querySelector('.thespl-infotext-gap');
			if (!gapEl) {
				gapEl = document.createElement('span');
				gapEl.className = 'thespl-infotext-gap';
				gapEl.textContent = '\u00a0\u00a0\u00a0';
				bandEl.appendChild(gapEl);
			}
			var bandCloneEl = innerEl.querySelector('.thespl-infotext-band-clone');
			if (!bandCloneEl) {
				bandCloneEl = document.createElement('span');
				bandCloneEl.className = 'thespl-infotext-band thespl-infotext-band-clone';
				if (bandCloneEl.style) {
					bandCloneEl.style.display = 'inline-block';
					bandCloneEl.style.whiteSpace = 'nowrap';
					bandCloneEl.style.maxWidth = 'none';
				}
				innerEl.appendChild(bandCloneEl);
			}
			var textEl = bandEl.querySelector('.thespl-infotext-text');
			if (!textEl) {
				textEl = document.createElement('span');
				textEl.className = 'thespl-infotext-text';
				try {
					if (textEl.style) {
						textEl.style.display = 'inline-block';
						textEl.style.whiteSpace = 'nowrap';
						textEl.style.maxWidth = 'none';
						textEl.style.overflow = 'visible';
						textEl.style.animation = 'none';
					}
				} catch (e) {}
				bandEl.appendChild(textEl);
			}
			var linkEl = bandEl.querySelector('.thespl-infotext-link');
			if (!linkEl) {
				linkEl = document.createElement('a');
				linkEl.className = 'thespl-infotext-link';
				linkEl.target = '_blank';
				linkEl.rel = 'noopener noreferrer';
				bandEl.appendChild(linkEl);
			}
			var trailingEl = bandEl.querySelector('.thespl-infotext-tail');
			if (!trailingEl) {
				trailingEl = document.createElement('span');
				trailingEl.className = 'thespl-infotext-tail';
				bandEl.appendChild(trailingEl);
			}
			var debugEl = null;
			var debugAttr = '';
			try {
				if (root && root.getAttribute) {
					debugAttr = root.getAttribute('data-debug') || '';
				}
			} catch (e) {}
			if (debugAttr === '1') {
				debugEl = wrap.querySelector('.thespl-infotext-debug');
				if (!debugEl) {
					debugEl = document.createElement('div');
					debugEl.className = 'thespl-infotext-debug';
					if (debugEl.style) {
						debugEl.style.fontSize = '10px';
						debugEl.style.opacity = '0.8';
						debugEl.style.marginTop = '2px';
						debugEl.style.color = '#f20000';
						debugEl.style.textAlign = 'left';
					}
					wrap.appendChild(debugEl);
				}
			}
			var lastTrackIndex = null;
			var lastVariantIndex = null;
			var overrideText = '';
			var overrideUntil = 0;
			var rotationIndex = 0;
			var lastRotationTime = 0;
			var rotationIntervalMs = 1000;
			var overrideDurationMs = 6000;
			var scrollDelayMs = 2000;
			var scrollSpeedPxPerSec = 20;
			var scrollRampDurationMs = 5000;
			var scrollState = {
				active: false,
				rafId: 0,
				offset: 0,
				delayRemaining: 0,
				gapWidth: 0,
				rampElapsed: 0
			};
			var overlayActive = false;
			var lastRenderedState = {
				text: '',
				linkText: '',
				linkHref: '',
				tail: ''
			};
			var pendingRenderState = null;
			var getMeta = function(){
				var playlist = {};
				try {
					if (typeof store.getPlaylist === 'function') {
						playlist = store.getPlaylist(root) || {};
					}
				} catch (e) {}
				var tracks = Array.isArray(playlist.tracks) ? playlist.tracks : [];
				var sel = {};
				try {
					if (typeof store.getSelection === 'function') {
						sel = store.getSelection(root) || {};
					}
				} catch (e) {}
				var trackIndex = Number.isFinite(sel.trackIndex) ? sel.trackIndex : (Number.isFinite(playlist.currentTrackIndex) ? playlist.currentTrackIndex : 0);
				var variantIndex = Number.isFinite(sel.variantIndex) ? sel.variantIndex : (Number.isFinite(playlist.currentVariantIndex) ? playlist.currentVariantIndex : 0);
				if (!Number.isFinite(trackIndex)) {
					trackIndex = 0;
				}
				if (!Number.isFinite(variantIndex)) {
					variantIndex = 0;
				}
				if (trackIndex < 0 || trackIndex >= tracks.length) {
					trackIndex = 0;
				}
				var t = tracks[trackIndex] || {};
				var variants = Array.isArray(t.variants) ? t.variants : [];
				var infos = [];
				if (Array.isArray(t.variant_info)) {
					infos = t.variant_info;
				} else if (Array.isArray(t.variantInfo)) {
					infos = t.variantInfo;
				}
				if (variantIndex < 0 || variantIndex >= variants.length) {
					variantIndex = 0;
				}
				var title = typeof t.title === 'string' ? t.title : '';
				var artist = typeof t.artist === 'string' ? t.artist : '';
				var credits = typeof t.credits === 'string' ? t.credits : '';
				var social = typeof t.social === 'string' ? t.social : '';
				var variantLabel = variants[variantIndex] || '';
				var variantNote = infos[variantIndex] || '';
				return {
					trackIndex: trackIndex,
					variantIndex: variantIndex,
					title: title,
					artist: artist,
					credits: credits,
					social: social,
					variantLabel: variantLabel,
					variantNote: variantNote
				};
			};
			var buildItems = function(meta){
				var items = [];
				if (!meta || typeof meta !== 'object') {
					return items;
				}
				var artist = typeof meta.artist === 'string' ? meta.artist : '';
				var credits = typeof meta.credits === 'string' ? meta.credits : '';
				var social = typeof meta.social === 'string' ? meta.social : '';
				if (artist) {
					items.push({ type: 'artist', text: artist });
				}
				if (social) {
					items.push({ type: 'social', text: social });
				}
				if (credits) {
					items.push({ type: 'credits', text: credits });
				}
				return items;
			};
			var parseSocialLink = function(raw){
				var href = typeof raw === 'string' ? raw : '';
				href = href.trim();
				if (!href.length) return null;
				if (!/^[a-z][a-z0-9+\-.]*:\/\//i.test(href)) {
					href = (href.indexOf('//') === 0 ? 'https:' : 'https://') + href;
				}
				var label = href;
				try {
					var urlObj = new URL(href);
					label = urlObj.hostname || href;
				} catch (e) {
					label = href.replace(/^[a-z][a-z0-9+\-.]*:\/\//i, '');
					var slashIndex = label.indexOf('/');
					if (slashIndex !== -1) label = label.substring(0, slashIndex);
				}
				if (label.indexOf('www.') === 0) label = label.substring(4);
				return { href: href, label: label };
			};
			var buildVariantString = function(meta){
				var base = meta && typeof meta.variantLabel === 'string' ? meta.variantLabel : '';
				var note = meta && typeof meta.variantNote === 'string' ? meta.variantNote : '';
				var headphones = '';
				try {
					if (root && root.getAttribute && root.getAttribute('data-binaural-status') === '1') {
						headphones = getStatusText(root, 'binaural', 'Binaural audio - use headphones');
					}
				} catch (e) {}
				var mainText = note || '';
				return {
					main: mainText,
					base: base,
					note: note,
					headphones: headphones
				};
			};
			var updateScrollLogic = function(){
				var needScroll = false;
				var rawNeedScroll = false;
				var wrapWidth = 0;
				var bandWidth = 0;
				try {
					if (wrap && wrap.classList) {
						wrap.classList.remove('thespl-infotext--scroll');
					}
					if (wrap) {
						wrapWidth = wrap.clientWidth || 0;
					}
					if (bandEl) {
						bandWidth = bandEl.scrollWidth || 0;
					}
					if (wrapWidth && bandWidth && bandWidth > wrapWidth + 1) {
						needScroll = true;
					}
				} catch (e) {}
				try {
					if (bandCloneEl && bandEl && needScroll) {
						bandCloneEl.innerHTML = '';
						var cloneChild = bandEl.cloneNode(true);
						bandCloneEl.appendChild(cloneChild);
						scrollState.gapWidth = 0;
					} else if (bandCloneEl && !needScroll) {
						bandCloneEl.innerHTML = '';
						scrollState.gapWidth = 0;
					}
				} catch (e) {}
				rawNeedScroll = needScroll;
				if (needScroll) {
					try {
						if (wrap && wrap.classList) {
							wrap.classList.add('thespl-infotext--scroll');
						}
					} catch (e) {}
					if (wrap && innerEl && !scrollState.active) {
						scrollState.active = true;
						scrollState.offset = 0;
						scrollState.rampElapsed = 0;
						var maxOffset = 0;
						if (bandWidth && bandWidth > wrapWidth) {
							maxOffset = bandWidth;
						}
						var lastTs = 0;
						var step = function(ts){
							if (!scrollState.active || !wrap) {
								scrollState.rafId = 0;
								return;
							}
							if (!lastTs) {
								lastTs = ts;
							}
							var dt = ts - lastTs;
							if (dt > 100) {
								dt = 100;
							}
							lastTs = ts;
							if (scrollState.delayRemaining > 0) {
								scrollState.delayRemaining -= dt;
								if (scrollState.delayRemaining < 0) {
									scrollState.delayRemaining = 0;
								}
								scrollState.offset = 0;
								if (innerEl && innerEl.style) {
									innerEl.style.transform = 'translateX(0px)';
								}
								scrollState.rafId = window.requestAnimationFrame(step);
								return;
							}
							if (!maxOffset || maxOffset <= 0) {
								scrollState.active = false;
								scrollState.rafId = 0;
								return;
							}
							if (scrollRampDurationMs > 0) {
								scrollState.rampElapsed += dt;
								if (scrollState.rampElapsed < 0) {
									scrollState.rampElapsed = 0;
								}
								if (scrollState.rampElapsed > scrollRampDurationMs) {
									scrollState.rampElapsed = scrollRampDurationMs;
								}
							}
							var rampFactor = 1;
							if (scrollRampDurationMs > 0 && scrollState.rampElapsed < scrollRampDurationMs) {
								var t = scrollState.rampElapsed / scrollRampDurationMs;
								rampFactor = t * t;
							}
							var effSpeed = scrollSpeedPxPerSec * rampFactor;
							var delta = (effSpeed * dt) / 1000;
							try {
								var next = scrollState.offset + delta;
								if (maxOffset > 0 && next >= maxOffset) {
									next = next - maxOffset;
								}
								scrollState.offset = next;
								if (innerEl && innerEl.style) {
									if (!overlayActive) {
										innerEl.style.transform = 'translate3d(' + (-scrollState.offset) + 'px,0,0)';
									}
								}
							} catch (e) {}
							scrollState.rafId = window.requestAnimationFrame(step);
						};
						scrollState.rafId = window.requestAnimationFrame(step);
					}
				} else {
					try {
						if (innerEl && innerEl.style && !overlayActive) {
							innerEl.style.transform = 'translate3d(0,0,0)';
						}
					} catch (e) {}
				}
				var hasContent = !!(lastRenderedState.text && lastRenderedState.text.length) || (lastRenderedState.linkHref && lastRenderedState.linkHref.length);
				try {
					var statusShell = root.querySelector('.thespl-player__status');
					var hasStatus = false;
					try {
						if (root && root.getAttribute) {
							hasStatus = root.getAttribute('data-thespl-display-status') === '1';
						}
					} catch (e) {}
					if (!hasStatus && statusShell && statusShell._text && typeof statusShell._text.textContent === 'string') {
						if (statusShell._text.textContent.length > 0) {
							hasStatus = true;
						}
					}
					if (statusShell && statusShell.style) {
						statusShell.style.visibility = (hasStatus || hasContent) ? 'visible' : 'hidden';
					}
				} catch (e) {}
			};
			var clearInfotext = function(){
				try {
					if (textEl) {
						textEl.textContent = '';
					}
					if (linkEl) {
						linkEl.textContent = '';
						linkEl.removeAttribute('href');
						linkEl.style.display = 'none';
					}
					if (trailingEl) {
						trailingEl.textContent = '';
					}
					lastRenderedState = {
						text: '',
						linkText: '',
						linkHref: '',
						tail: ''
					};
					pendingRenderState = null;
					overrideText = '';
					overrideUntil = 0;
					overlayActive = false;
					if (wrap && wrap.classList) {
						wrap.classList.remove('thespl-infotext--scroll');
					}
					scrollState.active = false;
					if (scrollState.rafId) {
						try {
							window.cancelAnimationFrame(scrollState.rafId);
						} catch (e) {}
						scrollState.rafId = 0;
					}
					scrollState.offset = 0;
					scrollState.delayRemaining = 0;
					if (innerEl && innerEl.style) {
						innerEl.style.transform = 'translateX(0px)';
					}
				} catch (e) {}
			};
			var render = function(){
				if (!root || !textEl) {
					return;
				}
				var state = null;
				if (window.THESPL_Player_Store && typeof window.THESPL_Player_Store.getUiState === 'function') {
					try {
						state = window.THESPL_Player_Store.getUiState(root) || {};
					} catch (e) {}
				}
				var now = Date.now();
				if (state && typeof state === 'object') {
					var phase = '';
					if (typeof state.uiPhase === 'string' && state.uiPhase.length) {
						phase = state.uiPhase;
					} else if (typeof state.phase === 'string' && state.phase.length) {
						phase = state.phase;
					}
					var hasError = typeof state.error === 'string' && state.error.length > 0;
					var hasPlayedOnce = !!state.hasPlayedOnce;
					var overlayRequested = false;
					try {
						if (root && root._thesplVariantClicked && overrideText && overrideText.length && overrideUntil > now) {
							overlayRequested = true;
						}
					} catch (e) {}
					if (!overlayRequested) {
						if (!hasPlayedOnce && !hasError) {
							clearInfotext();
							return;
						}
						if (hasError || phase === 'buffering') {
							clearInfotext();
							return;
						}
					}
				}
				var meta = getMeta();
				var isNewTrack = lastTrackIndex === null || meta.trackIndex !== lastTrackIndex;
				var isNewVariant = lastVariantIndex === null || meta.variantIndex !== lastVariantIndex;
				if (isNewTrack || isNewVariant) {
					lastTrackIndex = meta.trackIndex;
					lastVariantIndex = meta.variantIndex;
					if (isNewTrack) {
						if (scrollState.active && scrollState.rafId) {
							try {
								window.cancelAnimationFrame(scrollState.rafId);
							} catch (e) {}
							scrollState.rafId = 0;
						}
						scrollState.active = false;
						scrollState.offset = 0;
						scrollState.delayRemaining = scrollDelayMs;
						try {
							if (innerEl && innerEl.style) {
								innerEl.style.transform = 'translateX(0px)';
							}
						} catch (e) {}
					}
					var vinfo = buildVariantString(meta);
					var vs = vinfo && typeof vinfo.main === 'string' ? vinfo.main : '';
					if (vs && vs.length) {
						overrideText = vs;
						overrideUntil = now + overrideDurationMs;
					} else {
						overrideText = '';
						overrideUntil = 0;
					}
					rotationIndex = 0;
					lastRotationTime = now;
				}
				var mode = 'scroll';
				try {
					if (root && root.getAttribute) {
						var attrMode = root.getAttribute('data-thespl-infotext-mode') || '';
						if (attrMode === 'scroll') {
							mode = 'scroll';
						}
					}
				} catch (e) {}
				var allowVariantOverlay = false;
				try {
					if (root && root._thesplVariantClicked) {
						allowVariantOverlay = true;
					}
				} catch (e) {}
				var nextText = '';
				var nextLinkText = '';
				var nextLinkHref = '';
				var nextTail = '';
				if (allowVariantOverlay && overrideText && overrideText.length && now < overrideUntil) {
					overlayActive = true;
					try {
						if (innerEl && innerEl.style) {
							innerEl.style.transform = 'translateX(0px)';
						}
					} catch (e) {}
					var vinfoActive = buildVariantString(meta);
					var mainText = vinfoActive && typeof vinfoActive.main === 'string' ? vinfoActive.main : overrideText;
					nextText = mainText || '';
				} else {
					overlayActive = false;
					var items = buildItems(meta);
					if (items.length) {
						if (!lastRotationTime) {
							lastRotationTime = now;
						}
						if (mode === 'scroll') {
							var artistText = '';
							var creditsText = '';
							var socialItem = null;
							for (var i = 0; i < items.length; i++) {
								var it = items[i];
								if (!it || typeof it.text !== 'string' || !it.text.length) {
									continue;
								}
								if (it.type === 'artist') {
									artistText = it.text;
								} else if (it.type === 'credits') {
									creditsText = it.text;
								} else if (it.type === 'social') {
									socialItem = it;
								}
							}
							nextText = artistText || '';
							if (socialItem && typeof socialItem.text === 'string' && socialItem.text.length) {
								var parsed = parseSocialLink(socialItem.text);
								if (parsed && parsed.href) {
									nextLinkText = parsed.label;
									nextLinkHref = parsed.href;
									if (nextText) {
										nextText = nextText + '\u00a0|\u00a0';
									}
								}
							}
							if (creditsText) {
								nextTail = creditsText;
								if (nextText || nextLinkText) {
									nextTail = ' | ' + nextTail;
								}
							}
							rotationIndex = 0;
							lastRotationTime = now;
						} else {
							if (now - lastRotationTime >= rotationIntervalMs) {
								rotationIndex++;
								if (rotationIndex >= items.length) {
									rotationIndex = 0;
								}
								lastRotationTime = now;
							}
							var current = items[rotationIndex] || {};
							if (current && current.type === 'social') {
								var parsed = parseSocialLink(current.text);
								if (parsed && parsed.href) {
									nextLinkText = parsed.label;
									nextLinkHref = parsed.href;
								}
							} else if (current && typeof current.text === 'string') {
								nextText = current.text;
							}
						}
					} else {
						rotationIndex = 0;
						lastRotationTime = now;
					}
				}
				var compareState = pendingRenderState || lastRenderedState;
				var changed = (nextText !== compareState.text) || 
							  (nextLinkText !== compareState.linkText) ||
							  (nextLinkHref !== compareState.linkHref) ||
							  (nextTail !== compareState.tail);
				if (!changed) {
					updateScrollLogic();
					return;
				}
				pendingRenderState = {
					text: nextText,
					linkText: nextLinkText,
					linkHref: nextLinkHref,
					tail: nextTail
				};
				var applyToDom = function(){
					textEl.textContent = nextText;
					if (linkEl) {
						linkEl.textContent = nextLinkText;
						if (nextLinkHref) {
							linkEl.href = nextLinkHref;
							linkEl.style.display = 'inline';
							try {
								if (linkEl.style) linkEl.style.fontWeight = '600';
							} catch (e) {}
						} else {
							linkEl.removeAttribute('href');
							linkEl.style.display = 'none';
						}
					}
					if (trailingEl) {
						trailingEl.textContent = nextTail;
					}
					lastRenderedState = {
						text: nextText,
						linkText: nextLinkText,
						linkHref: nextLinkHref,
						tail: nextTail
					};
					pendingRenderState = null;
					updateScrollLogic();
				};
				if (innerEl && innerEl.style) {
					var fadeOut = fadeDurations.outMs;
					var fadeIn = fadeDurations.inMs;
					innerEl.style.transition = 'opacity ' + fadeOut + 'ms ease';
					innerEl.style.opacity = '0';
					if (innerEl._thesplFadeTimer) clearTimeout(innerEl._thesplFadeTimer);
					innerEl._thesplFadeTimer = setTimeout(function(){
						applyToDom();
						innerEl.style.transition = 'opacity ' + fadeIn + 'ms ease';
						window.requestAnimationFrame(function(){
							innerEl.style.opacity = '1';
							innerEl._thesplFadeTimer = null;
						});
					}, fadeOut);
				} else {
					applyToDom();
				}
			};
			var renderScheduled = false;
			var scheduleRender = function(){
				if (renderScheduled) {
					return;
				}
				renderScheduled = true;
				try {
					window.requestAnimationFrame(function(){
						renderScheduled = false;
						try {
							render();
						} catch (e) {}
					});
				} catch (e) {
					renderScheduled = false;
					try {
						render();
					} catch (e2) {}
				}
			};
			var unsubscribe = function(){};
			try {
				if (typeof store.subscribe === 'function') {
					unsubscribe = store.subscribe(root, scheduleRender);
				}
			} catch (e) {}
				try {
					root.setAttribute('data-thespl-infotext-bound', '1');
				} catch (e) {}
				try {
					scheduleRender();
				} catch (e) {}
			return function(){
				try {
					unsubscribe();
				} catch (e) {}
				if (scrollState.active && scrollState.rafId) {
					try {
						window.cancelAnimationFrame(scrollState.rafId);
					} catch (e) {}
				}
				scrollState.active = false;
				scrollState.rafId = 0;
			};
		},
		bindVariants: function(root, api){
			if (!root) return function(){};
			var instance = null;
			var getApi = function(){
				if (instance) return instance;
				try {
					instance = api || root._thesplPlayerApi || null;
				} catch (e) {}
				return instance;
			};
			var wrap = root.querySelector('.thespl-player__variants');
			if (!wrap) return function(){};
			var bound = [];
			var bindIndex = function(el, index){
				if (!el) return;
				var onClick = function(){
					var inst = getApi();
					if (!inst || typeof inst.selectVariant !== 'function') return;
					try {
						inst.selectVariant(index);
					} catch (e) {}
					try {
						root._thesplVariantClicked = true;
					} catch (e) {}
					try {
						if (root && root.classList && root.classList.contains('thespl-player')) {
						}
					} catch (e) {}
				};
				el.addEventListener('click', onClick);
				bound.push({ el: el, onClick: onClick });
			};
			var nodes = wrap.querySelectorAll('.thespl-player__variant');
			nodes.forEach(function(el, index){
				bindIndex(el, index);
			});
			return function(){
				for (var i = 0; i < bound.length; i++) {
					var b = bound[i];
					try {
						b.el.removeEventListener('click', b.onClick);
					} catch (e) {}
				}
				bound = [];
				instance = null;
			};
		},
		showBinauralStatus: function(root, durationMs){
			triggerBinauralStatus(root, durationMs);
		},
		bindTransport: function(root, api){
			if (!root) return function(){};
			var instance = null;
			var getApi = function(){
				if (instance) return instance;
				try {
					instance = api || root._thesplPlayerApi || null;
				} catch (e) {}
				return instance;
			};
			var bound = [];
			var bindBtn = function(selector, method){
				var el = root.querySelector(selector);
				if (!el) return;
				var onClick = function(){
					var inst = getApi();
					if (!inst || typeof inst[method] !== 'function') return;
					try {
						inst[method]();
					} catch (e) {}
				};
				var onKey = function(e){
					var key = e && e.key;
					if (key === 'Enter' || key === ' ') {
						e.preventDefault();
						onClick();
					}
				};
				el.addEventListener('click', onClick);
				el.addEventListener('keydown', onKey);
				bound.push({ el: el, onClick: onClick, onKey: onKey });
			};
			bindBtn('.thespl-player__btn--play', 'play');
			bindBtn('.thespl-player__btn--pause', 'pause');
			bindBtn('.thespl-player__btn--stop', 'stop');
			bindBtn('.thespl-player__btn--toggle', 'toggle');
			return function(){
				for (var i = 0; i < bound.length; i++) {
					var b = bound[i];
					try {
						b.el.removeEventListener('click', b.onClick);
						b.el.removeEventListener('keydown', b.onKey);
					} catch (e) {}
				}
				bound = [];
				instance = null;
			};
		}
	};
	var existing = window.THESPL_Player_UI || {};
	for (var key in UI) {
		if (Object.prototype.hasOwnProperty.call(UI, key) && typeof existing[key] === 'undefined') {
			existing[key] = UI[key];
		}
	}
	window.THESPL_Player_UI = existing;
})();
