const ninodemYoutube = {
	init() {
		document.querySelectorAll('[href*="youtube.com/watch"], [href*="youtu.be"]').forEach(link => {
			const figure = link.closest('figure');
			figure.classList.add('ytp-wrapper');
			link.addEventListener('click', function(event) {
				event.preventDefault();
				const videoUrl = this.href;
				const videoId = ninodemYoutube.getVideoId(videoUrl);
				if (!videoId) return;

				const figure = this.closest('figure');
				const placeholder = document.createElement('div');
				placeholder.style.width = this.offsetWidth + 'px';
				placeholder.style.height = this.offsetHeight + 'px';

                placeholder.appendChild(ninodemYoutube.createSpinner());

				figure.innerHTML = '';
				figure.appendChild(placeholder);

				setTimeout(() => {
					const iframe = document.createElement('iframe');
					iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1`;
					iframe.width = placeholder.style.width;
					iframe.height = placeholder.style.height;
					iframe.frameBorder = "0";
					iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
					iframe.allowFullscreen = true;

					placeholder.replaceWith(iframe);
				}, 1000);
			});
		});
	},

	getVideoId(url) {
		const match = url.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|v\/|.+\?v=))([^&?]+)/);
		return match ? match[1] : null;
	},

    createSpinner() {
        const spinner = document.createElement('div');
        spinner.className = 'ytp-spinner';

        const spinnerContainer = document.createElement('div');
        spinnerContainer.className = 'ytp-spinner-container';

        const spinnerRotator = document.createElement('div');
        spinnerRotator.className = 'ytp-spinner-rotator';

        const spinnerLeft = document.createElement('div');
        spinnerLeft.className = 'ytp-spinner-left';
        const spinnerCircleLeft = document.createElement('div');
        spinnerCircleLeft.className = 'ytp-spinner-circle';

        const spinnerRight = document.createElement('div');
        spinnerRight.className = 'ytp-spinner-right';
        const spinnerCircleRight = document.createElement('div');
        spinnerCircleRight.className = 'ytp-spinner-circle';

        spinnerLeft.appendChild(spinnerCircleLeft);
        spinnerRight.appendChild(spinnerCircleRight);
        spinnerRotator.appendChild(spinnerLeft);
        spinnerRotator.appendChild(spinnerRight);
        spinnerContainer.appendChild(spinnerRotator);
        spinner.appendChild(spinnerContainer);

        return spinner;
    }
};

document.addEventListener('DOMContentLoaded', () => ninodemYoutube.init());
