document.addEventListener('DOMContentLoaded', function () {

	function handleFormSubmit(formId, action) {
		const form = document.getElementById(formId);
		const submitButton = form?.querySelector('[type="submit"]');
		const successMessage = form?.querySelector('.cf-success');
		const errorMessage = form?.querySelector('.cf-error');

		form?.addEventListener('submit', function (e) {
			e.preventDefault();
			submitButton.classList.add('loading');

			const formData = new FormData(form);
			formData.append('action', action);
			formData.append('nonce', multicollabBlockEditorAjax.nonce);

			fetch(ajaxurl, {
				method: 'POST',
				body: formData, // Send as FormData
			})
			.then(response => {
				
				if( response.ok ) {
					successMessage.style.display = 'block';
					setTimeout(() => {
						successMessage.style.display = 'none';
					}, 3000);
				} else {
					console.log('error');
					errorMessage.style.display = 'block';
					setTimeout(() => {
						errorMessage.style.display = 'none';
					}, 3000);
				}
				
			}) // Adjust based on the expected response type
			.catch(() => {
				submitButton.classList.remove('loading');
				if (errorMessage) {
					errorMessage.style.display = 'block';
					setTimeout(() => {
						errorMessage.style.display = 'none';
					}, 3000);
				}
			});
		});
	}

	handleFormSubmit('multicollab_settings', 'multicollab_save_settings');
	handleFormSubmit('multicollab_email_notification', 'multicollab_save_email_notification');

	// Add loader on setting page 
	
	var loader = document.querySelector(".cf-settings-loader");
	if (loader) {
		setTimeout(function() {
			loader.style.transition = "opacity 0.5s ease"; // You can adjust the duration and easing
			loader.style.opacity = "0"; // Fade out effect
			setTimeout(function() {
				loader.style.display = "none"; // Hide the element after fading out
			}, 500); // This should match the duration of the transition
		}, 100);
	}

	document.querySelectorAll('.reset-filter').forEach(function (element) {
		element.addEventListener('click', function () {
			const parent = element.parentElement;
			const select = parent.querySelector('select');
			if (select) {
				select.selectedIndex = 0;
			}
			parent.submit();
		});
	});


	window.addEventListener('scroll', function () {
		/**
		 * Checks if the "load-more-activity" element is in view and clicks it if so.
		 * This function is used to automatically load more activity items when the user scrolls to the bottom of the page.
		 */
		var loadMoreActivity = document.querySelector('#cf-dashboard .load-more-activity');
		if (loadMoreActivity) {
			if (isIntoView(loadMoreActivity)) {
				loadMoreActivity.click();
			}
		}
	});

	/**
     * Handles the click event on the "Load More" button for the activity feed.
     * Fetches additional activity data from the server and appends it to the activity feed in dashboard.
     *
     * @param {Event} event - The click event object.
     */
	document.addEventListener('click', function (event) {
		if (event.target.matches('.load-more-activity')) {
			let pointer = event.target.getAttribute('data-pointer');
			let date = event.target.getAttribute('data-date');
			let postID = event.target.getAttribute('data-post');
			let categoryID = event.target.getAttribute('data-category');
			let cpt = event.target.getAttribute('data-cpt');
			let boardPosition = event.target.getAttribute('data-board-position');

			// Get all printed dates.
			let displayedDates = [];
			document.querySelectorAll('.cf-dashboard-panel__board-day').forEach(function (element) {
				displayedDates.push(element.textContent);
			});
			displayedDates = displayedDates.join('|');

			document.querySelectorAll('.load-more-activity').forEach(function (element) {
				element.remove();
			});

			fetch(ajaxurl, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				body: new URLSearchParams({
					action: 'multicollab_get_activities',
					nonce: typeof multicollabBlockEditorAjax !== 'undefined' ? multicollabBlockEditorAjax.nonce : '',
					pointer: pointer,
					date: date,
					postID: postID,
					categoryID: categoryID,
					cpt: cpt,
					boardPosition: boardPosition,
					displayedDates: displayedDates
				})
			})
			.then(response => response.text())
			.then(result => {
				document.querySelector('#cf-dashboard .cf-dashboard-panel__board-main.cf-list-view')?.insertAdjacentHTML('beforeend', result);
			})
			.catch(error => console.error('Error:', error));
		}

		 /**
		 * Handles the click event on the "Show Activity Details" button.
		 * Fetches the activity details from the server and displays them in the detail view in dashboard.
		 *
		 * @param {Event} event - The click event object.
		 */
		 if (event.target.matches('.show_activity_details')) {
			let postID = event.target.getAttribute('data-id');
	
			fetch(ajaxurl, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				body: new URLSearchParams({
					action: 'multicollab_get_activity_details',
					nonce: typeof multicollabBlockEditorAjax !== 'undefined' ? multicollabBlockEditorAjax.nonce : '',
					postID: postID
				})
			})
			.then(response => response.text())
			.then(result => {
				// Scroll to top
				window.scrollTo({ top: 200, behavior: 'smooth' });
	
				// Hide list view and show detail view
				document.querySelector('.cf-dashboard-panel__board-main.cf-list-view').style.display = 'none';
				document.querySelector('.cf-dashboard-panel__board-main.cf-detail-view').style.display = 'block';
	
				// Show detail content
				const detailElement = document.getElementById('board-item-detail');
				detailElement.style.display = 'block';
				detailElement.innerHTML = result;
	
				// Hide bulk actions
				document.querySelectorAll('.bulkactions').forEach(element => {
					element.style.display = 'none';
				});
			})
			.catch(error => console.error('Error:', error));
		}
	
		/**
		 * Handles the click event on the "Go Back" button in the activity detail view.
		 * This function restores the list view and hides the detail view, clears the detail element,
		 * and shows the bulk actions in dashboard.
		 *
		 * @param {Event} event - The click event object.
		 */
		if (event.target.matches('#activity-go-back')) {
			// Show list view and hide detail view
			document.querySelector('.cf-dashboard-panel__board-main.cf-list-view').style.display = 'block';
			document.querySelector('.cf-dashboard-panel__board-main.cf-detail-view').style.display = 'none';
	
			// Clear and show the detail element
			const detailElement = document.getElementById('board-item-detail');
			detailElement.style.display = 'block';
			detailElement.innerHTML = '';
	
			// Show bulk actions
			document.querySelectorAll('.bulkactions').forEach(function (element) {
				element.style.display = 'block';
			});
		}

	});

});
