jQuery(function ($) {
	let paged = 1
	const cat = aac_loadmore_params.cat || 0
	const $btn = $('#load-more-podcasts')
	const $container = $('#podcasty-list')

	$btn.on('click', function () {
		$btn.prop('disabled', true).text('Ładowanie...')

		$.ajax({
			url: aac_loadmore_params.ajax_url,
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'load_more_podcasts',
				paged: paged,
				cat: cat,
			},
			success: function (res) {
				if (res.success) {
					const $newItems = $(res.data.html).addClass('is-new')
					$container.append($newItems)

					setTimeout(() => {
						$newItems.each(function (i, el) {
							setTimeout(() => {
								$(el).removeClass('is-new')
							}, i * 100)
						})
					}, 50)

					paged = res.data.paged

					if (paged < res.data.max) {
						$btn.prop('disabled', false).text('Wczytaj więcej')
					} else {
						$btn.fadeOut()
					}
				} else {
					$btn.fadeOut()
				}
			},
			error: function () {
				$btn.text('Błąd ładowania')
			},
		})
	})
})
