/**
 * Shared "Email" recipient-picker modal.
 *
 * Powers the "Email Conversation" (Quick Actions) and "Email Review Link"
 * (Blog draft Actions) buttons. A trigger is any element with:
 *   data-sitestaffr-email="conversation" | "review_link"
 *   data-id="<call_id | post_id>"
 *
 * The modal lists the configured notification recipients as checkboxes so the
 * user emails only the person who asked — no inbox bloat for everyone else.
 *
 * Expects window.sitestaffrEmailModal: { ajaxurl, nonce, recipients[], i18n{} }.
 *
 * @since 1.28.0
 */
( function () {
	var cfg = window.sitestaffrEmailModal;
	if ( ! cfg ) {
		return;
	}
	var i18n = cfg.i18n || {};
	var overlay = null;
	var controller = null;

	function t( key, fallback ) {
		return i18n[ key ] || fallback;
	}

	function closeModal() {
		if ( controller ) {
			controller.close();
		}
	}

	function buildRecipientRows() {
		var recipients = cfg.recipients || [];
		if ( ! recipients.length ) {
			return '<p class="sitestaffr-em-empty">' + t( 'noRecipients', 'No notification recipients are configured yet.' ) + '</p>';
		}
		return recipients.map( function ( email, i ) {
			var safe = String( email ).replace( /"/g, '&quot;' );
			var checked = 0 === i ? ' checked' : '';
			return '<label class="sitestaffr-em-row"><input type="checkbox" value="' + safe + '"' + checked + '> <span>' + safe + '</span></label>';
		} ).join( '' );
	}

	function openModal( type, id ) {
		closeModal();

		var title = 'conversation' === type
			? t( 'conversationTitle', 'Email conversation' )
			: t( 'reviewTitle', 'Email review link' );

		overlay = document.createElement( 'div' );
		overlay.className = 'sitestaffr-modal-overlay';
		overlay.style.display = 'none';
		overlay.innerHTML =
			'<div class="sitestaffr-modal sitestaffr-modal--confirm" role="dialog" aria-modal="true" aria-label="' + title + '">' +
				'<div class="sitestaffr-modal-header">' +
					'<h2>' + title + '</h2>' +
					'<button type="button" class="sitestaffr-modal-close" aria-label="' + t( 'cancel', 'Cancel' ) + '">' +
						'<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>' +
					'</button>' +
				'</div>' +
				'<div class="sitestaffr-modal-body">' +
					'<p class="sitestaffr-em-sub">' + t( 'choose', 'Choose who should receive this email.' ) + '</p>' +
					'<div class="sitestaffr-em-list">' + buildRecipientRows() + '</div>' +
					'<p class="sitestaffr-em-status" role="status"></p>' +
				'</div>' +
				'<div class="sitestaffr-modal-footer">' +
					'<button type="button" class="button sitestaffr-em-cancel">' + t( 'cancel', 'Cancel' ) + '</button>' +
					'<button type="button" class="button button-primary sitestaffr-em-send">' + t( 'send', 'Send' ) + '</button>' +
				'</div>' +
			'</div>';

		document.body.appendChild( overlay );

		controller = window.SiteStaffrModal.enhance( overlay, {
			onClose: function () {
				if ( overlay && overlay.parentNode ) {
					overlay.parentNode.removeChild( overlay );
				}
				overlay = null;
				controller = null;
			}
		} );

		overlay.querySelector( '.sitestaffr-em-cancel' ).addEventListener( 'click', closeModal );
		overlay.querySelector( '.sitestaffr-em-send' ).addEventListener( 'click', function () {
			send( type, id );
		} );
		controller.open();
	}

	function send( type, id ) {
		var checks = overlay.querySelectorAll( '.sitestaffr-em-list input[type=checkbox]:checked' );
		var statusEl = overlay.querySelector( '.sitestaffr-em-status' );
		var sendBtn = overlay.querySelector( '.sitestaffr-em-send' );

		var recipients = Array.prototype.map.call( checks, function ( c ) { return c.value; } );
		if ( ! recipients.length ) {
			statusEl.textContent = t( 'pickOne', 'Choose at least one recipient.' );
			statusEl.className = 'sitestaffr-em-status sitestaffr-em-error';
			return;
		}

		sendBtn.disabled = true;
		statusEl.textContent = t( 'sending', 'Sending…' );
		statusEl.className = 'sitestaffr-em-status';

		var body = new URLSearchParams();
		body.append( 'action', 'conversation' === type ? 'sitestaffr_email_conversation' : 'sitestaffr_email_review_link' );
		body.append( 'nonce', cfg.nonce );
		body.append( 'conversation' === type ? 'call_id' : 'post_id', id );
		recipients.forEach( function ( r ) { body.append( 'recipients[]', r ); } );

		fetch( cfg.ajaxurl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body.toString()
		} ).then( function ( r ) { return r.json(); } ).then( function ( res ) {
			if ( res && res.success ) {
				statusEl.textContent = ( res.data && res.data.message ) || t( 'sent', 'Email sent.' );
				statusEl.className = 'sitestaffr-em-status sitestaffr-em-success';
				setTimeout( closeModal, 1500 );
			} else {
				sendBtn.disabled = false;
				statusEl.textContent = ( res && res.data && res.data.message ) || t( 'error', 'Something went wrong.' );
				statusEl.className = 'sitestaffr-em-status sitestaffr-em-error';
			}
		} ).catch( function () {
			sendBtn.disabled = false;
			statusEl.textContent = t( 'error', 'Something went wrong.' );
			statusEl.className = 'sitestaffr-em-status sitestaffr-em-error';
		} );
	}

	document.addEventListener( 'click', function ( e ) {
		var trigger = e.target.closest( '[data-sitestaffr-email]' );
		if ( ! trigger ) {
			return;
		}
		e.preventDefault();
		openModal( trigger.getAttribute( 'data-sitestaffr-email' ), trigger.getAttribute( 'data-id' ) );
	} );
} )();
