function playAudio() {
    const audio = document.getElementById("audio");
    audio.play();
}

function pauseAudio() {
    const audio = document.getElementById("audio");
    audio.pause();
}

let musicMode = false;
function toggleMusic() {
    musicMode = !musicMode;
    if (musicMode) {
        $(".btn_audio").each(idx => $(".btn_audio").eq(idx).text($(".btn_audio").eq(idx).data("text-off")));
        playAudio();
    }
    else {
        $(".btn_audio").each(idx => $(".btn_audio").eq(idx).text($(".btn_audio").eq(idx).data("text-on")));
        pauseAudio();
    }
}

function hackPentagon() {
	const accept = confirm('Вы нажали кнопку взлома Пентагона.\nВы уверены, что хотите взломать Пентагон?', 'Взлом Пентагона');
	if (!accept)
		return;

	$("html").css("background-color", "black");
	document.body.innerHTML = '<div id=\'dv\'></div>';
	document.body.style['background-color'] = 'black';
	document.body.style['color'] = 'yellow';
	document.body.style['margin'] = '20px';
	const dv = document.getElementById('dv');

	let i = 1;
	let t = setInterval(function () {
		let d = document.createElement('div');
		d.innerText = `Подождите, идет атака на Пентагон: ${i}%`;
		dv.prepend(d);
		if (i === 100) {
			let d2 = document.createElement('div');
			d2.style['color'] = 'green';
			d2.innerHTML = `<b>Поздравляю! ПЕНТАГОН УСПЕШНО ВЗЛОМАН.</b>`;
			dv.prepend(d2);
			clearTimeout(t);
		} else {
			i++;
		}
	}, 100);
}

function initHorizontalScroll(container) {
    const $container = $(container);
    const $scrollWrapper = $container.find('.AppScroll_container__TSykR');
    const $leftBtn = $container.find('.scrollButton_left');
    const $rightBtn = $container.find('.scrollButton_right');

    function updateButtons() {
        const scrollLeft = $scrollWrapper.scrollLeft();
        const maxScrollLeft = $scrollWrapper[0].scrollWidth - $scrollWrapper.width();

        $leftBtn.toggleClass('AppScroll_buttonHidden__TQwow', scrollLeft <= 10);
        $rightBtn.toggleClass('AppScroll_buttonHidden__TQwow', scrollLeft >= maxScrollLeft - 10);
    }

    function checkVisibility() {
        const needsScroll = $scrollWrapper[0].scrollWidth > $scrollWrapper.width();
        $leftBtn.css('display', needsScroll ? '' : 'none');
        $rightBtn.css('display', needsScroll ? '' : 'none');

        if (needsScroll) {
            updateButtons();
        }
    }

    $leftBtn.on('click', function () {
        $scrollWrapper.animate({
            scrollLeft: $scrollWrapper.scrollLeft() - $scrollWrapper.width() * 0.8
        }, 300);
    });

    $rightBtn.on('click', function () {
        $scrollWrapper.animate({
            scrollLeft: $scrollWrapper.scrollLeft() + $scrollWrapper.width() * 0.8
        }, 300);
    });

    $scrollWrapper.on('scroll', updateButtons);
    $(window).on('resize', checkVisibility);

    checkVisibility();
}

