/**
 * NR Brief Builder — wp-admin dashboard interactions.
 */
( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		var i18n       = ( window.briefifyAdminData && window.briefifyAdminData.i18n ) || {};
		var liveRegion = document.querySelector( '[data-briefify-live-region]' );

		function announce( message ) {
			if ( liveRegion ) {
				liveRegion.textContent = message;
			}
		}

		// Copy-to-clipboard buttons (the shortcode display, on both the
		// Dashboard and the Settings page). Gives both a visual ("Copied!"
		// swapped in for 2s) and an accessible (aria-live announcement)
		// confirmation — see UX_GUIDELINES.md, "Accessible feedback".
		document.querySelectorAll( '[data-briefify-copy]' ).forEach( function ( el ) {
			el.addEventListener( 'click', function () {
				// Captured fresh on every click: for the shortcode-generator's
				// dynamic button its text changes when the template changes,
				// so a value captured once at page load would go stale.
				var currentText = el.textContent;

				var done = function () {
					el.textContent = i18n.copied || 'Copied!';
					el.classList.add( 'is-copied' );
					announce( i18n.copiedAnnounce || 'Copied to clipboard.' );
					setTimeout( function () {
						el.textContent = currentText;
						el.classList.remove( 'is-copied' );
						announce( '' );
					}, 2000 );
				};

				if ( navigator.clipboard && navigator.clipboard.writeText ) {
					navigator.clipboard.writeText( currentText ).then( done );
					return;
				}

				var temp = document.createElement( 'textarea' );
				temp.value = currentText;
				temp.style.position = 'fixed';
				temp.style.opacity = '0';
				document.body.appendChild( temp );
				temp.select();
				try {
					document.execCommand( 'copy' );
					done();
				} catch ( e ) {
					// Clipboard unavailable — silently ignore.
				}
				document.body.removeChild( temp );
			} );
		} );

		// Shortcode generator + template preview (settings page): the template
		// select, the ARIA tabs, and the tabpanel all stay in sync — changing
		// any one of them updates the other two. Tabs follow the WAI-ARIA
		// "tabs with automatic activation" pattern: arrow keys both move focus
		// and select, matching the native <select> behavior right next to it.
		var select            = document.querySelector( '[data-briefify-shortcode-select]' );
		var output            = document.querySelector( '[data-briefify-shortcode-output]' );
		var previewTabs       = Array.prototype.slice.call( document.querySelectorAll( '[data-briefify-preview-tab]' ) );
		var previewInstances  = document.querySelectorAll( '[data-briefify-preview-instance]' );

		function setActiveTemplate( key, moveFocus ) {
			if ( select && select.value !== key ) {
				select.value = key;
			}
			if ( output ) {
				output.textContent = '[nr_brief template="' + key + '"]';
			}

			var focusTarget = null;

			previewTabs.forEach( function ( tab ) {
				var isActive = tab.getAttribute( 'data-briefify-preview-tab' ) === key;
				tab.classList.toggle( 'is-active', isActive );
				tab.setAttribute( 'aria-selected', isActive ? 'true' : 'false' );
				tab.setAttribute( 'tabindex', isActive ? '0' : '-1' );
				if ( isActive ) {
					focusTarget = tab;
				}
			} );

			previewInstances.forEach( function ( instance ) {
				var isActive = instance.getAttribute( 'data-briefify-preview-instance' ) === key;
				instance.classList.toggle( 'is-active', isActive );
				if ( isActive ) {
					instance.removeAttribute( 'hidden' );
				} else {
					instance.setAttribute( 'hidden', '' );
				}
			} );

			if ( moveFocus && focusTarget ) {
				focusTarget.focus();
			}
		}

		if ( select ) {
			select.addEventListener( 'change', function () {
				setActiveTemplate( select.value, false );
			} );
		}

		previewTabs.forEach( function ( tab, index ) {
			tab.addEventListener( 'click', function () {
				setActiveTemplate( tab.getAttribute( 'data-briefify-preview-tab' ), false );
			} );

			tab.addEventListener( 'keydown', function ( event ) {
				var targetIndex = null;

				switch ( event.key ) {
					case 'ArrowRight':
					case 'ArrowDown':
						targetIndex = ( index + 1 ) % previewTabs.length;
						break;
					case 'ArrowLeft':
					case 'ArrowUp':
						targetIndex = ( index - 1 + previewTabs.length ) % previewTabs.length;
						break;
					case 'Home':
						targetIndex = 0;
						break;
					case 'End':
						targetIndex = previewTabs.length - 1;
						break;
					default:
						return;
				}

				event.preventDefault();
				var targetTab = previewTabs[ targetIndex ];
				setActiveTemplate( targetTab.getAttribute( 'data-briefify-preview-tab' ), true );
			} );
		} );

		// "Send test email" button (settings page).
		var testBtn = document.querySelector( '[data-briefify-send-test]' );
		var testResult = document.querySelector( '[data-briefify-send-test-result]' );
		if ( testBtn && window.briefifyAdminData ) {
			testBtn.addEventListener( 'click', function () {
				var emailField = document.getElementById( 'briefify_notification_email' );

				if ( emailField && ! emailField.value.trim() ) {
					setResult( i18n.noEmail || 'Please set a notification email first.', true );
					return;
				}

				testBtn.disabled = true;
				setResult( i18n.sending || 'Sending…', false );

				var body = new URLSearchParams();
				body.append( 'action', 'briefify_send_test_email' );
				body.append( 'nonce', briefifyAdminData.nonce );

				fetch( briefifyAdminData.ajaxUrl, {
					method: 'POST',
					credentials: 'same-origin',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: body.toString()
				} )
					.then( function ( response ) {
						return response.json();
					} )
					.then( function ( json ) {
						testBtn.disabled = false;
						if ( json && json.success ) {
							setResult( ( json.data && json.data.message ) || i18n.sent || 'Sent.', false );
						} else {
							setResult( ( json && json.data && json.data.message ) || i18n.error || 'Failed.', true );
						}
					} )
					.catch( function () {
						testBtn.disabled = false;
						setResult( i18n.error || 'Failed.', true );
					} );
			} );
		}

		function setResult( message, isError ) {
			if ( ! testResult ) {
				return;
			}
			testResult.textContent = message;
			testResult.classList.toggle( 'briefify-admin-test-result--error', !! isError );
			announce( message );
		}
	} );
} )();
