( function ( api, config ) {
	'use strict';

	api.bind( 'ready', function () {
		var uploadControl = document.getElementById( 'customize-control-fanspaysite_apple_touch_icon' );
		var links;
		var title;
		var help;
		var linkList;
		var standardLink;
		var precomposedLink;

		if ( ! uploadControl || ! config ) {
			return;
		}

		links = document.createElement( 'div' );
		links.className = 'fanspaysite-touch-icon-links';
		links.hidden = true;

		title = document.createElement( 'span' );
		title.className = 'customize-control-title';
		title.textContent = config.previewTitle;
		links.appendChild( title );

		help = document.createElement( 'span' );
		help.className = 'description customize-control-description';
		help.textContent = config.previewHelp;
		links.appendChild( help );

		linkList = document.createElement( 'p' );
		standardLink = document.createElement( 'a' );
		standardLink.href = config.standardUrl;
		standardLink.target = '_blank';
		standardLink.rel = 'noopener noreferrer';
		standardLink.textContent = '/apple-touch-icon.png';
		standardLink.hidden = true;
		linkList.appendChild( standardLink );
		linkList.appendChild( document.createElement( 'br' ) );

		precomposedLink = document.createElement( 'a' );
		precomposedLink.href = config.precomposedUrl;
		precomposedLink.target = '_blank';
		precomposedLink.rel = 'noopener noreferrer';
		precomposedLink.textContent = '/apple-touch-icon-precomposed.png';
		precomposedLink.hidden = true;
		linkList.appendChild( precomposedLink );
		links.appendChild( linkList );
		uploadControl.appendChild( links );

		function refreshLinks() {
			var previewLinks = links.querySelectorAll( 'a' );
			var pending = previewLinks.length;
			var available = false;

			Array.prototype.forEach.call( previewLinks, function ( link ) {
				var image = new window.Image();
				var finish = function ( exists ) {
					link.hidden = ! exists;
					available = available || exists;
					pending -= 1;

					if ( 0 === pending ) {
						links.hidden = ! available;
					}
				};

				image.onload = function () {
					finish( true );
				};
				image.onerror = function () {
					finish( false );
				};
				image.src = link.href + ( -1 === link.href.indexOf( '?' ) ? '?' : '&' ) + 'fanspaysite_preview=' + Date.now();
			} );
		}

		refreshLinks();
		api.bind( 'saved', refreshLinks );
	} );
}( wp.customize, window.fanspaysiteTouchIcons ) );