function fillWeather() {
	$(".pwrs-weather-hidable").hide();
	$(".pwrs-weather-opacity").css('opacity', '.1');
	$(".pwrs-weather-spinable").html("<i class=\"fa fa-spinner fa-pulse fa-fw\" style='color: #bbb'></i>");
	$(".pwrs-state").text("Выполняется загрузка данных о погоде");

	$.ajax('/api/weathers', {
		success: (d) => {
			console.log('w.success', d);

			const pm = d.current.temperatureC > 0 ? '+' : d.current.temperatureC < 0 ? '-' : ' ';

			$(".pwrs-current-pm").text(pm);
			$(".pwrs-current-temp").text(d.current.temperatureC);

			$(".pwrs-current-icon").html(`<img src='${d.current.conditionIcon}' />`);

			$(".pwrs-current-feelsliketemp").text(`${pm}${d.current.feelsLikeC}°`);
			$(".pwrs-current-cond-text").text(d.current.conditionText);


			$(".pwrs-current-wind").text(d.current.windKph);
			$(".pwrs-current-press").text(d.current.pressureMb);
			$(".pwrs-current-humidity").text(d.current.humidity);
			$(".pwrs-current-uv").text(d.current.uv);

			var lis = [];
			for (const idx in d.todayHourly) {
				const h = d.todayHourly[idx];
				const hpm = h.temp > 0 ? '+' : h.temp < 0 ? '-' : ' ';
				lis.push(`<li class="AppHourlyItem_container__aqC1z"><div aria-hidden="true" class="AppHourlyItem_content__MoqYX"><time class="AppHourlyItem_time__515ZC">${h.title}</time><div class="AppHourlyItem_center__AJ7yk"><img src='${h.conditionIcon}' style='width: 32px;' /></div><p class="AppHourlyItem_main__HNbqX">${hpm}${h.temp}°</p></div></li>`);
			}
			lis.push('<li class="AppHourlyItem_separator__cLM0_"></li>');
			for (const idx in d.tomorrowHourly) {
				const h = d.tomorrowHourly[idx];
				const hpm = h.temp > 0 ? '+' : h.temp < 0 ? '-' : ' ';
				lis.push(`<li class="AppHourlyItem_container__aqC1z"><div aria-hidden="true" class="AppHourlyItem_content__MoqYX"><time class="AppHourlyItem_time__515ZC">${h.title}</time><div class="AppHourlyItem_center__AJ7yk"><img src='${h.conditionIcon}' style='width: 32px;' /></div><p class="AppHourlyItem_main__HNbqX">${hpm}${h.temp}°</p></div></li>`);
			}
			$(".pwrs-weather-hourly").html(lis.join('\n'));

			var lids = [];
			let lastIcon = '';
			$(".AppShortForecastDay_container__r4hyT").remove();
			for (var idx in d.next3Days) {
				const dy = d.next3Days[idx];
				const alt = idx % 2 === 1 ? ' AppShortForecastDay_container_alternative__ERpaq' : '';
				const maxPm = dy.maxTemp > 0 ? '+' : dy.maxTemp < 0 ? '-' : ' ';
				const minPm = dy.minTemp > 0 ? '+' : dy.minTemp < 0 ? '-' : ' ';
				lastIcon = dy.conditionIcon;

				lids.push(`<div class="AppShortForecastDay_container__r4hyT${alt}">
                <a rel="nofollow" class="AppLink_link___0246 AppShortForecastDay_head__5ya1y" data-internal="true" href="javascript:void(0)">
                    <span class="AppShortForecastDay_title__2NpIg">${dy.title}</span>
                    <span class="AppShortForecastDay_subtitle__hv_2V">${dy.subTitle}</span>
                    <img src='${dy.conditionIcon}' style='width: 32px;' />
                </a>
                <span class="AppShortForecastDay_temperature__DV3oM">${maxPm}${dy.maxTemp}°</span>
                <div class="AppShortForecastDay_content__e_oar"></div>
                <span class="AppShortForecastDay_temperature__DV3oM">${minPm}${dy.minTemp}°</span>
            </div>`);
			}

			for (var idx = 3; idx < 10; idx++) {
				const alt = idx % 2 === 1 ? ' AppShortForecastDay_container_alternative__ERpaq' : '';
				lids.push(`<div class="AppShortForecastDay_container__r4hyT${alt}" style='opacity: .5'>
                <a rel="nofollow" class="AppLink_link___0246 AppShortForecastDay_head__5ya1y" data-internal="true" href="javascript:void(0)">
                    <span class="AppShortForecastDay_title__2NpIg">-</span>
                    <span class="AppShortForecastDay_subtitle__hv_2V">-</span>
                    <img src='${lastIcon}' style='width: 32px;' />
                </a>
                <span class="AppShortForecastDay_temperature__DV3oM">-</span>
                <div class="AppShortForecastDay_content__e_oar"></div>
                <span class="AppShortForecastDay_temperature__DV3oM">-</span>
            </div>`);
			}

			$(".pwrs-weather-daily").prepend($(lids.join('\n')));

			$(".pwrs-weather-opacity").css('opacity', '');
			$(".pwrs-weather-hidable").show();
			$(".pwrs-state").text("У природы нет плохой погоды");
		},
		error: (xhr) => {
			$(".pwrs-state").html(`<b style='color: red'>${xhr.responseText}</b>`);
		}
	});
	
}

function init() {
	$(".btn_reload_waether").click(fillWeather);
	$(".btn_audio").click(toggleMusic);
	$(".btn_pentagon").click(hackPentagon);

	$('.AppHourly_container__4bfEv').each(function () {
		initHorizontalScroll(this);
	});

	fillWeather();
}

$().ready(init);
