/**
 * Account Block Frontend JavaScript
 *
 * Handles profile picture file selection display and form submission.
 */

(function() {
	'use strict';

	/**
	 * Initialize profile picture file input handler.
	 */
	function initProfilePictureFileInput() {
		const fileInput = document.getElementById('ambh_profile_picture_file');
		const fileNameDisplay = document.querySelector('.ambassador-account__file-name');

		if (!fileInput || !fileNameDisplay) {
			return;
		}

		fileInput.addEventListener('change', function() {
			if (this.files && this.files.length > 0) {
				const fileName = this.files[0].name;
				fileNameDisplay.textContent = fileName;
			} else {
				fileNameDisplay.textContent = '';
			}
		});
	}

	/**
	 * Handle profile picture upload form submission.
	 */
	function initProfilePictureUpload() {
		const uploadForm = document.getElementById('ambh_upload_profile_picture_form');
		if (!uploadForm) {
			return;
		}

		uploadForm.addEventListener('submit', async function(e) {
			e.preventDefault();

			const fileInput = document.getElementById('ambh_profile_picture_file');
			const nonceInput = uploadForm.querySelector('input[name="_wpnonce"]');
			const restNonce = (window.ambhConstants && ambhConstants.restNonce) ? ambhConstants.restNonce : (nonceInput ? nonceInput.value : '');

			if (!fileInput.files.length) {
				showMessage('Please select a file.', 'error');
				return;
			}

			const formData = new FormData();
			formData.append('file', fileInput.files[0]);

			try {
				const response = await fetch('/wp-json/' + ambhConstants.namespace + '/account/profile-picture/upload', {
					method: 'POST',
					headers: {
						'X-WP-Nonce': restNonce,
					},
					credentials: 'same-origin',
					body: formData,
				});

				const data = await response.json();

				if (!response.ok) {
					showMessage(data.message || 'Upload failed. Please try again.', 'error');
					return;
				}

				showMessage('Profile picture uploaded successfully.', 'success');
				fileInput.value = '';
				document.querySelector('.ambassador-account__file-name').textContent = '';

				// Reload page after short delay to show updated picture
				setTimeout(() => {
					window.location.reload();
				}, 1500);

			} catch (error) {
				console.error('Upload error:', error);
				showMessage('An error occurred during upload. Please try again.', 'error');
			}
		});
	}

	/**
	 * Handle profile picture removal form submission.
	 */
	function initProfilePictureRemove() {
		const removeForm = document.getElementById('ambh_remove_profile_picture_form');
		if (!removeForm) {
			return;
		}

		removeForm.addEventListener('submit', async function(e) {
			e.preventDefault();

			if (!confirm('Are you sure you want to remove your profile picture?')) {
				return;
			}

			const nonce = removeForm.querySelector('input[name="_wpnonce"]');
			const restNonce = (window.ambhConstants && ambhConstants.restNonce) ? ambhConstants.restNonce : (nonce ? nonce.value : '');

			try {
				const response = await fetch('/wp-json/' + ambhConstants.namespace + '/account/profile-picture/remove', {
					method: 'POST',
					headers: {
						'X-WP-Nonce': restNonce,
						'Content-Type': 'application/json',
					},
					credentials: 'same-origin',
				});

				const data = await response.json();

				if (!response.ok) {
					showMessage(data.message || 'Removal failed. Please try again.', 'error');
					return;
				}

				showMessage('Profile picture removed successfully.', 'success');

				// Reload page after short delay to show updated picture
				setTimeout(() => {
					window.location.reload();
				}, 1500);

			} catch (error) {
				console.error('Remove error:', error);
				showMessage('An error occurred during removal. Please try again.', 'error');
			}
		});
	}

	/**
	 * Handle profile form submission.
	 */
	function initProfileFormSubmit() {
		const profileForm = document.querySelector('.ambassador-account__profile-form');
		if (!profileForm) {
			return;
		}

		profileForm.addEventListener('submit', async function(e) {
			e.preventDefault();

			const nonceInput = profileForm.querySelector('input[name="_wpnonce"]');
			const restNonce = (window.ambhConstants && ambhConstants.restNonce) ? ambhConstants.restNonce : (nonceInput ? nonceInput.value : '');
			const messageContainer = document.querySelector('.ambassador-account__profile-message');

			const formData = new FormData(profileForm);
			formData.delete('ambassador_update_profile');

			try {
				const response = await fetch('/wp-json/' + ambhConstants.namespace + '/account/profile', {
					method: 'POST',
					headers: {
						'X-WP-Nonce': restNonce,
					},
					credentials: 'same-origin',
					body: formData,
				});

				const data = await response.json();

				if (!response.ok) {
					showMessage(data.message || 'Profile update failed. Please try again.', 'error', messageContainer);
					return;
				}

				showMessage(data.message || 'Profile updated successfully.', 'success', messageContainer);
			} catch (error) {
				console.error('Profile update error:', error);
				showMessage('An error occurred while saving your profile. Please try again.', 'error', messageContainer);
			}
		});
	}

	/**
	 * Show temporary message to user.
	 */
	function showMessage(message, type, container) {
		const messageDiv = document.createElement('div');
		messageDiv.className = `ambassador-account__notice ambassador-account__notice--${type}`;
		messageDiv.innerHTML = `<p>${escapeHtml(message)}</p>`;

		const target = container || document.querySelector('.ambassador-account__profile-picture-section');
		if (!target) {
			return;
		}

		target.insertAdjacentElement('afterbegin', messageDiv);
		setTimeout(() => {
			messageDiv.remove();
		}, 5000);
	}

	/**
	 * Escape HTML special characters.
	 */
	function escapeHtml(text) {
		const map = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			"'": '&#039;'
		};
		return text.replace(/[&<>"']/g, m => map[m]);
	}

	/**
	 * Handle fundraiser type tabs (My Fundraisers / My Groups / My pages).
	 */
	function initFundraiserTabs() {
		const section = document.querySelector('.ambassador-account__dashboard-section--fundraisers');
		if (!section) return;

		const tabs = section.querySelectorAll('.ambassador-account__fundraiser-tab[data-tab]');
		if (!tabs.length) return;

		const list = section.querySelector('.ambassador-account__fundraiser-list');
		const emptyMsg = section.querySelector('.ambassador-account__fundraiser-tab-empty');

		function activateTab(tabEl) {
			const type = tabEl.dataset.tab;

			tabs.forEach(function(t) {
				const active = t === tabEl;
				t.classList.toggle('ambassador-account__fundraiser-tab--active', active);
				t.setAttribute('aria-selected', active ? 'true' : 'false');
			});

			if (!list) return;
			let visible = 0;
			list.querySelectorAll('.ambassador-account__fundraiser-card').forEach(function(card) {
				const show = card.dataset.type === type;
				card.hidden = !show;
				if (show) visible++;
			});

			if (emptyMsg) emptyMsg.hidden = visible > 0;
		}

		tabs.forEach(function(tab) {
			tab.addEventListener('click', function() {
				activateTab(this);
			});
		});

		// Apply the tab that is already marked active (set server-side).
		const initial = section.querySelector('.ambassador-account__fundraiser-tab--active');
		if (initial) activateTab(initial);
	}

	/**
	 * Handle three-dots action menus on fundraiser and member cards.
	 */
	function initFundraiserMenus() {
		const section = document.querySelector('.ambassador-account__dashboard-section--fundraisers');
		if (!section) {
			return;
		}

		section.addEventListener('click', function(e) {
			const trigger = e.target.closest('.ambassador-account__fundraiser-menu-trigger');
			if (trigger) {
				e.stopPropagation();
				const menuId = trigger.getAttribute('aria-controls');
				const menu = menuId ? document.getElementById(menuId) : null;
				if (!menu) return;

				const isOpen = !menu.hidden;

				// Close all open menus first.
				closeAllMenus();

				if (!isOpen) {
					menu.hidden = false;
					trigger.setAttribute('aria-expanded', 'true');
					const card = trigger.closest('.ambassador-account__fundraiser-card');
					if (card) card.classList.add('has-open-menu');
				}
				return;
			}

			// Click on a menu item — close the parent menu.
			const item = e.target.closest('.ambassador-account__fundraiser-menu-item');
			if (item) {
				closeAllMenus();
			}
		});

		// Close on outside click.
		document.addEventListener('click', function() {
			closeAllMenus();
		});

		// Close on Escape.
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape') {
				const openMenu = section.querySelector('.ambassador-account__fundraiser-menu-dropdown:not([hidden])');
				if (openMenu) {
					const trigger = section.querySelector('[aria-controls="' + openMenu.id + '"]');
					closeAllMenus();
					if (trigger) trigger.focus();
				}
			}
		});

		function closeAllMenus() {
			section.querySelectorAll('.ambassador-account__fundraiser-menu-dropdown').forEach(function(menu) {
				if (!menu.hidden) {
					menu.hidden = true;
					const trigger = section.querySelector('[aria-controls="' + menu.id + '"]');
					if (trigger) trigger.setAttribute('aria-expanded', 'false');
				}
			});
			section.querySelectorAll('.ambassador-account__fundraiser-card.has-open-menu').forEach(function(card) {
				card.classList.remove('has-open-menu');
			});
		}
	}

	/**
	 * Handle "Close fundraiser" action menu button.
	 */
	function initCloseFundraiser() {
		const section = document.querySelector('.ambassador-account__dashboard-section--fundraisers');
		if (!section) return;

		section.addEventListener('click', async function(e) {
			const btn = e.target.closest('[data-action="close-fundraiser"]');
			if (!btn) return;

			e.stopPropagation();

			const card = btn.closest('.ambassador-account__fundraiser-card');
			if (!card) return;

			const fundraiserId = card.dataset.fundraiserId;
			if (!fundraiserId) return;

			if (!window.confirm('Are you sure you want to close this fundraiser? This will also close all underlying fundraisers and cannot be undone.')) {
				return;
			}

			const restNonce = (window.ambhConstants && ambhConstants.restNonce) ? ambhConstants.restNonce : '';
			btn.disabled = true;

			try {
				const response = await fetch('/wp-json/' + ambhConstants.namespace + '/fundraisers/' + fundraiserId + '/close', {
					method: 'POST',
					headers: {
						'X-WP-Nonce': restNonce,
						'Content-Type': 'application/json',
					},
					credentials: 'same-origin',
				});

				const data = await response.json();

				if (!response.ok) {
					btn.disabled = false;
					showMessage(data.message || 'Could not close fundraiser. Please try again.', 'error', card);
					return;
				}

				window.location.reload();
			} catch (error) {
				console.error('Close fundraiser error:', error);
				btn.disabled = false;
				showMessage('An error occurred. Please try again.', 'error', card);
			}
		});
	}

	/**
	 * Handle "Remove member" action menu button.
	 */
	function initRemoveMember() {
		const section = document.querySelector('.ambassador-account__dashboard-section--fundraisers');
		if (!section) return;

		section.addEventListener('click', async function(e) {
			const btn = e.target.closest('[data-action="remove-member"]');
			if (!btn) return;

			e.stopPropagation();

			const memberFundraiserId = btn.dataset.memberFundraiserId;
			if (!memberFundraiserId) return;

			const memberItem = btn.closest('.ambassador-account__fundraiser-member-item');
			const memberName = memberItem
				? memberItem.querySelector('.ambassador-account__fundraiser-member-name')?.textContent?.trim()
				: null;

			const confirmMessage = memberName
				? 'Remove ' + memberName + ' from this group? Their fundraiser will be closed and they will no longer appear as an active member.'
				: 'Remove this member from the group? Their fundraiser will be closed.';

			if (!window.confirm(confirmMessage)) {
				return;
			}

			const restNonce = (window.ambhConstants && ambhConstants.restNonce) ? ambhConstants.restNonce : '';
			btn.disabled = true;

			try {
				const response = await fetch('/wp-json/' + ambhConstants.namespace + '/fundraisers/' + memberFundraiserId + '/close', {
					method: 'POST',
					headers: {
						'X-WP-Nonce': restNonce,
						'Content-Type': 'application/json',
					},
					credentials: 'same-origin',
				});

				const data = await response.json();

				if (!response.ok) {
					btn.disabled = false;
					const card = btn.closest('.ambassador-account__fundraiser-card');
					showMessage(data.message || 'Could not remove member. Please try again.', 'error', card || section);
					return;
				}

				window.location.reload();
			} catch (error) {
				console.error('Remove member error:', error);
				btn.disabled = false;
				const card = btn.closest('.ambassador-account__fundraiser-card');
				showMessage('An error occurred. Please try again.', 'error', card || section);
			}
		});
	}

	/**
	 * Handle "Invite member" button: show/hide the inline invite form.
	 */
	function initInviteMember() {
		const section = document.querySelector('.ambassador-account__dashboard-section--fundraisers');
		if (!section) return;

		// Toggle form open when the invite button is clicked.
		section.addEventListener('click', function(e) {
			const btn = e.target.closest('[data-action="invite-member"]');
			if (!btn) return;

			e.stopPropagation();

			const fundraiserId = btn.dataset.fundraiserId;
			if (!fundraiserId) return;

			const form = document.getElementById('ambh-invite-form-' + fundraiserId);
			if (!form) return;

			const isHidden = form.hasAttribute('hidden');
			form.toggleAttribute('hidden', !isHidden);

			if (isHidden) {
				// Focus the first input when opening.
				const firstInput = form.querySelector('input[type="text"], input[type="email"]');
				if (firstInput) firstInput.focus();
			}
		});

		// Handle the Cancel button inside the form.
		section.addEventListener('click', function(e) {
			const btn = e.target.closest('[data-action="close-invite-form"]');
			if (!btn) return;

			const fundraiserId = btn.dataset.fundraiserId;
			if (!fundraiserId) return;

			const form = document.getElementById('ambh-invite-form-' + fundraiserId);
			if (form) form.setAttribute('hidden', '');
		});
	}

	// Initialize when DOM is ready
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', () => {
			initProfilePictureFileInput();
			initProfilePictureUpload();
			initProfilePictureRemove();
			initProfileFormSubmit();
			initFundraiserTabs();
			initFundraiserMenus();
			initCloseFundraiser();
			initRemoveMember();
			initInviteMember();
		});
	} else {
		initProfilePictureFileInput();
		initProfilePictureUpload();
		initProfilePictureRemove();
		initProfileFormSubmit();
		initFundraiserTabs();
		initFundraiserMenus();
		initCloseFundraiser();
		initRemoveMember();
		initInviteMember();
	}
})();
