/* © Copyright RadioBS - Created by Lugsoft - lugsoft.com.br */
(function ($) {
	"use strict";

	var playerAudio = document.querySelector('#player_audio');
	var timeMsg;

	setTimeout(autoPlay, 500);

	// prefers-color-scheme
	const setThemeMode = function (theme) {
		const dataBsTheme = theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : theme;
		document.documentElement.setAttribute('data-bs-theme', dataBsTheme);
	}
	setThemeMode(CONFIG.themeMode)

	// play - player
	$(document).on('click', '.b-play, .b-stop', function (e) {
		e.preventDefault();
		audioPlay(this);
	});

	// audio play
	function audioPlay(data) {
		var $data = $(data);
		var StreamUrl = $data.data('stream');
		$('#player_audio').html(`<source id="radio_stream" src="${StreamUrl}" type="audio/mp3">`);
		playerAudio.load();
		var class_name = data.getAttribute('class');
		$('.b-stop').removeClass('b-stop').addClass('b-play');
		if (class_name === 'b-play') {
			$data.removeClass('b-play').addClass('b-stop');
			playerAudio.play().then(() => {
				console.log('play success');
			}).catch(() => {
				console.log('play failed');
			});
		} else {
			$data.removeClass('b-stop').addClass('b-play');
			playerAudio.pause();
		}
	}

	// autoplay
	function autoPlay() {
		var StreamUrl = $('.b-play').attr('data-stream');
		$('#player_audio').html('<source id="radio_stream" src="' + StreamUrl + '" type="audio/mp3">');
		playerAudio.load();
		let playAttempt = setInterval(() => {
			if (playerAudio.paused) {
				playerAudio.play().then(() => {
					clearInterval(playAttempt);
					$('.b-play').removeClass('b-play').addClass('b-stop');
					console.log("autoplay success");
				}).catch((e) => {
					console.log("autoplay failed");
				});
			} else {
				$('.b-play').removeClass('b-play').addClass('b-stop');
				console.log("clean autoplay");
				clearInterval(playAttempt);
			}
		}, 3000);
	}

	//Share social
	$('#shareBS').click(function (e) {
		var share = $('#shareBS');
		var url = share.attr('data-url');
		var text = share.attr('data-title');
		navigator.share({ title: text, url: url });
	});

	function requestApi(ref, data, service, method) {
		return $.ajax({
			method: method,
			url: `${CONFIG.pathSystem}api/${service}`,
			data: data,
			dataType: "json",
			processData: false,
			contentType: false,
			cache: false,
			beforeSend: function () {
				$(ref + ' .loading').removeClass('d-none');
				$(ref + ' .submit').addClass('d-none');
			},
			success: function (res) {
				$(ref + ' .loading').addClass('d-none');
				$(ref + ' .submit').removeClass('d-none');
				var $resMessage = $(ref + ' #res-message');
				if (res.status) {
					$resMessage.html(`<span class="text-success">${res.message}</span>`);
				} else {
					$resMessage.html(`<span class="text-danger">${res.message}</span>`);
				}
				clearTimeout(timeMsg);
				timeMsg = setTimeout(() => { $resMessage.html('') }, 7000);
			}
		});
	}

	function playingNow() {
		var ref = '.player';
		var $ref = $(ref);
		requestApi(ref, '', 'playingNow', 'GET').done(function (res) {
			if (res.status) {
				var { playingNow, albumCover, trackName, siteTitle } = res.data;

				$ref.find('#playingNow').text(playingNow ? playingNow : '...');

				if (albumCover) {
					var albumCoverSrc = albumCover.replace('100x100', '300x300');
					$ref.find('.player-info img').attr('src', albumCoverSrc);
				}

				if ('mediaSession' in navigator) {
					navigator.mediaSession.metadata = new MediaMetadata({
						title: trackName,
						artist: siteTitle,
						artwork: [{ src: albumCoverSrc, sizes: '384x384', type: 'image/png' }]
					});
					console.log('init mediaSession metadata');
				} else {
					console.log('mediaSession not available');
				}
			}
		}).fail(function (xhr, status, error) {
			console.error('Request failed:', error);
		});
	}

	function LoadAds() {
		var ref = '#LoadAds';
		var $ref = $(ref);
		if ($ref.length) {
			$ref.html('');
			requestApi(ref, '', 'loadAdsPWA', 'GET').done(function (res) {
				var LoadAds = '';
				if (res.data) {
					var data = res.data;
					var imageUrl = `${CONFIG.pathSystem}public/banner/${data.image}`;
					var imageTag = data.link ? `<a href="${data.link}" target="${data.link_target}" id="${data.id}">
                        <img class="img-fluid" src="${imageUrl}" alt="${data.title}"></a>` :
						`<img class="img-fluid" src="${imageUrl}" alt="${data.title}">`;
					LoadAds = imageTag;
				}
				$ref.html(LoadAds);
			});
		}
	}

	function clickAds() {
		var $ref = $('#LoadAds');
		if ($ref.length) {
			$ref.on('click', function (e) {
				var data = new FormData();
				var id = $(this).children('a').attr('id');
				data.append('id', id);
				requestApi('#notref', data, 'clickAds', 'POST');
			});
		}
	}

	setTimeout(playingNow, 1200);
	setTimeout(() => {
		LoadAds();
		clickAds();
	}, 2000);
	setInterval(playingNow, 90000);
	setInterval(LoadAds, 120000);

	// Detecta se o dispositivo está no iOS
	const isIOS = () => {
		const userAgent = navigator.userAgent;
		const isIPadOrIPhoneOrIPod = /iPad|iPhone|iPod/.test(userAgent);
		const isMac = userAgent.includes("Mac") && "ontouchend" in document;
		return isIPadOrIPhoneOrIPod || isMac;
	}
	// Detects standalone mode
	const isInStandaloneMode = () => ('standalone' in window.navigator) && (window.navigator.standalone);

	// Verifica se deve exibir notificação popup de instalação:
	if (isIOS() && !isInStandaloneMode()) {
		$('#installModalIos').modal('show');
	} else {
		// Detectar outros Dispositivos
		let installEvent = null;
		const installButton = document.querySelector("#install");

		window.addEventListener("beforeinstallprompt", (e) => {
			e.preventDefault();
			console.log("Ready to install...");
			installEvent = e;
			$('#installModal').modal('show');
		});

		if (installButton) {
			installButton.addEventListener("click", function () {
				if (installEvent) {
					installEvent.prompt();
					installEvent.userChoice.then((choiceResult) => {
						if (choiceResult.outcome === 'accepted') {
							console.log('User accepted');
							$('#installModal').modal('hide');
						} else {
							console.log('User dismissed');
						}
						installEvent = null;
					});
				}
			});
		}
	}

})(jQuery);
