(function () {
	try {
		var cfg  = window.thesplPlaylistEditorConfig || {};
		var pid  = cfg.postId || 0;
		var root = document.getElementById( 'thespl-playlist-editor-' + pid );
		if ( ! root) {
			try {
						root = document.querySelector( '.thespl-playlist-editor' );} catch (e) {
						} }
		if ( ! root) {
			return;}
		var tbody        = root.querySelector( '.thespl-playlist-editor__tracks' );
		var btnAdd       = root.querySelector( '.thespl-playlist-editor__add-track' );
		var btnAddMedia  = root.querySelector( '.thespl-playlist-editor__add-from-media' );
		var raw          = root.querySelector( '.thespl-playlist-editor__raw' );
		var hidden       = root.querySelector( '.thespl-playlist-editor__hidden' );
		var maxV         = cfg.variantCount || 2;
		var isReadOnly   = !! cfg.readOnly;
		var i18n         = (cfg.i18n || {});
		var rowUid       = 1;
		var isDirty      = false;
		var markDirty    = function () {
			isDirty = true;
		};
		var clearDirty   = function () {
			isDirty = false;
		};
		try {
			window.addEventListener(
				'beforeunload',
				function (e) {
					if ( ! isDirty) {
						return;
					}
					e.preventDefault();
					e.returnValue = '';
				}
			);
		} catch (e) {
		}
		var toggleClass  = function (el,cls,on) {
			if ( ! el) {
						return;}var c = el.classList;if (on) {
					c.add( cls );} else {
							c.remove( cls );}};
		var markRequired = function (tr) {
			if ( ! tr) {
				return;}
			var titleEl   = tr.querySelector( 'td:nth-child(2) input[type=text]' );
			var artistEl  = tr.querySelector( 'td:nth-child(3) input[type=text]' );
			var audioIdEl = tr.querySelector( 'td:nth-child(7) input[type=hidden]' );
			var chooseBtn = tr.querySelector( 'td:nth-child(7) button.button' );
			var hasTitle  = ! ! (titleEl && String( titleEl.value || '' ).trim());
			var hasArtist = ! ! (artistEl && String( artistEl.value || '' ).trim());
			var hasAudio  = ! ! (audioIdEl && parseInt( String( audioIdEl.value || '0' ),10 ) > 0);
			toggleClass( titleEl,'thespl-input-error', ! hasTitle );
			toggleClass( artistEl,'thespl-input-error', ! hasArtist );
			toggleClass( chooseBtn,'thespl-button-error', ! hasAudio );
			toggleClass( tr,'thespl-row-error',( ! hasTitle || ! hasArtist || ! hasAudio) );
		};
		var validateAll  = function () {
			var ok = true;var firstErr = null;
			var rows = tbody ? tbody.querySelectorAll( 'tr.thespl-editor-row-main' ) : [];
			if (rows && rows.forEach) {
				rows.forEach(
					function (r) {
							markRequired( r );if (r.classList.contains( 'thespl-row-error' )) {
							ok = false;if ( ! firstErr) {
								firstErr = r;}}}
				);}
			if ( ! ok && firstErr) {
				try {
							firstErr.scrollIntoView( {behavior:'smooth',block:'center'} );} catch (e) {
							}}
			return ok;
		};
		var makeRow      = function (t) {
			var uid      = rowUid++;
			var detId    = 'thespl-variants-' + String( pid ) + '-' + String( uid );
			var tr       = document.createElement( 'tr' );
			tr.className = 'thespl-editor-row-main';
			tr.setAttribute( 'data-row-id',String( uid ) );
			tr.setAttribute( 'data-variants-id',String( detId ) );
			var tdDrag       = document.createElement( 'td' );
			tdDrag.innerHTML = '\u2630';
			tdDrag.className = 'thespl-row-handle';
			tdDrag.setAttribute( 'data-label',String( i18n.move || 'Move' ) );
			tr.appendChild( tdDrag );
			var tdTitle = document.createElement( 'td' );
			tdTitle.setAttribute( 'data-label',String( i18n.title || 'Title' ) );
			var inpTitle       = document.createElement( 'input' );
			inpTitle.type      = 'text';
			inpTitle.className = 'widefat';
			inpTitle.value     = (t && t.title) || '';
			tdTitle.appendChild( inpTitle );
			tr.appendChild( tdTitle );
			var tdArtist = document.createElement( 'td' );
			tdArtist.setAttribute( 'data-label',String( i18n.artist || 'Artist' ) );
			var inpArtist       = document.createElement( 'input' );
			inpArtist.type      = 'text';
			inpArtist.className = 'widefat';
			inpArtist.value     = (t && t.artist) || '';
			tdArtist.appendChild( inpArtist );
			tr.appendChild( tdArtist );
			var tdVariants = document.createElement( 'td' );
			tdVariants.setAttribute( 'data-label',String( i18n.variants || 'Variants' ) );
			var btnToggle         = document.createElement( 'button' );
			btnToggle.type        = 'button';
			btnToggle.className   = 'button thespl-row-variants-toggle';
			btnToggle.textContent = (i18n.variants || 'Variants') + ' ▸';
			btnToggle.setAttribute( 'aria-expanded','false' );
			btnToggle.setAttribute( 'aria-controls',detId );
			tdVariants.appendChild( btnToggle );
			var detailsWrap       = document.createElement( 'div' );
			detailsWrap.className = 'thespl-track-card__details';
			detailsWrap.id        = detId;
			detailsWrap.setAttribute( 'role','region' );
			detailsWrap.setAttribute( 'aria-label',String( i18n.variantsEditor || ((i18n.variants || 'Variants') + ' editor') ) );
			detailsWrap.hidden = true;
			tr.appendChild( tdVariants );
			var tdCredits = document.createElement( 'td' );
			tdCredits.setAttribute( 'data-label',String( i18n.credits || 'Credits' ) );
			var inpCredits       = document.createElement( 'input' );
			inpCredits.type      = 'text';
			inpCredits.className = 'widefat';
			inpCredits.value     = (t && t.credits) || '';
			tdCredits.appendChild( inpCredits );
			tr.appendChild( tdCredits );
			var tdSocial = document.createElement( 'td' );
			tdSocial.setAttribute( 'data-label',String( i18n.social || 'Artist URL' ) );
			var inpSocial       = document.createElement( 'input' );
			inpSocial.type      = 'url';
			inpSocial.className = 'widefat';
			inpSocial.value     = (t && t.social) || '';
			tdSocial.appendChild( inpSocial );
			tr.appendChild( tdSocial );
			var tdAudio = document.createElement( 'td' );
			tdAudio.setAttribute( 'data-label',String( i18n.audio || 'Audio' ) );
			var audioId            = document.createElement( 'input' );
			audioId.type           = 'hidden';
			audioId.value          = ((t && t.audio_attachment_id) || 0);
			var btnChooseA         = document.createElement( 'button' );
			btnChooseA.type        = 'button';
			btnChooseA.className   = 'button';
			btnChooseA.textContent = (i18n.choose || 'Choose');
			var btnClearA          = document.createElement( 'button' );
			btnClearA.type         = 'button';
			btnClearA.className    = 'button thespl-button--spaced';
			btnClearA.textContent  = (i18n.clear || 'Clear');
			var aLabel             = document.createElement( 'span' );
			aLabel.className       = 'thespl-media-label';
			aLabel.style.marginLeft = '6px';
			aLabel.style.opacity = '0.7';
			tdAudio.appendChild( audioId );
			tdAudio.appendChild( btnChooseA );
			tdAudio.appendChild( btnClearA );
			tdAudio.appendChild( aLabel );
			tr.appendChild( tdAudio );
			var tdCover = document.createElement( 'td' );
			tdCover.setAttribute( 'data-label',String( i18n.cover || 'Cover' ) );
			var coverId            = document.createElement( 'input' );
			coverId.type           = 'hidden';
			coverId.value          = ((t && t.cover_attachment_id) || 0);
			var btnChooseC         = document.createElement( 'button' );
			btnChooseC.type        = 'button';
			btnChooseC.className   = 'button';
			btnChooseC.textContent = (i18n.choose || 'Choose');
			var btnClearC          = document.createElement( 'button' );
			btnClearC.type         = 'button';
			btnClearC.className    = 'button thespl-button--spaced';
			btnClearC.textContent  = (i18n.clear || 'Clear');
			var cLabel             = document.createElement( 'span' );
			cLabel.className       = 'thespl-media-label';
			cLabel.style.marginLeft = '6px';
			cLabel.style.opacity = '0.7';
			tdCover.appendChild( coverId );
			tdCover.appendChild( btnChooseC );
			tdCover.appendChild( btnClearC );
			tdCover.appendChild( cLabel );
			tr.appendChild( tdCover );
			var tdRemove = document.createElement( 'td' );
			tdRemove.setAttribute( 'data-label',String( i18n.remove || 'Remove' ) );
			var btnRem         = document.createElement( 'button' );
			btnRem.type        = 'button';
			btnRem.className   = 'button';
			btnRem.textContent = (i18n.remove || 'Remove');
			tdRemove.appendChild( btnRem );
			tr.appendChild( tdRemove );
			var det       = document.createElement( 'tr' );
			det.className = 'thespl-editor-row-details';
			det.setAttribute( 'data-row-id',String( uid ) );
			det.id          = detId + '-row';
			var tdDet       = document.createElement( 'td' );
			tdDet.colSpan   = 9;
			var panel       = document.createElement( 'div' );
			panel.className = 'thespl-variants-editor';
			panel.style.setProperty( '--thespl-variants-cols',String( maxV ) );
			var variants     = Array.isArray( t && t.variants ) ? t.variants : [];
			var variantInfo  = Array.isArray( t && t.variant_info ) ? t.variant_info : [];
			var base         = (i18n && i18n.variantBase) ? String( i18n.variantBase ) : 'Variant';
			var infoBase     = (i18n && i18n.variantInfoBase) ? String( i18n.variantInfoBase ) : 'Notes';
			for (var i = 0;i < maxV;i++) {
				var item = document.createElement( 'div' );
				item.className = 'thespl-variants-editor__item';
				var vi = document.createElement( 'input' );
				vi.type = 'text';
				vi.value = (variants[i] || '');
				vi.setAttribute( 'data-variant-role','label' );
				vi.placeholder = (base + ' ' + String( i + 1 ));
				item.appendChild( vi );
				var info = document.createElement( 'input' );
				info.type = 'text';
				info.value = (variantInfo[i] || '');
				info.setAttribute( 'data-variant-role','info' );
				info.placeholder = (infoBase + ' ' + String( i + 1 ));
				item.appendChild( info );
				panel.appendChild( item );
			}
			detailsWrap.appendChild( panel );
			tdDet.appendChild( detailsWrap );
			det.appendChild( tdDet );
			det.style.display = 'none';
			var mq            = (window.matchMedia ? window.matchMedia( '(max-width: 960px)' ) : null);
			var table         = (root ? root.querySelector( '.thespl-playlist-editor__table' ) : null);
			var thead         = (table ? table.querySelector( 'thead' ) : null);
			var isCompact     = function () {
				try {
					var w = window.innerWidth || 0;
					if (w && w <= 960) {
						return true;}
					if (thead && window.getComputedStyle) {
						return window.getComputedStyle( thead ).display === 'none';}
				} catch (e) {
				}
				return false;
			};
			var reparent      = function () {
				try {
					if (isCompact()) {
						if (detailsWrap.parentNode !== tdVariants) {
							tdVariants.appendChild( detailsWrap );}
					} else {
						if (detailsWrap.parentNode !== tdDet) {
							tdDet.appendChild( detailsWrap );}
					}
				} catch (e) {
				}
			};
			var setOpen       = function (open) {
				try {
					reparent();} catch (e) {
					}
					if (isCompact()) {
						detailsWrap.hidden = ! open;
						det.style.display  = 'none';
					} else {
						detailsWrap.hidden = false;
						det.style.display  = open ? '' : 'none';
					}
					btnToggle.textContent = (i18n.variants || 'Variants') + ' ' + (open ? '\u25BE' : '\u25B8');
					btnToggle.setAttribute( 'aria-expanded',open ? 'true' : 'false' );
					tr.classList.toggle( 'is-expanded', ! ! open );
			};
			btnToggle.addEventListener(
				'click',
				function () {
					var y   = 0;
					var top = 0;
					try {
						y = window.pageYOffset || 0;top = btnToggle.getBoundingClientRect().top || 0;} catch (e) {
						}
						var next = String( btnToggle.getAttribute( 'aria-expanded' ) || 'false' ) !== 'true';
						setOpen( next );
						try {
							window.requestAnimationFrame(
								function () {
									try {
											var nextTop = btnToggle.getBoundingClientRect().top || 0;
											var dy      = nextTop - top;
										if (dy) {
											window.scrollTo( 0,(window.pageYOffset || y) + dy );}
									} catch (e) {
									}
								}
							);
						} catch (e) {
						}
				}
			);
			var resizeT  = 0;
			var relayout = function () {
				setOpen( String( btnToggle.getAttribute( 'aria-expanded' ) || 'false' ) === 'true' );};
			if (mq) {
				try {
					if (typeof mq.addEventListener === 'function') {
						mq.addEventListener( 'change',relayout );
					} else if (typeof mq.addListener === 'function') {
						mq.addListener( relayout );
					}
				} catch (e) {
				}
			}
			try {
				window.addEventListener(
					'resize',
					function () {
						try {
							if (resizeT) {
											window.clearTimeout( resizeT );}} catch (e) {
											}
											resizeT = window.setTimeout( relayout,60 );
					},
					{passive:true}
				);
			} catch (e) {
			}
			var fmtId = function (id) {
				var n = parseInt( String( id || '0' ), 10 );
				return n > 0 ? (' (' + String( n ) + ')') : '';
			};
			var setAudioLabel = function (el, id) { el.textContent = fmtId( id ); };
			var setCoverLabel = function (el, id) {
				el.textContent = fmtId( id );
			};
			var openMedia = function (type,setId,setLabel) {
				if ( ! window.wp || ! wp.media) {
					return;}
				var f = wp.media( {frame:'select',multiple:false,library:{type:type}} );
				f.on(
					'select',
					function () {
						var sel = f.state().get( 'selection' );
						var m   = sel && sel.first();
						if ( ! m) {
							return;}
						if (type && type.length && type.indexOf( 'audio/flac' ) !== -1) {
							var filename = (m.get && m.get( 'filename' )) || '';
							var ext = String( filename || '' ).split( '.' ).pop().toLowerCase();
							if (['flac','wav'].indexOf( ext ) === -1) {
								window.alert( String( i18n.invalidAudioType || 'Only FLAC and WAV files are allowed.' ) );
								return;
							}
						}
						var id               = (m.id || m.get && m.get( 'id' ));
						setId.value          = String( id || 0 );
						if (setId === audioId) {
							setAudioLabel( setLabel, id );
						} else {
							setCoverLabel( setLabel, id );
						}
						syncJson();
						markRequired( tr );
						markDirty();
					}
				);
				f.open();
			};
			btnChooseA.addEventListener(
				'click',
				function () {
					openMedia( ['audio/flac','audio/wav','audio/x-wav'],audioId,aLabel );}
			);
			btnClearA.addEventListener(
				'click',
				function () {
					audioId.value = '0';aLabel.textContent = '';syncJson();markRequired( tr );markDirty();}
			);
			btnChooseC.addEventListener(
				'click',
				function () {
					openMedia( ['image'],coverId,cLabel );}
			);
			btnClearC.addEventListener(
				'click',
				function () {
					coverId.value = '0';cLabel.textContent = '';syncJson();markDirty();}
			);
			btnRem.addEventListener(
				'click',
				function () {
					if (isReadOnly) {
						return;
					}
					if (tr.parentNode) {
						tr.parentNode.removeChild( tr );}
					if (det.parentNode) {
						det.parentNode.removeChild( det );}
					syncJson();
					markDirty();
				}
			);
			var normalizeSocial = function (raw) {
				var v = String( raw || '' ).trim();
				if ( ! v) {
					return '';
				}
				if (/^[a-z][a-z0-9+\-.]*:\/\//i.test( v )) {
					return v;
				}
				if (v.indexOf( '//' ) === 0) {
					return 'https:' + v;
				}
				return 'https://' + v;
			};
			inpSocial.addEventListener(
				'blur',
				function () {
					if (isReadOnly) {
						return;
					}
					var v = normalizeSocial( inpSocial.value );
					inpSocial.value = v;
					syncJson();
					markDirty();
				}
			);
			[inpTitle,inpArtist,inpCredits,inpSocial].forEach(
				function (el) {
					el.addEventListener(
						'input',
						function () {
							if (isReadOnly) {
								return;
							}
										syncJson();markRequired( tr );markDirty();}
					);}
			);
			Array.prototype.forEach.call(
				panel.querySelectorAll( 'input' ),
				function (el) {
					el.addEventListener(
						'input',
						function () {
							if (isReadOnly) {
								return;
							}
							syncJson();markDirty();}
					);}
			);
			if (isReadOnly) {
				Array.prototype.forEach.call(
					tr.querySelectorAll( 'input, button' ),
					function (el) {
						if (el !== btnToggle) {
							el.disabled = true;
						}
					}
				);
				Array.prototype.forEach.call(
					panel.querySelectorAll( 'input' ),
					function (el) {
						el.disabled = true;
					}
				);
				tdDrag.style.opacity = '0.45';
			}
			setOpen( false );
			tbody.appendChild( tr );
			tbody.appendChild( det );
			if (parseInt( String( audioId.value || '0' ), 10 ) > 0 && ! aLabel.textContent) { setAudioLabel( aLabel, audioId.value ); }
			if (parseInt( String( coverId.value || '0' ), 10 ) > 0 && ! cLabel.textContent) {
				setCoverLabel( cLabel, coverId.value );
			}
			markRequired( tr );
			return tr;
		};
		var readInit     = function () {
			var init = [];
			var rawS = (cfg.rawJson || '');
			if ( ! rawS && raw) {
				try {
							rawS = raw.value || '';} catch (e) {
							}}
			try {
				var j = rawS ? JSON.parse( rawS ) : {};if (j && Array.isArray( j.tracks )) {
							init = j.tracks;}} catch (e) {
							}
							return init;
		};
		var syncJson     = function () {
			if (isReadOnly) {
				return;
			}
			var mains  = tbody.querySelectorAll( 'tr.thespl-editor-row-main' );
			var tracks = [];
			mains.forEach(
				function (tr) {
					var id         = tr.getAttribute( 'data-row-id' ) || '';
					var vid        = tr.getAttribute( 'data-variants-id' ) || '';
					var textInputs = tr.querySelectorAll( 'input[type=text].widefat' );
					var title      = (textInputs[0] ? textInputs[0].value : '');
					var artist     = (textInputs[1] ? textInputs[1].value : '');
					var credits    = (textInputs[2] ? textInputs[2].value : '');
					var social     = (tr.querySelector( 'input[type=url]' ) ? tr.querySelector( 'input[type=url]' ).value : '');
					var variants   = [];
					var variantInfo = [];
					var region     = (vid ? document.getElementById( vid ) : null);
					if (region) {
						var vLabels = region.querySelectorAll( '.thespl-variants-editor input[data-variant-role="label"]' );
						var vInfos  = region.querySelectorAll( '.thespl-variants-editor input[data-variant-role="info"]' );
						for (var i = 0;i < vLabels.length;i++) {
							variants.push( String( vLabels[i].value || '' ) );
						}
						for (var j = 0;j < vInfos.length;j++) {
							variantInfo.push( String( vInfos[j].value || '' ) );
						}
					}
					var audioId = (tr.querySelector( 'td:nth-child(7) input[type=hidden]' ) ? parseInt( tr.querySelector( 'td:nth-child(7) input[type=hidden]' ).value,10 ) : 0) || 0;
					var coverId = (tr.querySelector( 'td:nth-child(8) input[type=hidden]' ) ? parseInt( tr.querySelector( 'td:nth-child(8) input[type=hidden]' ).value,10 ) : 0) || 0;
					tracks.push( {title:title,artist:artist,credits:credits,variants:variants,variant_info:variantInfo,social:social,audio_attachment_id:audioId,cover_attachment_id:coverId} );
				}
			);
			var out = {tracks:tracks};
			var s   = JSON.stringify( out );
			if (hidden) {
				hidden.value = s;}
			if (raw) {
				raw.value = s;}
		};
		var renderTracks = function () {
			tbody.innerHTML = '';
			var init        = readInit();
			for (var i = 0;i < init.length;i++) {
				makeRow( init[i] || {} );}
			if ( ! isReadOnly && typeof jQuery !== 'undefined' && jQuery && jQuery.fn && jQuery.fn.sortable) {
				try {
					jQuery( tbody ).sortable(
						{items:'tr.thespl-editor-row-main',handle:'.thespl-row-handle',update:function () {
							var $tbody = jQuery( tbody );
							$tbody.find( 'tr.thespl-editor-row-main' ).each(
								function () {
									var id     = this.getAttribute( 'data-row-id' ) || '';
									var detail = $tbody.find( "tr.thespl-editor-row-details[data-row-id='" + id + "']" )[0];
									if (detail && detail.previousSibling !== this) {
										this.parentNode.insertBefore( detail,this.nextSibling );}
								}
							);
							syncJson();
						}}
					);
				} catch (e) {
				}
			}
			syncJson();
			validateAll();
		}
		if (btnAdd) {
			if (isReadOnly) {
				btnAdd.disabled = true;
			}
			btnAdd.addEventListener(
				'click',
				function () {
					if (isReadOnly) {
						return;
					}
						makeRow( {} );syncJson();markDirty();}
			);}
		if (btnAddMedia) {
			if (isReadOnly) {
				btnAddMedia.disabled = true;
			}
			btnAddMedia.addEventListener(
				'click',
				function () {
					if (isReadOnly) {
						return;
					}
					if ( ! window.wp || ! wp.media) {
						return;}
					var f = wp.media( {frame:'select',multiple:true,library:{type:['audio']}} );
					f.on(
						'select',
						function () {
							var sel = f.state().get( 'selection' );
							sel.each(
								function (m) {
									var id    = (m.id || m.get && m.get( 'id' ));
									var title = (m.get && m.get( 'title' )) || '';
									makeRow( {title:String( title || '' ),audio_attachment_id:Number( id || 0 )} );
								}
							);
							syncJson();
							validateAll();
							if (sel && sel.length) {
								markDirty();
							}
						}
					);
					f.open();
				}
			);
		}
		try {
			var msg      = (i18n && i18n.missingRequired) ? String( i18n.missingRequired ) : 'Please complete Title, Artist and Audio.';
			var publish  = document.getElementById( 'publish' );
			if (publish) {
				publish.addEventListener(
					'click',
					function (e) {
						if ( ! validateAll()) {
							e.preventDefault();e.stopPropagation();try {
									window.alert( msg );} catch (err) {
									}} else {
							clearDirty();
						}}
				);
			}
			var save     = document.getElementById( 'save-post' );
			if (save) {
				save.addEventListener(
					'click',
					function (e) {
						if ( ! validateAll()) {
							e.preventDefault();e.stopPropagation();try {
								window.alert( msg );} catch (err) {
								}} else {
							clearDirty();
						}
					}
				);
			}
			var saveTarget = publish || save;
			var btnSavePlaylist = document.querySelector( '.thespl-playlist-editor__save-playlist' );
			if (btnSavePlaylist && saveTarget) {
				btnSavePlaylist.addEventListener(
					'click',
					function (e) {
						e.preventDefault();e.stopPropagation();
						if (validateAll()) {
							clearDirty();
							try {
									saveTarget.click();
							} catch (err) {
							}
						} else {
							try {
								window.alert( msg );} catch (err) {
							}
						}
					}
				);
			}
		} catch (e) {
		}
		renderTracks();
	} catch (e) {
	}
})();
