(function () {
	try {
		var cfg   = window.thesplPreviewConfig || {};
		var pid   = cfg.postId || 0;
		var w     = document.getElementById( 'thespl-preview-wrap-' + pid );
		var sel   = document.querySelector( 'select[name="thespl_playlist_template"]' );
		var short = document.getElementById( 'thespl-preview-shortcode-' + pid );
		if ( ! w || ! sel || ! pid) {
			return;}
		var ajaxUrl           = cfg.ajaxUrl || window.ajaxurl || '';
		var nonce             = cfg.nonce || '';
		var pluginUrl         = cfg.pluginUrl || '';
		var uploadsBaseUrl    = cfg.uploadsBaseUrl || '';
		var foldersMeta       = cfg.templateFolders || {};
		var defaultSlug       = cfg.defaultSlug || '';
		var ver               = String( cfg.version || '' );
		var errorTitle        = String( cfg.errorTitle || 'The Studio Player could not render the selected player template.' );
		var errorBody         = String( cfg.errorBody || 'Please check your custom player template file for syntax or runtime errors. If your site becomes unavailable after editing a template, you can rename the template folder or the plugin folder via FTP to deactivate it and restore access.' );
		var assetErrorTitle   = String( cfg.assetErrorTitle || 'The selected template assets could not be loaded.' );
		var assetErrorBody    = String( cfg.assetErrorBody || 'The preview HTML was rendered, but the template JavaScript dependencies are missing or not reachable. Check whether script.js exists in the selected template folder and whether the template slug is still valid.' );
		var slugMismatchTitle = String( cfg.slugMismatchTitle || 'Template slug mismatch detected.' );
		var slugMismatchBody  = String( cfg.slugMismatchBody || 'The selected template slug does not match the slug selector used inside template dependencies. This often happens after renaming a template folder. Keep folder name and internal data-template-slug bindings in sync.' );
		var showError       = function (target,title,body) {
			try {
				var el = target || w;
				if ( ! el) {
					return;}
				var wrap = document.createElement( 'div' );
				wrap.className = 'notice notice-error';
				var p1 = document.createElement( 'p' );
				p1.textContent = String( title || errorTitle );
				var p2 = document.createElement( 'p' );
				p2.textContent = String( body || errorBody );
				wrap.appendChild( p1 );
				wrap.appendChild( p2 );
				el.innerHTML = '';
				el.appendChild( wrap );
			} catch (e) {
			}
		};
		window.thesplPreviewShowError = showError;
		var hasRuntime      = function () {
			return !! (
				window.THESPL_Player_Core
				&& typeof window.THESPL_Player_Core.initAll === 'function'
				&& window.THESPL_Player_Store
				&& window.THESPL_Player_UI
			);
		};
		var waitForRuntime  = function (tries,delay) {
			return new Promise(
				function (resolve) {
					var left = Number( tries ) || 0;
					var step = Number( delay ) || 0;
					var tick = function () {
						if (hasRuntime()) {
							resolve( true );
							return;
						}
						if (left <= 0) {
							resolve( false );
							return;
						}
						left--;
						window.setTimeout( tick, step );
					};
					tick();
				}
			);
		};
		var resolveTemplateBase = function (tpl) {
			var slug   = String( tpl || '' );
			var folder = null;
			var src    = null;
			if (slug && foldersMeta && Object.prototype.hasOwnProperty.call( foldersMeta, slug )) {
				var meta = foldersMeta[ slug ] || {};
				if (meta && typeof meta.folder === 'string' && meta.folder) {
					folder = meta.folder;
					src    = typeof meta.src === 'string' ? meta.src : null;
				}
			}
			if (folder && src === 'uploads' && uploadsBaseUrl) {
				return String( uploadsBaseUrl ) + String( folder ) + '/';
			}
			if (folder && pluginUrl) {
				return String( pluginUrl ) + 'templates/player/' + String( folder ) + '/';
			}
			return String( pluginUrl ) + 'templates/player/' + String( slug || 'default' ) + '/';
		};
		var ensureAssets    = function (tpl) {
			return new Promise(
				function (resolve) {
					var base   = resolveTemplateBase( tpl );
					var href   = base + 'style.css?ver=' + ver;
					var linkId = 'thespl-template-style';
					var link   = document.getElementById( linkId );
					if ( ! link) {
						link = document.createElement( 'link' );link.id = linkId;link.rel = 'stylesheet';document.head.appendChild( link );}
					link.href = href;
					var jsId  = 'thespl-template-script';
					var src   = base + 'script.js?ver=' + ver;
					var old   = document.getElementById( jsId );
					if (old && old.parentNode) {
						old.parentNode.removeChild( old );}
					var s = document.createElement( 'script' );
					s.id  = jsId; s.src = src; s.defer = true;
					s.onload                           = function () {
						resolve(
							{
								scriptLoaded: true,
								scriptUrl: src
							}
						);
					};
					s.onerror = function () {
						resolve(
							{
								scriptLoaded: false,
								scriptUrl: src
							}
						);
					};
					document.body.appendChild( s );
				}
			);
		};
		var detectSlugMismatch = function (tpl,scriptUrl) {
			return new Promise(
				function (resolve) {
					if ( ! tpl || ! scriptUrl) {
						resolve(
							{
								mismatch: false,
								detected: []
							}
						);
						return;
					}
					fetch(
						scriptUrl,
						{
							method: 'GET',
							credentials: 'same-origin'
						}
					).then(
						function (res) {
							if ( ! res || ! res.ok) {
								resolve(
									{
										mismatch: false,
										detected: []
									}
								);
								return null;
							}
							return res.text();
						}
					).then(
						function (txt) {
							if ( ! txt || typeof txt !== 'string') {
								resolve(
									{
										mismatch: false,
										detected: []
									}
								);
								return;
							}
							var rx      = /data-template-slug=["']([a-z0-9_-]+)["']/g;
							var found   = [];
							var matched = null;
							while (null !== (matched = rx.exec( txt ))) {
								var val = String( matched[1] || '' );
								if (val && found.indexOf( val ) === -1) {
									found.push( val );
								}
							}
							if ( ! found.length || found.indexOf( tpl ) !== -1) {
								resolve(
									{
										mismatch: false,
										detected: found
									}
								);
								return;
							}
							resolve(
								{
									mismatch: true,
									detected: found
								}
							);
						}
					).catch(
						function () {
							resolve(
								{
									mismatch: false,
									detected: []
								}
							);
						}
					);
				}
			);
		};
		var updateShortcode = function () {
			var tpl            = sel.value || '';
			var sc             = '[thespl_player playlist_id="' + pid + '"]';
			var effectiveDefault = defaultSlug ? String( defaultSlug ) : '';
			if (tpl) {
				if ( ! effectiveDefault || tpl !== effectiveDefault) {
					sc = '[thespl_player playlist_id="' + pid + '" template="' + tpl + '"]';
				}
			}
			if (short) {
				short.textContent = sc;
			}
		};
		var ajaxRender      = function (tpl) {
			var fd = new FormData();
			fd.append( 'action','thespl_preview_render' );
			fd.append( 'post_id',String( pid ) );
			fd.append( 'template',String( tpl || 'default' ) );
			fd.append( 'nonce',String( nonce ) );
			return 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 || typeof j.data.html !== 'string') {
						showError();
						return false;}
					w.innerHTML = j.data.html;
					return ensureAssets( tpl ).then(
						function (assetsState) {
							if ( ! assetsState || ! assetsState.scriptLoaded) {
								try {
									console.warn( 'THESPL preview template script could not be loaded for template:', String( tpl || 'default' ) );
								} catch (e) {
								}
								showError( w, assetErrorTitle, assetErrorBody );
								return false;
							}
							return detectSlugMismatch( String( tpl || 'default' ), String( assetsState.scriptUrl || '' ) ).then(
								function (slugState) {
									if (slugState && slugState.mismatch) {
										var detail = slugMismatchBody;
										var from   = slugState.detected && slugState.detected.length ? slugState.detected.join( ', ' ) : '';
										if (from) {
											detail += ' Selected slug: "' + String( tpl || 'default' ) + '". Script bindings: "' + from + '".';
										}
										showError( w, slugMismatchTitle, detail );
										return false;
									}
									return waitForRuntime( 5, 80 ).then(
								function (ok) {
									if ( ! ok) {
										try {
											console.warn( 'THESPL preview runtime missing', {
												core: !! window.THESPL_Player_Core,
												initAll: !! (window.THESPL_Player_Core && typeof window.THESPL_Player_Core.initAll === 'function'),
												store: !! window.THESPL_Player_Store,
												ui: !! window.THESPL_Player_UI
											} );
										} catch (e) {
										}
										return true;
									}
									try {
										window.THESPL_Player_Core.initAll();
									} catch (e) {
										return true;
									}
									return true;
								}
							);
								}
							);
						}
					);
				}
			).catch(
				function () {
					showError();
					return false;}
			);
		};
		sel.addEventListener(
			'change',
			function () {
				updateShortcode();ajaxRender( sel.value );}
		);
		updateShortcode();
		ajaxRender( sel.value || 'default' );
	} catch (e) {
	}
})();
