(function () {
	try {
			// Initialize the design preview UI for the current playlist post.
			var cfg           = window.thesplPreviewConfig || {};
			var pid           = cfg.postId || 0;
			
			// Debug: Check if config and postId are available
			if ( ! cfg || pid === 0) {
				console.warn('THESPL Design: Config or postId not available', {cfg: cfg, pid: pid});
				return;
			}
		var w             = document.getElementById( 'thespl-preview-wrap-' + pid );
		var panel         = document.getElementById( 'thespl-design-panel-' + pid );
		
		// Debug: Check if panel element exists
		if ( ! panel) {
			console.warn('THESPL Design: Panel element not found', 'thespl-design-panel-' + pid);
			return;
		}
		var accent        = document.getElementById( 'thespl-design-accent-' + pid );
		var wf            = document.getElementById( 'thespl-design-waveform-' + pid );
		var ring          = document.getElementById( 'thespl-design-ring-' + pid );
		var bufferAlpha   = document.getElementById( 'thespl-design-buffer-alpha-' + pid );
		var accent2       = document.getElementById( 'thespl-design-accent2-' + pid );
		var base          = document.getElementById( 'thespl-design-base-' + pid );
		var text          = document.getElementById( 'thespl-design-text-' + pid );
		var btnBg         = document.getElementById( 'thespl-design-button-bg-' + pid );
		var btnText       = document.getElementById( 'thespl-design-button-text-' + pid );
		var btnActiveBg   = document.getElementById( 'thespl-design-button-active-bg-' + pid );
		var btnActiveText = document.getElementById( 'thespl-design-button-active-text-' + pid );
		var chipBg        = document.getElementById( 'thespl-design-chip-bg-' + pid );
		var chipBr        = document.getElementById( 'thespl-design-chip-br-' + pid );
		var showPl        = document.getElementById( 'thespl-design-show-playlist-' + pid );
		var showInfo      = document.getElementById( 'thespl-design-show-info-' + pid );
		var reset         = (panel ? panel.querySelector( '[data-thespl-reset="1"]' ) : null);
		var magicBtn      = document.getElementById( 'thespl-magic-btn-' + pid );
		var magicPageBg   = document.getElementById( 'thespl-magic-page-bg-' + pid );
		var magicPageText = document.getElementById( 'thespl-magic-page-text-' + pid );
		var magicAccent1  = document.getElementById( 'thespl-magic-accent1-' + pid );
		var magicAccent2  = document.getElementById( 'thespl-magic-accent2-' + pid );
		var containerMax  = document.getElementById( 'thespl-design-container-max-' + pid );
		var debugPanel    = document.getElementById( 'thespl-design-debug-' + pid );
		var debugToggle   = document.getElementById( 'thespl-design-debug-toggle-' + pid );
		var magicStatus   = document.getElementById( 'thespl-magic-status-' + pid );
		var lockToggle    = document.getElementById( 'thespl-design-lock-toggle-' + pid );
		var lockState     = document.getElementById( 'thespl-design-lock-state-' + pid );
		var lockInput     = document.getElementById( 'thespl-design-lock-input-' + pid );
		var lockOverlay   = panel ? panel.querySelector( '.thespl-design-panel__lock-overlay' ) : null;
		if ( ! w || ! panel) {
			return;}

		var labelExpand   = 'Expand';
		var labelCollapse = 'Collapse';
		var lockLabelLock = (window.thesplDesignI18n && window.thesplDesignI18n.lockLabelLock) ? String( window.thesplDesignI18n.lockLabelLock ) : 'Lock design';
		var lockLabelUnlock = (window.thesplDesignI18n && window.thesplDesignI18n.lockLabelUnlock) ? String( window.thesplDesignI18n.lockLabelUnlock ) : 'Unlock design';
		var lockStatusLocked = (window.thesplDesignI18n && window.thesplDesignI18n.lockStatusLocked) ? String( window.thesplDesignI18n.lockStatusLocked ) : 'Design changes are locked.';
		var lockStatusUnlocked = (window.thesplDesignI18n && window.thesplDesignI18n.lockStatusUnlocked) ? String( window.thesplDesignI18n.lockStatusUnlocked ) : 'Design changes are unlocked.';
		var initializedAttr = panel ? String( panel.getAttribute( 'data-thespl-design-initialized' ) || '0' ) : '0';
		var unlockUntilAttr = panel ? parseInt( String( panel.getAttribute( 'data-thespl-design-unlock-until' ) || '0' ),10 ) : 0;
		var nowAttr         = panel ? parseInt( String( panel.getAttribute( 'data-thespl-now' ) || '0' ),10 ) : 0;
		var initMetaAttr    = panel ? String( panel.getAttribute( 'data-thespl-design-init-meta' ) || '0' ) : '0';
		var designInitialized = initializedAttr === '1';
		var designUnlockUntil = Number.isFinite( unlockUntilAttr ) ? unlockUntilAttr : 0;
		var designNow         = Number.isFinite( nowAttr ) ? nowAttr : 0;
		var designInitMetaSet = initMetaAttr === '1';
		var designLocked      = false;
		if (designInitMetaSet && designInitialized) {
			if (designUnlockUntil === 0) {
				designLocked = true;
			} else if (designUnlockUntil > 0 && designNow > designUnlockUntil) {
				designLocked = true;
			}
		}
		var tplSel                   = document.querySelector( 'select[name="thespl_playlist_template"]' );
		var userControls             = panel ? panel.querySelector( '[data-thespl-user-css-controls="1"]' ) : null;
		var userNote                 = panel ? panel.querySelector( '[data-thespl-user-css-note="1"]' ) : null;
		var audioInfoWrap            = panel ? panel.querySelector( '[data-thespl-audio-info-label-default]' ) : null;
		var audioInfoLabelSpan       = audioInfoWrap ? audioInfoWrap.querySelector( '[data-thespl-audio-info-label-text="1"]' ) : null;
		var templatesCfg             = cfg && cfg.templates && typeof cfg.templates === 'object' ? cfg.templates : {};
		var getCurrentTemplateSlug   = function () {
			try {
				if (tplSel && tplSel.value) {
					return String( tplSel.value );
				}
			} catch (e) {
			}
			return String( cfg && cfg.currentTemplate ? cfg.currentTemplate : '' );
		};
		var getFullSchemaForCurrentTemplate = function () {
			try {
				var slug = getCurrentTemplateSlug();
				if ( ! slug || ! templatesCfg) {
					return null;
				}
				var sch = templatesCfg[slug];
				if ( ! sch || typeof sch !== 'object') {
					return null;
				}
				return sch;
			} catch (e) {
				return null;
			}
		};
		var initialSchema            = getFullSchemaForCurrentTemplate();
		if (initialSchema && initialSchema.flags) {
			try {
				if (showPl && typeof initialSchema.flags.show_playlist !== 'undefined') {
					showPl.checked = initialSchema.flags.show_playlist ? true : false;
				}
				if (showInfo && typeof initialSchema.flags.show_audio_info !== 'undefined') {
					showInfo.checked = initialSchema.flags.show_audio_info ? true : false;
				}
			} catch (e) {
			}
		}
		if (initialSchema && initialSchema.lock && typeof initialSchema.lock.locked !== 'undefined') {
			try {
				designLocked = initialSchema.lock.locked ? true : false;
			} catch (e) {
			}
		}
		// Determine whether the current template allows user CSS overrides.
		var getAllowFromSelect       = function () {
			try {
				if ( ! tplSel || ! tplSel.options || tplSel.selectedIndex < 0) {
					return true;}
				var opt = tplSel.options[tplSel.selectedIndex];
				if ( ! opt) {
					return true;}
				return String( opt.getAttribute( 'data-thespl-allow-user-css-overrides' ) || '1' ) !== '0';
			} catch (e) {
				return true;}
		};
		// Enable or dim user CSS fields depending on template support.
		var applyUserCssAvailability = function () {
			try {
				var allow = getAllowFromSelect();
				if (userNote) {
					userNote.style.display = allow ? 'none' : 'block';}
				if (userControls) {
					userControls.style.opacity = allow ? '1' : '0.6';
					var els                    = userControls.querySelectorAll( 'input, button, select, textarea' );
					for (var i = 0;i < els.length;i++) {
						try {
							els[i].disabled = ! allow;} catch (e) {
							}
					}
					try {
						var reasonTxt = '';
						try {
							var uc    = panel ? panel.querySelector( '.thespl-user-css' ) : null;
							reasonTxt = String( (uc && uc.getAttribute( 'data-thespl-user-css-reason' )) || '' );
							if ( ! reasonTxt && userNote) {
								reasonTxt = String( userNote.textContent || '' );}
						} catch (e) {
						}
						for (var j = 0;j < els.length;j++) {
							try {
								els[j].title = allow ? '' : reasonTxt;} catch (e) {
								}
						}
					} catch (e) {
					}
				}
				try {
					var uc = panel ? panel.querySelector( '.thespl-user-css' ) : null;
					if (uc) {
						uc.classList.toggle( 'is-user-css-disabled', ! allow );}
				} catch (e) {
				}
			} catch (e) {
			}
		};
		var getAudioInfoPanelSupportFromSelect = function () {
			try {
				if ( ! tplSel || ! tplSel.options || tplSel.selectedIndex < 0) {
					return true;
				}
				var opt = tplSel.options[tplSel.selectedIndex];
				if ( ! opt) {
					return true;
				}
				return String( opt.getAttribute( 'data-thespl-has-audio-info-panel' ) || '1' ) !== '0';
			} catch (e) {
				return true;
			}
		};
		var applyAudioInfoAvailability        = function () {
			try {
				if ( ! showInfo) {
					return;
				}
				if (designLocked) {
					try {
						showInfo.disabled = true;
					} catch (e) {
					}
					return;
				}
				var supports = getAudioInfoPanelSupportFromSelect();
				var lblDefault = audioInfoWrap ? String( audioInfoWrap.getAttribute( 'data-thespl-audio-info-label-default' ) || '' ) : '';
				var lblMissing = audioInfoWrap ? String( audioInfoWrap.getAttribute( 'data-thespl-audio-info-label-missing' ) || '' ) : '';
				if ( ! supports) {
					try {
						showInfo.checked = false;
					} catch (e) {
					}
				}
				try {
					showInfo.disabled = ! supports;
				} catch (e) {
				}
				if (audioInfoLabelSpan) {
					try {
						if ( ! supports && lblMissing) {
							audioInfoLabelSpan.textContent = lblMissing;
						} else if (lblDefault) {
							audioInfoLabelSpan.textContent = lblDefault;
						}
					} catch (e) {
					}
				}
			} catch (e) {
			}
		};
		var applyDesignLockState = function () {
			try {
				var isLocked = !! designLocked;
				try {
					panel.classList.toggle( 'is-design-locked',isLocked );
				} catch (e) {
				}
				if (lockOverlay) {
					try {
						lockOverlay.setAttribute( 'aria-hidden',isLocked ? 'false' : 'true' );
					} catch (e) {
					}
				}
				if (lockState) {
					try {
						lockState.textContent = isLocked ? lockStatusLocked : lockStatusUnlocked;
					} catch (e) {
					}
				}
				if (lockToggle) {
					try {
						lockToggle.textContent = isLocked ? lockLabelUnlock : lockLabelLock;
						lockToggle.setAttribute( 'aria-pressed',isLocked ? 'false' : 'true' );
					} catch (e) {
					}
				}
				if (lockInput) {
					try {
						lockInput.value = isLocked ? 'locked' : 'unlocked';
					} catch (e) {
					}
				}
				var lockables = panel.querySelectorAll( '.thespl-design-panel__lock-scope input, .thespl-design-panel__lock-scope button, .thespl-design-panel__lock-scope select, .thespl-design-panel__lock-scope textarea' );
				for (var lk = 0;lk < lockables.length;lk++) {
					try {
						if (String( lockables[lk].type || '' ).toLowerCase() === 'hidden') {
							continue;
						}
						lockables[lk].disabled = isLocked;
					} catch (e) {
					}
				}
				if ( ! isLocked ) {
					applyUserCssAvailability();
					applyAudioInfoAvailability();
				}
			} catch (e) {
			}
		};
		if (tplSel) {
			tplSel.addEventListener(
				'change',
				function () {
					try {
						var schema = getFullSchemaForCurrentTemplate();
						if (schema && schema.lock && typeof schema.lock.locked !== 'undefined') {
							designLocked = schema.lock.locked ? true : false;
						}
						if (schema && schema.flags) {
							if (showPl && typeof schema.flags.show_playlist !== 'undefined') {
								showPl.checked = schema.flags.show_playlist ? true : false;
							}
							if (showInfo && typeof schema.flags.show_audio_info !== 'undefined') {
								showInfo.checked = schema.flags.show_audio_info ? true : false;
							}
						}
					} catch (e) {
					}
					applyUserCssAvailability();
					applyDesignLockState();
					applyAudioInfoAvailability();
					try {
						if (typeof applyVisibility === 'function') {
							applyVisibility();
						}
					} catch (e) {
					}
				}
			);}
		applyUserCssAvailability();
		applyDesignLockState();
		if (lockToggle) {
			lockToggle.addEventListener(
				'click',
				function () {
					designLocked = ! designLocked;
					applyDesignLockState();
				}
			);
		}
		// Hide the debug panel by default; it is toggled via the Magic button or the toggle.
		if (debugPanel) {
			try {
				debugPanel.style.display = 'none';} catch (e) {
				}
		}
		var magicLabelIdle      = magicBtn ? String( magicBtn.getAttribute( 'data-thespl-label-idle' ) || magicBtn.textContent || '' ) : '';
		var magicLabelBusy      = magicBtn ? String( magicBtn.getAttribute( 'data-thespl-label-busy' ) || magicLabelIdle || '' ) : '';
		var magicStatusSuccess  = magicBtn ? String( magicBtn.getAttribute( 'data-thespl-status-success' ) || '' ) : '';
		var magicStatusError    = magicBtn ? String( magicBtn.getAttribute( 'data-thespl-status-error' ) || '' ) : '';
		var setMagicState       = function (isBusy) {
			try {
				if ( ! magicBtn) {
					return;}
				if (isBusy) {
					magicBtn.disabled = true;
					magicBtn.classList.add( 'disabled' );
					magicBtn.classList.add( 'thespl-magic-btn--busy' );
					if (magicLabelBusy) {
						magicBtn.textContent = magicLabelBusy;}
				} else {
					magicBtn.disabled = !! designLocked;
					magicBtn.classList.remove( 'disabled' );
					magicBtn.classList.remove( 'thespl-magic-btn--busy' );
					if (magicLabelIdle) {
						magicBtn.textContent = magicLabelIdle;}
				}
			} catch (e) {
			}
		};
		var showMagicStatus     = function (msg,isError) {
			try {
				if ( ! magicStatus) {
					return;}
				magicStatus.textContent = String( msg || '' );
				magicStatus.classList.remove( 'thespl-magic-status--error' );
				magicStatus.classList.remove( 'thespl-magic-status--ok' );
				if (msg) {
					if (isError) {
						magicStatus.classList.add( 'thespl-magic-status--error' );
					} else {
						magicStatus.classList.add( 'thespl-magic-status--ok' );
					}
				}
			} catch (e) {
			}
		};
		var highlightField      = function (input) {
			try {
				if ( ! input) {
					return;}
				var node    = input.parentNode;
				var wrapper = null;
				while (node) {
					if (node.classList && node.classList.contains( 'thespl-color-field' )) {
						wrapper = node;
						break;
					}
					node = node.parentNode;
				}
				if ( ! wrapper) {
					return;}
				wrapper.classList.add( 'thespl-color-field--magic-updated' );
				setTimeout(
					function () {
						try {
							wrapper.classList.remove( 'thespl-color-field--magic-updated' );
						} catch (e) {
						}
					},
					1500
				);
			} catch (e) {
			}
		};
		// Escape text for safe HTML output in the debug panel.
		var escHtml             = function (v) {
			try {
				var s = String( v == null ? '' : v );
				return s.replace( /[&<>\"]/g,function (ch) {if (ch === '&') {return '&amp;';}if (ch === '<') {return '&lt;';}if (ch === '>') {return '&gt;';}if (ch === '"') {return '&quot;';}return ch;} );} catch (e) {
				return '';
			}
		};
		// Normalize potential color strings to a safe HEX value or empty string.
		var safeColor           = function (v) {
			try {
				var s = String( v || '' ).trim();
				if (/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test( s )) {
					return s;}
				return '';} catch (e) {
				return '';
			}
		};
		// Render a detailed theme color analysis panel from server-provided data.
		var renderDebug         = function (sources,tokens) {
			try {
				if ( ! debugPanel || ! sources) {
					return;}
				var html    = '';
				var gs      = sources.global_styles || {};
				var gp      = sources.global_palette || {};
				var custom  = sources.customizer || {};
				var theme   = sources.theme || {};
				var classic = sources.classic_css_probe || {};
				var cssTop  = sources.css_top_colors || {};
				var resolved = sources.resolved || {};
				var pipeline = sources.pipeline || [];
				var inputs   = sources.inputs || {};
				var hasAny  = false;
				html += '<div class="thespl-design-debug__header">';
				html += '<div class="thespl-design-debug__title">Palette analysis</div>';
				html += '<div class="thespl-design-debug__hint">Base colors, generator pipeline and player tokens.</div>';
				html += '</div>';
				html += '<div class="thespl-design-debug__grid">';
				var addColor = function (label,val,section) {
					try {
						var c = safeColor( val );
						var sec = section ? String( section ) : '';
						if ( ! c && ! String( val || '' )) {
							return;}
						hasAny = true;
						html += '<div class="thespl-design-debug__item">';
						html += '<span class="thespl-design-debug__label">' + escHtml( label ) + (sec ? ' (' + escHtml( sec ) + ')' : '') + '</span>';
						if (c) {
							html += '<span class="thespl-design-debug__swatch" style="background:' + escHtml( c ) + '"></span>';
						}
						html += '<span class="thespl-design-debug__value">' + escHtml( c || String( val || '' ) ) + '</span>';
						html += '</div>'; } catch (e) {
					}
				};
				var addText = function (label,val,section) {
					try {
						if (val === undefined || val === null || String( val ) === '') {
							return;}
						hasAny = true;
						var sec = section ? String( section ) : '';
						html += '<div class="thespl-design-debug__item">';
						html += '<span class="thespl-design-debug__label">' + escHtml( label ) + (sec ? ' (' + escHtml( sec ) + ')' : '') + '</span>';
						html += '<span class="thespl-design-debug__value">' + escHtml( String( val ) ) + '</span>';
						html += '</div>'; } catch (e) {
					}
				};
				if (inputs) {
					addColor( 'Input page background',inputs.page_bg || '','Inputs' );
					addColor( 'Input page text',inputs.page_text || '','Inputs' );
					addColor( 'Input accent 1',inputs.accent_1 || '','Inputs' );
					addColor( 'Input accent 2',inputs.accent_2 || '','Inputs' );
				}
				if (pipeline && Object.prototype.toString.call( pipeline ) === '[object Array]' && pipeline.length) {
					for (var pi = 0;pi < pipeline.length;pi++) {
						try {
							var st = pipeline[pi] || {};
							var stepName = st.step || ('step ' + String( pi + 1 ));
							var status = st.status || '';
							var parts = [];
							if (st.bg) {
								parts.push( 'bg: ' + String( st.bg ) );}
							if (st.text) {
								parts.push( 'text: ' + String( st.text ) );}
							if (st.accent) {
								parts.push( 'accent: ' + String( st.accent ) );}
							var summary = '';
							if (status) {
								summary = 'status: ' + String( status );
								if (parts.length) {
									summary += ' | ';
								}
							}
							if (parts.length) {
								summary += parts.join( ', ' );
							}
							if (summary) {
								addText( 'Step ' + String( pi + 1 ) + ' – ' + stepName,summary,'Pipeline' );
							}
						} catch (e) {
						}
					}
				}
				if (gs && (gs.background || gs.text || gs.link)) {
					addColor( 'Background',gs.background,'Global Styles' );
					addColor( 'Text',gs.text,'Global Styles' );
					addColor( 'Link',gs.link,'Global Styles' );}
			if (gp && gp.palette) {
				var preferredSlug = gp.preferred_slug || '';
				var preferredHex  = gp.preferred_hex || '';
				if (preferredSlug || preferredHex) {
					addColor( 'Preferred accent',preferredHex || '',preferredSlug || 'palette' );}
				var pal = gp.palette;
				if (pal && typeof pal === 'object') {
					for (var slug in pal) {
						if (Object.prototype.hasOwnProperty.call( pal,slug )) {
							addColor( slug,pal[slug],'Global palette' );}
					}
				}
			}
				if (custom && (custom.background_color_raw || custom.header_textcolor_raw)) {
					addText( 'Customizer background',custom.background_color_raw,'Customizer' );
					addText( 'Customizer header text',custom.header_textcolor_raw,'Customizer' );}
				if (custom && custom.derived) {
					var d = custom.derived;
					if (d.bg && d.bg.length) {
						for (var i = 0;i < d.bg.length;i++) {
							addColor( 'Customizer BG',d.bg[i],'Customizer derived' );
						}
					}
					if (d.text && d.text.length) {
						for (var j = 0;j < d.text.length;j++) {
							addColor( 'Customizer text',d.text[j],'Customizer derived' );
						}
					}
					if (d.accent && d.accent.length) {
						for (var k = 0;k < d.accent.length;k++) {
							addColor( 'Customizer accent',d.accent[k],'Customizer derived' );
						}
					}
				}
			if (theme && theme.name) {
				addText( 'Theme',theme.name,'Theme' );}
			if (theme && theme.stylesheet) {
				addText( 'Stylesheet',theme.stylesheet,'Theme' );}
			if (theme && typeof theme.is_block_theme !== 'undefined') {
				addText( 'Block theme',theme.is_block_theme ? 'yes' : 'no','Theme' );}
				if (classic && (classic.bg || classic.text || classic.link)) {
					addColor( 'CSS background',classic.bg,'Classic CSS' );
					addColor( 'CSS text',classic.text,'Classic CSS' );
					addColor( 'CSS link',classic.link,'Classic CSS' );}
				if (cssTop && cssTop.colors) {
					var topColors = cssTop.colors;
					for (var hex in topColors) {
						if (Object.prototype.hasOwnProperty.call( topColors,hex )) {
							addColor( 'CSS color',hex,'CSS top colors x' + String( topColors[hex] ) );
						}
					}
					if (cssTop.bg_candidate) {
						addColor( 'CSS BG candidate',cssTop.bg_candidate,'CSS top colors' );
					}
				}
				if (tokens || resolved) {
					var r = resolved || {};
					var tk = tokens || {};
					addColor( 'Player background',r.bg || tk.bg || '','Player tokens' );
					addColor( 'Player text',r.text || tk.text || '','Player tokens' );
					addColor( 'Player accent',r.accent || tk.accent || '','Player tokens' );
					addColor( 'Player accent 2',r.accent_2 || tk.accent_2 || '','Player tokens' );
					addColor( 'Player waveform',r.waveform || tk.waveform || '','Player tokens' );}
				html += '</div>';
				if ( ! hasAny) {
					html += '<div class="thespl-design-debug__hint">No theme color data available yet.</div>';}
				debugPanel.innerHTML = html;
			} catch (e) {
			}
		};
		var detectPageBackground = function () {
			try {
				var doc       = window.document;
				var candidates = [];
				if ( doc && doc.body ) {
					candidates.push( doc.body );
				}
				if ( doc && doc.documentElement && doc.documentElement !== doc.body ) {
					candidates.push( doc.documentElement );
				}
				if ( w && w.parentNode && w.parentNode.nodeType === 1 ) {
					candidates.push( w.parentNode );
				}
				var color = '';
				for ( var i = 0;i < candidates.length;i++ ) {
					var el = candidates[i];
					try {
						var cs = window.getComputedStyle ? window.getComputedStyle( el ) : null;
						var bg = cs ? (cs.backgroundColor || cs.background || '') : '';
						if ( ! bg ) {
							continue;
						}
						if ( bg === 'transparent' || bg === 'rgba(0, 0, 0, 0)' || bg === 'rgba(0,0,0,0)' ) {
							continue;
						}
						color = bg;
						break;
					} catch (e) {}
				}
				if ( ! color ) {
					return '';
				}
				if ( color[0] === '#' ) {
					return safeColor( color );
				}
				var m = color.match( /rgba?\((\d+)[^\d]+(\d+)[^\d]+(\d+)/i );
				if ( ! m ) {
					return '';
				}
				var r = parseInt( m[1],10 ) || 0;
				var g = parseInt( m[2],10 ) || 0;
				var b = parseInt( m[3],10 ) || 0;
				return rgbToHex( [r,g,b] );
			} catch (e) {
				return '';
			}
		};
		if (debugToggle && debugPanel) {
			try {
				debugToggle.addEventListener(
					'click',
					function () {
						try {
							var expanded = String( debugToggle.getAttribute( 'aria-expanded' ) || 'false' ) === 'true';
							var next     = ! expanded;
							debugToggle.setAttribute( 'aria-expanded',next ? 'true' : 'false' );
							debugPanel.setAttribute( 'aria-hidden',next ? 'false' : 'true' );
							debugPanel.style.display = next ? 'block' : 'none';
						} catch (e) {
						}
					}
				);
			} catch (e) {
			}
		}
		// Store a named theme token as a simple string value.
		var setTheme            = function (k,v) {
			// Deprecated: legacy theme store is no longer used by the player.
		};
		// Convert a HEX color string into an [r,g,b] array.
		var hexToRgb            = function (h) {
			try {
						var s = String( h || '' ).trim().replace( '#','' );if ( ! s) {
					return null;}if (s.length === 3) {
							var r = parseInt( s[0] + s[0],16 ),g = parseInt( s[1] + s[1],16 ),b = parseInt( s[2] + s[2],16 );return [r,g,b];}if (s.length === 6) {
						var r = parseInt( s.slice( 0,2 ),16 ),g = parseInt( s.slice( 2,4 ),16 ),b = parseInt( s.slice( 4,6 ),16 );return [r,g,b];}return null;} catch (e) {
				return null;}};
		// Convert an [r,g,b] triplet into a normalized 6-digit HEX color.
		var rgbToHex            = function (rgb) {
			try {
				if ( ! rgb || rgb.length !== 3) {
					return '';}var r = Math.max( 0,Math.min( 255,parseInt( rgb[0],10 ) || 0 ) );var g = Math.max( 0,Math.min( 255,parseInt( rgb[1],10 ) || 0 ) );var b = Math.max( 0,Math.min( 255,parseInt( rgb[2],10 ) || 0 ) );var h = function (n) {
							var s = n.toString( 16 );return s.length === 1 ? '0' + s : s;};return '#' + h( r ) + h( g ) + h( b );} catch (e) {
				return '';}};
		// Mix two HEX colors using linear interpolation (t between 0 and 1).
		var mixHex              = function (a,b,t) {
			try {
						var ar = hexToRgb( a ),br = hexToRgb( b );var tt = Math.max( 0,Math.min( 1,Number( t ) ) );if ( ! ar || ! br) {
					return '';}return rgbToHex( [Math.round( ar[0] * (1 - tt) + br[0] * tt ),Math.round( ar[1] * (1 - tt) + br[1] * tt ),Math.round( ar[2] * (1 - tt) + br[2] * tt )] );} catch (e) {
				return '';} };
		// Normalize arbitrary color strings (including rgba()) into HEX for native inputs.
		// If the input is controlled by wpColorPicker, use its API to update the UI and trigger change events.
		var normalizeColorInput = function (input,val) {
			try {
				if ( ! input) {
					return;
				}
				var s = String( val || '' ).trim();
				if ( ! s) {
					return;
				}
				var finalHex = s;
				// Convert rgba to hex if necessary
				if (s[0] !== '#') {
					var m = s.match( /rgba?\((\d+)[^\d]+(\d+)[^\d]+(\d+)/i );
					if (m) {
						var r = parseInt( m[1],10 ) || 0;
						var g = parseInt( m[2],10 ) || 0;
						var b = parseInt( m[3],10 ) || 0;
						finalHex = rgbToHex( [r,g,b] );
					}
				}
				
				// Try to update via wpColorPicker API first
				var $ = window.jQuery;
				var updated = false;

				if ($ && $.fn.wpColorPicker) {
					// 1. Try updating the input directly
					try {
						var $inp = $(input);
						if ($inp.closest('.wp-picker-container').length || $inp.hasClass('wp-color-picker')) {
							$inp.wpColorPicker('color', finalHex);
							updated = true;
						}
					} catch (e) {}

					// 2. Try updating the associated -text input (common WP pattern)
					if (!updated && input.id) {
						try {
							var textId = input.id + '-text';
							var textInput = document.getElementById(textId);
							if (textInput) {
								var $textInp = $(textInput);
								if ($textInp.closest('.wp-picker-container').length || $textInp.hasClass('wp-color-picker')) {
									$textInp.wpColorPicker('color', finalHex);
									updated = true;
								}
							}
						} catch (e) {}
					}
				}

				// 3. FORCE VISUAL UPDATE: Manually color the swatch if API failed or as backup
				try {
					var $container = $(input).closest('.wp-picker-container');
					if ($container.length === 0 && input.id) {
						var textId = input.id + '-text';
						var textInput = document.getElementById(textId);
						if (textInput) {
							$container = $(textInput).closest('.wp-picker-container');
						}
					}
					if ($container.length) {
						$container.find('.wp-color-result').css('background-color', finalHex);
						$container.find('.wp-color-picker').val(finalHex); // Update the hidden input used by iris
					}
				} catch (e) {}

				// Always fallback to updating the input value manually to ensure
				// the data is present even if the picker UI update failed silently.
				// This also ensures the change event is fired if the picker didn't fire it.
				if (input.value !== finalHex) {
					input.value = finalHex;
					input.dispatchEvent( new Event( 'input',{ bubbles: true } ) );
					input.dispatchEvent( new Event( 'change',{ bubbles: true } ) );
				}
			} catch (e) {
			}
		};
		// Approximate relative luminance for a HEX color.
		var lumaHex             = function (h) {
			try {
						var rgb = hexToRgb( h );if ( ! rgb) {
					return 0.0;}var r = rgb[0] / 255,g = rgb[1] / 255,b = rgb[2] / 255;return 0.2126 * r + 0.7152 * g + 0.0722 * b;} catch (e) {
				return 0.0;}};
		// Choose dark or light text color depending on background luminance.
		var bestTextOnBg        = function (bg) {
			try {
						return lumaHex( bg ) > 0.56 ? '#111111' : '#ffffff';} catch (e) {
					return '#ffffff';}};
		// Derive buffered ring color from accent and alpha and expose it via CSS variable.
		var applyBufferTheme   = function () {
			try {
				var acc = accent ? String( accent.value || '' ) : '';
				var alpha = bufferAlpha ? parseFloat( bufferAlpha.value ) : NaN;
				if (isNaN( alpha )) {
					alpha = 0.3;
				}
				if (alpha < 0) {
					alpha = 0.0;
				} else if (alpha > 1) {
					alpha = 1.0;
				}
				var alphaStr = alpha.toFixed( 3 );
				var rgba = 'rgba(180,230,255,' + alphaStr + ')';
				var rgb = acc ? hexToRgb( acc ) : null;
				if (rgb && rgb.length === 3) {
					rgba = 'rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',' + alphaStr + ')';
				}
				setCssVar( '--thespl-buffered',String( rgba || '' ) );
			} catch (e) {
			}
		};
		// Resolve the inner player element inside the preview wrapper.
		var getPlayer           = function () {
			try {
						return w.querySelector( '.thespl-player' );} catch (e) {
					return null;}};
		// Apply a CSS custom property both on the wrapper and the player.
		var setCssVar           = function (name,val) {
			try {
				w.style.setProperty( String( name || '' ),String( val || '' ) );} catch (e) {
				}
				var p = getPlayer();
				if (p) {
					try {
						p.style.setProperty( String( name || '' ),String( val || '' ) );} catch (e) {
						}}
		};
		// Derive related text colors (muted, panel) from the main text color.
		var applyTextVars       = function (hex) {
			try {
				var h = String( hex || '' );
				setCssVar( '--thespl-text',h );
				var rgb = hexToRgb( h );
				if (rgb && rgb.length === 3) {
					setCssVar( '--thespl-muted','rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',0.7)' );
					setCssVar( '--thespl-panel-bg','rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',0.05)' );
					setCssVar( '--thespl-panel-br','rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',0.12)' );
				}
			} catch (e) {
			}
		};
		var openPreviewAudioInfo = function () {
			var player = getPlayer();
			if ( ! player) {
				return;
			}
			if (player.classList.contains( 'thespl-hide-audio-info' ) || w.classList.contains( 'thespl-hide-audio-info' )) {
				return;
			}
			var tryOpen = function (attempt) {
				var currentPlayer = getPlayer();
				if ( ! currentPlayer) {
					return;
				}
				if (currentPlayer.classList.contains( 'thespl-hide-audio-info' ) || w.classList.contains( 'thespl-hide-audio-info' )) {
					return;
				}
				var bt    = currentPlayer.querySelector( '.thespl-player__audio-info-toggle' );
				var panel = currentPlayer.querySelector( '.thespl-player__audio-info-panel' );
				if ( ! bt || ! panel) {
					if (attempt < 4) {
						window.setTimeout(
							function () {
								tryOpen( attempt + 1 );
							},
							80
						);
					}
					return;
				}
				if (bt.getAttribute( 'aria-expanded' ) !== 'true') {
					try {
						bt.click();
					} catch (e) {
					}
				}
				if (panel.classList.contains( 'is-collapsed' ) && attempt < 4) {
					window.setTimeout(
						function () {
							tryOpen( attempt + 1 );
						},
						80
					);
				}
			};
			tryOpen( 0 );
		};
		// Show or hide playlist and track info sections based on checkboxes.
		var applyVisibility     = function () {
			var clsPl   = 'thespl-hide-playlist';
			var clsInfo = 'thespl-hide-audio-info';
			var player  = getPlayer();
			var hidePl  = showPl ? ! showPl.checked : false;
			var hideInfo = showInfo ? ! showInfo.checked : false;
			if (showPl) {
				w.classList.toggle( clsPl, hidePl );
				if (player) {
					player.classList.toggle( clsPl, hidePl );
				}
			}
			if (showInfo) {
				w.classList.toggle( clsInfo, hideInfo );
				if (player) {
					player.classList.toggle( clsInfo, hideInfo );
				}
				if ( ! hideInfo) {
					openPreviewAudioInfo();
				}
			}
		};
		if (accent) {
			accent.addEventListener(
				'input',
				function () {
						setTheme( 'progress',accent.value );setCssVar( '--thespl-accent',String( accent.value || '' ) );applyBufferTheme();try {
						var t = document.getElementById( accent.id + '-text' );if (t) {
								t.value = accent.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( accent.id ) + '"]' ) : null;if (sw) {
								sw.style.background = accent.value;}} catch (e) {
							}
				}
			);
		}
		if (bufferAlpha) {
			bufferAlpha.addEventListener(
				'input',
				function () {
					applyBufferTheme();
				}
			);
		}
		if (wf) {
			wf.addEventListener(
				'input',
				function () {
						setTheme( 'waveform',wf.value );setCssVar( '--thespl-waveform',String( wf.value || '' ) );setCssVar( '--thespl-wave',String( wf.value || '' ) );try {
						var t = document.getElementById( wf.id + '-text' );if (t) {
								t.value = wf.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( wf.id ) + '"]' ) : null;if (sw) {
								sw.style.background = wf.value;}} catch (e) {
							}
				}
			);
		}
		if (ring) {
			ring.addEventListener(
				'input',
				function () {
						setTheme( 'ringBase',ring.value );setCssVar( '--thespl-ring-base',String( ring.value || '' ) );try {
						var t = document.getElementById( ring.id + '-text' );if (t) {
								t.value = ring.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( ring.id ) + '"]' ) : null;if (sw) {
								sw.style.background = ring.value;}} catch (e) {
							}
				}
			);
		}
		if (accent2) {
			accent2.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-accent-2',String( accent2.value || '' ) );try {
						var t = document.getElementById( accent2.id + '-text' );if (t) {
								t.value = accent2.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( accent2.id ) + '"]' ) : null;if (sw) {
								sw.style.background = accent2.value;}} catch (e) {
							}
				}
			);
		}
		if (base) {
			base.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-bg',String( base.value || '' ) );try {
						var t = document.getElementById( base.id + '-text' );if (t) {
								t.value = base.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( base.id ) + '"]' ) : null;if (sw) {
								sw.style.background = base.value;}} catch (e) {
							}
				}
			);
		}
		if (text) {
			text.addEventListener(
				'input',
				function () {
						applyTextVars( text.value );try {
						var t = document.getElementById( text.id + '-text' );if (t) {
								t.value = text.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( text.id ) + '"]' ) : null;if (sw) {
								sw.style.background = text.value;}} catch (e) {
							}
				}
			);
		}
		if (btnBg) {
			btnBg.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-button-bg',String( btnBg.value || '' ) );try {
						var t = document.getElementById( btnBg.id + '-text' );if (t) {
								t.value = btnBg.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( btnBg.id ) + '"]' ) : null;if (sw) {
								sw.style.background = btnBg.value;}} catch (e) {
							}
				}
			);
		}
		if (btnText) {
			btnText.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-button-text',String( btnText.value || '' ) );try {
						var t = document.getElementById( btnText.id + '-text' );if (t) {
								t.value = btnText.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( btnText.id ) + '"]' ) : null;if (sw) {
								sw.style.background = btnText.value;}} catch (e) {
							}
				}
			);
		}
		if (btnActiveBg) {
			btnActiveBg.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-button-active-bg',String( btnActiveBg.value || '' ) );try {
						var t = document.getElementById( btnActiveBg.id + '-text' );if (t) {
								t.value = btnActiveBg.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( btnActiveBg.id ) + '"]' ) : null;if (sw) {
								sw.style.background = btnActiveBg.value;}} catch (e) {
							}
				}
			);
		}
		if (btnActiveText) {
			btnActiveText.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-button-active-text',String( btnActiveText.value || '' ) );try {
						var t = document.getElementById( btnActiveText.id + '-text' );if (t) {
														t.value = btnActiveText.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( btnActiveText.id ) + '"]' ) : null;if (sw) {
								sw.style.background = btnActiveText.value;}} catch (e) {
							}
				}
			);
		}
		if (chipBg) {
			chipBg.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-chip-bg',String( chipBg.value || '' ) );try {
						var t = document.getElementById( chipBg.id + '-text' );if (t) {
								t.value = chipBg.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( chipBg.id ) + '"]' ) : null;if (sw) {
								sw.style.background = chipBg.value;}} catch (e) {
							}
				}
			);
		}
		if (chipBr) {
			chipBr.addEventListener(
				'input',
				function () {
						setCssVar( '--thespl-chip-br',String( chipBr.value || '' ) );try {
						var t = document.getElementById( chipBr.id + '-text' );if (t) {
								t.value = chipBr.value;}var sw = panel ? panel.querySelector( '.thespl-swatch[data-swatch-for="' + String( chipBr.id ) + '"]' ) : null;if (sw) {
								sw.style.background = chipBr.value;}} catch (e) {
							}
				}
			);
		}
		if (showPl) {
			showPl.addEventListener( 'change',applyVisibility );}
		if (showInfo) {
			showInfo.addEventListener( 'change',applyVisibility );}
		applyVisibility();
		applyAudioInfoAvailability();
		if (window.MutationObserver) {
			try {
				var thesplPreviewObserver = new MutationObserver(
					function () {
						applyVisibility();
					}
				);
				thesplPreviewObserver.observe(
					w,
					{
						childList: true,
						subtree: true
					}
				);
			} catch (e) {
			}
		}
		applyBufferTheme();
		if (accent) {
			setCssVar( '--thespl-accent',String( accent.value || '' ) );}
		if (wf) {
			setCssVar( '--thespl-waveform',String( wf.value || '' ) );setCssVar( '--thespl-wave',String( wf.value || '' ) );}
		if (ring) {
			setCssVar( '--thespl-ring-base',String( ring.value || '' ) );}
		if (accent2) {
			setCssVar( '--thespl-accent-2',String( accent2.value || '' ) );}
		if (base) {
			setCssVar( '--thespl-bg',String( base.value || '' ) );}
		if (text) {
			applyTextVars( String( text.value || '' ) );}
		if (btnBg) {
			setCssVar( '--thespl-button-bg',String( btnBg.value || '' ) );}
		if (btnText) {
			setCssVar( '--thespl-button-text',String( btnText.value || '' ) );}
		if (btnActiveBg) {
			setCssVar( '--thespl-button-active-bg',String( btnActiveBg.value || '' ) );}
		if (btnActiveText) {
			setCssVar( '--thespl-button-active-text',String( btnActiveText.value || '' ) );}
		if (chipBg) {
			setCssVar( '--thespl-chip-bg',String( chipBg.value || '' ) );}
		if (chipBr) {
			setCssVar( '--thespl-chip-br',String( chipBr.value || '' ) );}
		if (reset) {
			reset.addEventListener(
				'click',
				function () {
					try {
						try {
							if (typeof window.thesplDesignI18n === 'object' && window.thesplDesignI18n) {
								var title   = String( window.thesplDesignI18n.confirmResetTitle || '' );
								var message = String( window.thesplDesignI18n.confirmResetMessage || '' );
								var full    = title ? title + '\n\n' + message : message;
								if (full) {
									if (! window.confirm( full )) {
										return;
									}
								}
							} else {
								if (! window.confirm( 'Reset design to template defaults? Unsaved changes will be lost.' )) {
									return;
								}
							}
						} catch (e) {}
						var schema = getFullSchemaForCurrentTemplate();
						var defs = schema && schema.template_meta && schema.template_meta.defaults ? schema.template_meta.defaults : null;
						var colors = defs && defs.colors && typeof defs.colors === 'object' ? defs.colors : null;
						var defAccent = colors && colors.accent_color ? String( colors.accent_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-accent' ) || '' ) : '');
						var defAccent2 = colors && colors.accent_2_color ? String( colors.accent_2_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-accent2' ) || '' ) : '');
						var defBase = colors && colors.base_color ? String( colors.base_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-base' ) || '' ) : '');
						var defText = colors && colors.text_color ? String( colors.text_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-text' ) || '' ) : '');
						var defWf = colors && colors.waveform_color ? String( colors.waveform_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-waveform' ) || '' ) : '');
						var defRing = colors && colors.ring_base_color ? String( colors.ring_base_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-ring' ) || '' ) : '');
						var defBtnBg = colors && colors.button_bg_color ? String( colors.button_bg_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-btn-bg' ) || '' ) : '');
						var defBtnText = colors && colors.button_text_color ? String( colors.button_text_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-btn-text' ) || '' ) : '');
						var defBtnActiveBg = colors && colors.button_active_bg_color ? String( colors.button_active_bg_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-btn-active-bg' ) || '' ) : '');
						var defBtnActiveText = colors && colors.button_active_text_color ? String( colors.button_active_text_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-btn-active-text' ) || '' ) : '');
						var defChipBg = colors && colors.chip_bg_color ? String( colors.chip_bg_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-chip-bg' ) || '' ) : '');
						var defChipBr = colors && colors.chip_br_color ? String( colors.chip_br_color || '' ) : (w && w.getAttribute ? String( w.getAttribute( 'data-thespl-default-chip-br' ) || '' ) : '');
						if (accent && defAccent) {
							normalizeColorInput( accent,defAccent );
						}
						if (wf && defWf) {
							normalizeColorInput( wf,defWf );
						}
						if (ring && defRing) {
							normalizeColorInput( ring,defRing );
						}
						if (accent2 && defAccent2) {
							normalizeColorInput( accent2,defAccent2 );
						}
						if (base && defBase) {
							normalizeColorInput( base,defBase );
						}
						if (text && defText) {
							normalizeColorInput( text,defText );
						}
						if (btnBg) {
							if (defBtnBg) {
								normalizeColorInput( btnBg,defBtnBg );
							} else if (defBase && defAccent) {
								normalizeColorInput( btnBg,mixHex( defBase,defAccent,0.15 ) || btnBg.value );
							}
						}
						if (btnText) {
							if (defBtnText) {
								normalizeColorInput( btnText,defBtnText );
							} else if (btnBg) {
								normalizeColorInput( btnText,bestTextOnBg( btnBg.value ) );
							}
						}
						if (btnActiveBg) {
							if (defBtnActiveBg) {
								normalizeColorInput( btnActiveBg,defBtnActiveBg );
							} else if (defAccent) {
								normalizeColorInput( btnActiveBg,defAccent );
							}
						}
						if (btnActiveText) {
							if (defBtnActiveText) {
								normalizeColorInput( btnActiveText,defBtnActiveText );
							} else if (btnActiveBg) {
								normalizeColorInput( btnActiveText,bestTextOnBg( btnActiveBg.value ) );
							}
						}
						if (chipBg) {
							if (defChipBg) {
								normalizeColorInput( chipBg,defChipBg );
							} else if (defBase) {
								normalizeColorInput( chipBg,mixHex( defBase,'#ffffff',0.06 ) || chipBg.value );
							}
						}
						if (chipBr) {
							if (defChipBr) {
								normalizeColorInput( chipBr,defChipBr );
							} else if (defBase) {
								normalizeColorInput( chipBr,mixHex( defBase,'#ffffff',0.12 ) || chipBr.value );
							}
						}
						try {
							var magicBg = defBase ? defBase : '';
							var magicText = defText ? defText : '';
							var magicAcc1 = defAccent ? defAccent : '';
							var magicAcc2 = defAccent2 ? defAccent2 : '';
							if ( magicPageBg && magicBg ) {
								normalizeColorInput( magicPageBg,magicBg );
							}
							if ( magicPageText && magicText ) {
								normalizeColorInput( magicPageText,magicText );
							}
							if ( magicAccent1 && magicAcc1 ) {
								normalizeColorInput( magicAccent1,magicAcc1 );
							}
							if ( magicAccent2 && magicAcc2 ) {
								normalizeColorInput( magicAccent2,magicAcc2 );
							}
						} catch (e) {}
						refreshColorPickerPalettes();
						if (bufferAlpha && defs && typeof defs.buffer_ring_alpha === 'number') {
							try {
								bufferAlpha.value = String( defs.buffer_ring_alpha );
							} catch (e) {
							}
						}
						applyBufferTheme();
					} catch (e) {}
				}
			);
		}
		// Open the native WordPress color picker for the given field ID.
		var openColorPicker = function (id) {
			try {
					var baseId    = String( id || '' );
					var textInput = document.getElementById( baseId + '-text' );
					var baseInput = document.getElementById( baseId );
					var target    = baseInput || textInput; if ( ! target) {
						return;}
					if (window.jQuery && window.jQuery.fn && window.jQuery.fn.wpColorPicker && textInput) {
					try {
						var $ = window.jQuery;
						var $input = $( textInput );
							var $container = $input.closest( '.wp-picker-container' );
							var $button = $container && $container.length ? $container.find( '.wp-color-result' ) : null;
							if ($button && $button.length) {
								$button.trigger( 'click' );
								return;
							}
							$input.trigger( 'click' );
						} catch (e) {
						}
						return;
					}
					if (typeof target.click === 'function') {
						target.click();
					}
			} catch (e) {
			}
		};
		// Attach click handlers to our small swatch elements to focus the picker field.
		try {
			var swatches = panel.querySelectorAll( '.thespl-swatch' );
			for (var i = 0;i < swatches.length;i++) {
				try {
					swatches[i].addEventListener(
						'click',
						function (ev) {
									var t = ev.currentTarget;var forId = t.getAttribute( 'data-swatch-for' );openColorPicker( forId );}
					);} catch (e) {
					}
			}
		} catch (e) {
		}
		// Keep manual HEX text inputs in sync with the underlying color pickers.
		var bindColorSync = function (textId,hiddenInput,onValid) {
			try {
				var txt = document.getElementById( String( textId || '' ) );
				if ( ! txt || ! hiddenInput) {
					return;
				}
				// 1. When Hidden Input changes (Source of Truth), update Text + Run Logic
				var syncFromTruth = function () {
					try {
						var v = String( hiddenInput.value || '' ).trim();
						// Update text input if different
						if (txt.value !== v) {
							// Set flag to prevent syncFromText from firing back
							txt.setAttribute('data-syncing', 'true');
							txt.value = v;
							// Clear flag after short delay to be safe
							setTimeout(function() { txt.removeAttribute('data-syncing'); }, 0);
						}
						// Run Logic (Preview updates)
						if (typeof onValid === 'function') {
							onValid( v );
						}
					} catch (e) {
					}
				};
				hiddenInput.addEventListener( 'input',syncFromTruth );
				hiddenInput.addEventListener( 'change',syncFromTruth );

				// 2. When Text Input changes (User manual entry), push to Truth
				var syncFromText = function () {
					try {
						// Prevent recursion if this change was triggered by syncFromTruth
						if (txt.getAttribute('data-syncing') === 'true') {
							return;
						}

						var v = String( txt.value || '' ).trim();
						if ( ! v) {
							return;
						}
						if (v[0] !== '#') {
							v = '#' + v;
						}
						// Check if value actually changed to avoid redundant updates
						if (hiddenInput.value === v) {
							return;
						}

						// Update hidden input immediately to break potential recursion loops
						// before calling normalizeColorInput which might trigger events back
						hiddenInput.value = v;
						// Dispatch input event to ensure other listeners (like preview updates) run
						hiddenInput.dispatchEvent(new Event('input', {bubbles: true}));

						// Now update the picker visual state
						normalizeColorInput( hiddenInput,v );
					} catch (e) {
					}
				};
				txt.addEventListener( 'input',syncFromText );
				txt.addEventListener( 'change',syncFromText );
			} catch (e) {
			}
		};
		var buildPalettesFromInputs = function () {
			var out = [];
			var add = function (val) {
				try {
					var c = safeColor( val );
					if ( ! c) {
						return;}
					if (out.indexOf( c ) === -1) {
						out.push( c );}
				} catch (e) {
				}
			};
			try {
				if (accent && accent.value) {
					add( accent.value );}
			} catch (e) {
			}
			try {
				if (accent2 && accent2.value) {
					add( accent2.value );}
			} catch (e) {
			}
			try {
				if (base && base.value) {
					add( base.value );}
			} catch (e) {
			}
			try {
				if (text && text.value) {
					add( text.value );}
			} catch (e) {
			}
			try {
				if (wf && wf.value) {
					add( wf.value );}
			} catch (e) {
			}
			try {
				if (ring && ring.value) {
					add( ring.value );}
			} catch (e) {
			}
			try {
				if (btnBg && btnBg.value) {
					add( btnBg.value );}
			} catch (e) {
			}
			try {
				if (btnText && btnText.value) {
					add( btnText.value );}
			} catch (e) {
			}
			try {
				if (btnActiveBg && btnActiveBg.value) {
					add( btnActiveBg.value );}
			} catch (e) {
			}
			try {
				if (btnActiveText && btnActiveText.value) {
					add( btnActiveText.value );}
			} catch (e) {
			}
			try {
				if (chipBg && chipBg.value) {
					add( chipBg.value );}
			} catch (e) {
			}
			try {
				if (chipBr && chipBr.value) {
					add( chipBr.value );}
			} catch (e) {
			}
			try {
				if (magicPageBg && magicPageBg.value) {
					add( magicPageBg.value );}
			} catch (e) {
			}
			try {
				if (magicPageText && magicPageText.value) {
					add( magicPageText.value );}
			} catch (e) {
			}
			try {
				if (magicAccent1 && magicAccent1.value) {
					add( magicAccent1.value );}
			} catch (e) {
			}
			try {
				if (magicAccent2 && magicAccent2.value) {
					add( magicAccent2.value );}
			} catch (e) {
			}
			return out;
		};
		var initWpColorPicker = function () {
			try {
				if ( ! window.jQuery || ! window.jQuery.fn || ! window.jQuery.fn.wpColorPicker ) {
					setTimeout( initWpColorPicker,100 );
					return;
				}
				if ( ! panel) {
					return;
				}
				var $            = window.jQuery;
				var basePalettes = [];
				try {
					if (cfg && cfg.palettes && Object.prototype.toString.call( cfg.palettes ) === '[object Array]') {
						for (var j = 0;j < cfg.palettes.length;j++) {
							var pv = safeColor( cfg.palettes[j] );
							if (pv && basePalettes.indexOf( pv ) === -1) {
								basePalettes.push( pv );
							}
						}
					}
				} catch (e) {
				}
				try {
					var dyn = buildPalettesFromInputs();
					if (dyn && Object.prototype.toString.call( dyn ) === '[object Array]') {
						for (var dj = 0;dj < dyn.length;dj++) {
							var dv = safeColor( dyn[dj] );
							if (dv && basePalettes.indexOf( dv ) === -1) {
								basePalettes.push( dv );
							}
						}
					}
				} catch (e) {
				}
				if (basePalettes.length > 6) {
					basePalettes = basePalettes.slice( 0,6 );
				}
				var meta        = cfg && cfg.paletteMeta && typeof cfg.paletteMeta === 'object' ? cfg.paletteMeta : {};
				var inputs      = panel.querySelectorAll( '.thespl-color-field input[type="text"]' );
				var applyPicker = function (input) {
					$( input ).wpColorPicker(
						{
							change: function (event,ui) {
								try {
									var v = ui && ui.color && typeof ui.color.toString === 'function' ? ui.color.toString() : String( input.value || '' );
									input.value = v;
									var ev;
									if (typeof Event === 'function') {
										ev = new Event( 'input',{bubbles:true} );
									} else {
										ev = document.createEvent( 'Event' );
										ev.initEvent( 'input',true,true );
									}
									input.dispatchEvent( ev );
								} catch (e) {
								}
							},
							clear: function () {
								try {
									var ev;
									if (typeof Event === 'function') {
										ev = new Event( 'input',{bubbles:true} );
									} else {
										ev = document.createEvent( 'Event' );
										ev.initEvent( 'input',true,true );
									}
									input.dispatchEvent( ev );
								} catch (e) {
								}
							},
							palettes: basePalettes,
						}
					);
				};
				for (var i = 0;i < inputs.length;i++) {
					(function (input) {
						applyPicker( input );
						try {
							var $container = $( input ).closest( '.wp-picker-container' );
							var $palEls    = $container.find( '.iris-palette' );
							$palEls.each(
								function (idx,el) {
									try {
										var hex  = basePalettes[idx] || '';
										var key  = safeColor( hex );
										var label = '';
										if (key && meta && meta[key] && Object.prototype.toString.call( meta[key] ) === '[object Array]' && meta[key].length) {
											label = 'Debug source: ' + meta[key].join( ' | ' ) + ' (' + key + ')';
										} else if (key) {
											label = 'Debug source: ' + key;
										} else {
											label = 'Debug source';
										}
										el.setAttribute( 'title',label );
										el.setAttribute( 'data-thespl-debug-source',label );
									} catch (e) {
									}
								}
							);
						} catch (e) {
						}
					})( inputs[i] );
				}
				var magicInputs = panel.querySelectorAll( '.thespl-magic-inputs .thespl-magic-color' );
				for (var mi = 0;mi < magicInputs.length;mi++) {
					try {
						applyPicker( magicInputs[mi] );
					} catch (e) {
					}
				}
			} catch (e) {
			}
		};
		var refreshColorPickerPalettes = function () {
			try {
				if ( ! window.jQuery || ! panel) {
					return;
				}
				var basePalettes = [];
				try {
					var dyn = buildPalettesFromInputs();
					if (dyn && Object.prototype.toString.call( dyn ) === '[object Array]') {
						for (var dj = 0;dj < dyn.length;dj++) {
							var dv = safeColor( dyn[dj] );
							if (dv && basePalettes.indexOf( dv ) === -1) {
								basePalettes.push( dv );
							}
						}
					}
				} catch (e) {
				}
				if (basePalettes.length > 6) {
					basePalettes = basePalettes.slice( 0,6 );
				}
				var meta = cfg && cfg.paletteMeta && typeof cfg.paletteMeta === 'object' ? cfg.paletteMeta : {};
				try {
					var containers = panel.querySelectorAll( '.wp-picker-container' );
					for (var ci = 0;ci < containers.length;ci++) {
						var c = containers[ci];
						var palEls = c.querySelectorAll( '.iris-palette' );
						for (var pi = 0;pi < palEls.length;pi++) {
							try {
								var hex = basePalettes[pi] || '';
								var key = safeColor( hex );
								var label = '';
								if (key && meta && meta[key] && Object.prototype.toString.call( meta[key] ) === '[object Array]' && meta[key].length) {
									label = 'Debug source: ' + meta[key].join( ' | ' ) + ' (' + key + ')';
								} else if (key) {
									label = 'Debug source: ' + key;
								} else {
									label = 'Debug source';
								}
								if (key) {
									palEls[pi].style.backgroundColor = key;
									palEls[pi].setAttribute( 'data-color',key );
									try {
										if (window.jQuery && window.jQuery.fn) {
											window.jQuery( palEls[pi] ).data( 'color',key );
										}
									} catch (e) {}
								}
								palEls[pi].setAttribute( 'title',label );
								palEls[pi].setAttribute( 'data-thespl-debug-source',label );
							} catch (e) {
							}
						}
					}
				} catch (e) {
				}
			} catch (e) {
			}
		};
		var bindText = function(textId, unusedCallback) {
			try {
				var hiddenId = textId.replace(/-text$/, '');
				var hiddenInput = document.getElementById(hiddenId);
				if (hiddenInput) {
					// We ignore the callback because explicit input listeners (lines 411+) already handle the logic.
					// This prevents double execution and enforces Single Source of Truth via the hidden input.
					bindColorSync(textId, hiddenInput);
				}
			} catch (e) {}
		};
		bindText(
			'thespl-design-accent-' + pid + '-text',
			function (v) {
				try {
						accent.value = v;setTheme( 'progress',v );setCssVar( '--thespl-accent',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-accent-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-accent2-' + pid + '-text',
			function (v) {
				try {
						accent2.value = v;setCssVar( '--thespl-accent-2',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-accent2-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-base-' + pid + '-text',
			function (v) {
				try {
						base.value = v;setCssVar( '--thespl-bg',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-base-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-text-' + pid + '-text',
			function (v) {
				try {
						text.value = v;applyTextVars( String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-text-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-waveform-' + pid + '-text',
			function (v) {
				try {
						wf.value = v;setCssVar( '--thespl-waveform',String( v ) );setCssVar( '--thespl-wave',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-waveform-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-ring-' + pid + '-text',
			function (v) {
				try {
						ring.value = v;setCssVar( '--thespl-ring-base',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-ring-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-button-bg-' + pid + '-text',
			function (v) {
				try {
						btnBg.value = v;setCssVar( '--thespl-button-bg',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-button-bg-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-button-text-' + pid + '-text',
			function (v) {
				try {
						btnText.value = v;setCssVar( '--thespl-button-text',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-button-text-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-button-active-bg-' + pid + '-text',
			function (v) {
				try {
						btnActiveBg.value = v;setCssVar( '--thespl-button-active-bg',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-button-active-bg-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-button-active-text-' + pid + '-text',
			function (v) {
				try {
						btnActiveText.value = v;setCssVar( '--thespl-button-active-text',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-button-active-text-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-chip-bg-' + pid + '-text',
			function (v) {
				try {
						chipBg.value = v;setCssVar( '--thespl-chip-bg',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-chip-bg-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		bindText(
			'thespl-design-chip-br-' + pid + '-text',
			function (v) {
				try {
						chipBr.value = v;setCssVar( '--thespl-chip-br',String( v ) );var sw = panel.querySelector( '.thespl-swatch[data-swatch-for="thespl-design-chip-br-' + pid + '"]' );if (sw) {
						sw.style.background = v;}} catch (e) {
						}}
		);
		// Allow constraining the preview width for testing different player sizes.
		if (containerMax) {
			try {
				var applyW = function () {
					try {
							var v = parseInt( String( containerMax.value || '' ),10 ) || 0; if (v > 0) {
								w.style.maxWidth = String( v ) + 'px';}
						} catch (e) {
						}
					};
				containerMax.addEventListener( 'input',applyW );
				applyW();
			} catch (e) {
			}
		}
		// Trigger a server-side "magic palette" analysis and re-render the preview.
		if (magicBtn) {
			magicBtn.addEventListener(
				'click',
				function () {
					if (designLocked) {
						return;
					}
					try {
						setMagicState( true );
						showMagicStatus( '',false );
					} catch (e) {
					}
					var ajaxUrl = cfg.ajaxUrl || window.ajaxurl || '';
					var nonce   = cfg.magicNonce || '';
					var fd      = new FormData();
					fd.append( 'action','thespl_magic_palette' );
					fd.append( 'post_id',String( pid ) );
					fd.append( 'nonce',String( nonce ) );
					try {
						var pageBg = '';
						if ( magicPageBg && magicPageBg.value ) {
							pageBg = String( magicPageBg.value || '' ).trim();
						} else {
							pageBg = detectPageBackground();
						}
						if ( pageBg ) {
							fd.append( 'page_bg',String( pageBg ) );
						}
					} catch (e) {}
					try {
						if ( magicPageText && magicPageText.value ) {
							var pageText = String( magicPageText.value || '' ).trim();
							if ( pageText ) {
								fd.append( 'page_text',String( pageText ) );
							}
						}
					} catch (e) {}
					try {
						if ( magicAccent1 && magicAccent1.value ) {
							var accent1 = String( magicAccent1.value || '' ).trim();
							if ( accent1 ) {
								fd.append( 'accent_1',String( accent1 ) );
							}
						}
					} catch (e) {}
					try {
						if ( magicAccent2 && magicAccent2.value ) {
							var accent2Hex = String( magicAccent2.value || '' ).trim();
							if ( accent2Hex ) {
								fd.append( 'accent_2',String( accent2Hex ) );
							}
						}
					} catch (e) {}
					fetch( 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) {
								if (magicStatusError) {
									showMagicStatus( magicStatusError,true );
								}
								return;
							}
							var d = j.data.design || {};
							var t = j.data.tokens || {};
							var s = j.data.sources || null;
							if (s && typeof renderDebug === 'function') {
								renderDebug( s,t );
								if (debugPanel && debugToggle) {
										try {
											debugToggle.setAttribute( 'aria-expanded','true' );
											debugPanel.setAttribute( 'aria-hidden','false' );
											debugPanel.style.display = 'block';
										} catch (e) {
										}
									}
								}
								if (magicStatusSuccess) {
									showMagicStatus( magicStatusSuccess,false );
								}
								if (d.accent_color && accent) {
									normalizeColorInput( accent,d.accent_color );
									highlightField( accent );
								}
								if (d.waveform_color && wf) {
									normalizeColorInput( wf,d.waveform_color );
									highlightField( wf );
								}
								if (d.ring_base_color && ring) {
									normalizeColorInput( ring,d.ring_base_color );
									highlightField( ring );
								}
								if (d.accent_2_color && accent2) {
									normalizeColorInput( accent2,d.accent_2_color );
									highlightField( accent2 );
								}
								if (d.base_color && base) {
									normalizeColorInput( base,d.base_color );
									highlightField( base );
								}
								if (d.text_color && text) {
									normalizeColorInput( text,d.text_color );
									highlightField( text );
								}
								if (d.button_bg_color && btnBg) {
									normalizeColorInput( btnBg,d.button_bg_color );
									highlightField( btnBg );
								}
								if (d.button_text_color && btnText) {
									normalizeColorInput( btnText,d.button_text_color );
									highlightField( btnText );
								}
								if (d.button_active_bg_color && btnActiveBg) {
									normalizeColorInput( btnActiveBg,d.button_active_bg_color );
									highlightField( btnActiveBg );
								}
								if (d.button_active_text_color && btnActiveText) {
									normalizeColorInput( btnActiveText,d.button_active_text_color );
									highlightField( btnActiveText );
								}
								if (d.chip_bg_color && chipBg) {
									normalizeColorInput( chipBg,d.chip_bg_color );
									highlightField( chipBg );
								}
								if (d.chip_br_color && chipBr) {
									normalizeColorInput( chipBr,d.chip_br_color );
									highlightField( chipBr );
								}
						refreshColorPickerPalettes();
					}
						)
						.catch(
							function () {
								if (magicStatusError) {
									showMagicStatus( magicStatusError,true );
								}
							}
						)
						.finally(
							function () {
								try {
									setMagicState( false );
								} catch (e) {
								}
							}
						);
				});
		}
	initWpColorPicker();
} catch (e) {
}
})();
