/* eslint-disable jsdoc/require-param-type, jsdoc/empty-tags */
(function ($) {
	'use strict';
	$(document).ready(function () {
		/* eslint-disable camelcase, no-undef */
		const ajax_url = forumax_localize_script.ajaxurl;

		$('.single-filter-item a').on('click', function (e) {
			e.preventDefault();

			// Prefer the custom data_id attribute on the closest widget, fall back to the element id
			const $widget = $(this).closest('.forum-post-widget');
			const data_id = $widget.attr('data_id') || $widget.attr('id');
			const forum_value = $(this).attr('data-forum');
			const nonce = forumax_localize_script.nonce;

			$('.forum-post-widget[data_id=' + data_id + '] .single-filter-item a').removeClass('data-active');
			$(this).addClass('data-active');

			$.ajax({
				url: ajax_url,
				method: 'POST',
				data: {
					action: 'forumax_ajax_forum',
					data_forum: forum_value,
					nonce,
				},
				beforeSend() {
					$('.forum-post-widget[data_id="' + data_id + '"] #aj-post-filter-widget').html(
						'<?xml version="1.0" encoding="utf-8"?>\n' +
						'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: none; display: block; shape-rendering: auto;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">\n' +
						'<circle class="bbpc-preloader" cx="50" cy="50" r="18" stroke-width="2" stroke="#11a683" stroke-dasharray="28.274333882308138 28.274333882308138" fill="none" stroke-linecap="round">\n' +
						'  <animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1s" keyTimes="0;1" values="0 50 50;360 50 50"></animateTransform>\n' +
						'</circle>\n' +
						'</svg>'
					);
				},
				success(data) {
					$('.forum-post-widget[data_id="' + data_id + '"] #aj-post-filter-widget').html(data);
				},
				error() {
					/* eslint-disable no-console */
					console.log('Oops! Something wrong, try again!');
					/* eslint-enable no-console */
				},
			});
		});

		$('.collapse-btn-wrap, .forumax-collapse-btn-wrap').on('click', function (e) {
			e.preventDefault();
			$(this).toggleClass('active');
			// Target the corresponding collapse-wrap within the same parent
			$(this).siblings('.collapse-wrap, .forumax-collapse-wrap').slideToggle(500);
		});

	});
})(jQuery);