/**
 * Masteriyo public profile frontend JS.
 *
 * @since 2.6.8
 *
 * @param {object} $ jQuery object
 * @param {object} masteriyo_data Global data object
 */
(function ($, masteriyo_data) {
	'use strict';

	var masteriyoPublicProfile = {
		// Cached elements.
		$enrolledCoursesMainContent: $(
			'#masteriyo-enrolled-courses-main-content .masteriyo-enrolled-courses--content',
		),

		$offeredCoursesMainContent: $('#masteriyo-courses-offered-main-content'),
		/**
		 * Initializes the public profile.
		 *
		 * @since 2.6.8
		 */
		init: function () {
			this.bindUIActions();
		},

		/**
		 * Binds event handlers to the pagination items.
		 *
		 * @since 2.6.8
		 *
		 * @param {object} self Current object
		 */
		bindUIActions: function () {
			var self = this;

			// Event delegation for pagination items.
			$(document.body).on(
				'click',
				'.masteriyo-courses--pagination-item a',
				function () {
					var page = $(this).data('page');
					var userId = parseInt(
						$('input[name="masteriyo_public_profile_user_id"]').val(),
					);

					var courseType = 'offered';
					var parent = '#masteriyo-courses-offered-main-content';

					if (
						$(this).parents('#masteriyo-enrolled-courses-main-content').length
					) {
						courseType = 'enrolled';
						parent = '#masteriyo-enrolled-courses-main-content';
					}

					var currentPage = $(parent)
						.find(
							'.masteriyo-courses--pagination-item.masteriyo-courses--pagination-item--active',
						)
						.find('a')
						.data('page');

					if (userId && page && currentPage && page !== currentPage) {
						self.fetchNextPage(userId, page, courseType, parent);
					}
				},
			);
		},

		/**
		 * Fetches the next page of courses.
		 *
		 * @since 2.6.8
		 *
		 * @param {number} userId User ID
		 * @param {number} page Page number
		 * @param {string} courseType Course type
		 */
		fetchNextPage: function (userId, page, courseType, parent) {
			var self = this;

			$.ajax({
				url: masteriyo_data.ajax_url,
				data: {
					action: 'masteriyo_public_profile_pagination',
					nonce: masteriyo_data.nonce,
					page: page,
					user_id: userId,
					course_type: courseType,
				},
				type: 'POST',
				beforeSend: function (jqXHR) {
					$('.masteriyo-col-right--tab-content').block(
						masteriyoPublicProfile.getBlockLoadingConfiguration(),
					);
				},
				complete: function (jqXHR, textStatus) {
					$('.masteriyo-col-right--tab-content').unblock(
						masteriyoPublicProfile.getBlockLoadingConfiguration(),
					);
				},
			})
				.done(function (res) {
					if (res.success) {
						self.updateCoursesList(res, courseType);
						self.updatePagination(res, page, parent);
					}
				})
				.fail(function (error) {
					console.error('Error fetching next page:', error);
				});
		},

		/**
		 * Updates the list of courses.
		 *
		 * @since 2.6.8
		 *
		 * @param {object} res Response object
		 * @param {string} courseType Course type
		 */
		updateCoursesList: function (res, courseType) {
			if ('offered' === courseType) {
				this.$offeredCoursesMainContent
					.find('.masteriyo-courses--content')
					.replaceWith(res.data.html);
			} else if ('enrolled' === courseType) {
				this.$enrolledCoursesMainContent.html(res.data.html);
			}
		},

		/**
		 * Updates the pagination.
		 *
		 * @since 2.6.8
		 *
		 * @param {object} res Response object
		 * @param {number} page Current page number
		 */
		updatePagination: function (res, page, parent) {
			var pagination = res.data.pagination;
			var totalPages = pagination.total_pages;
			var currentPage = pagination.current_page;

			var previousClass =
				currentPage === 1 ? 'masteriyo-courses--pagination-item--disabled' : '';
			var previousPage = currentPage === 1 ? 0 : currentPage - 1;

			var activeClass =
				currentPage === page
					? 'masteriyo-courses--pagination-item--active'
					: '';

			var nextClass =
				currentPage === totalPages
					? 'masteriyo-courses--pagination-item--disabled'
					: '';
			var nextPage = currentPage === totalPages ? 0 : currentPage + 1;

			$(parent)
				.find('.masteriyo-courses--pagination-item')
				.removeClass('masteriyo-courses--pagination-item--active');
			$(parent)
				.find('.masteriyo-courses--pagination-item.pagination-previous')
				.removeClass('masteriyo-courses--pagination-item--disabled');
			$(parent)
				.find('.masteriyo-courses--pagination-item.pagination-next')
				.removeClass('masteriyo-courses--pagination-item--disabled');

			$(parent)
				.find('.masteriyo-courses--pagination-item.pagination-previous')
				.addClass(previousClass);
			$(parent)
				.find('.masteriyo-courses--pagination-item.pagination-previous')
				.find('a')
				.data('page', previousPage);

			$(parent)
				.find('.masteriyo-courses--pagination-item')
				.find('a[data-page="' + currentPage + '"]')
				.parent('.masteriyo-courses--pagination-item')
				.not('.pagination-next')
				.not('.pagination-previous')
				.addClass(activeClass);

			$(parent)
				.find('.masteriyo-courses--pagination-item.pagination-next')
				.addClass(nextClass);
			$(parent)
				.find('.masteriyo-courses--pagination-item.pagination-next')
				.find('a')
				.data('page', nextPage);
		},

		/**
		 * Retrieves the spinner element for blocking UI during Ajax requests.
		 *
		 * @since 2.13.0
		 *
		 * @returns {string} The spinner HTML.
		 */
		getSpinner: function () {
			return '<span class="spinner" style="visibility:visible"></span>';
		},

		/**
		 * Retrieves the block loading configuration for blocking UI during Ajax requests.
		 *
		 * @since 2.13.0
		 *
		 * @returns {object} The block loading configuration.
		 */
		getBlockLoadingConfiguration: function () {
			return {
				message: this.getSpinner(),
				css: {
					border: '',
					width: '0%',
				},
				overlayCSS: {
					background: '#fff',
					opacity: 0.6,
				},
			};
		},
	};

	masteriyoPublicProfile.init();
})(jQuery, window.MASTERIYO_PUBLIC_PROFILE_DATA);
