/**
 * Wohno — deactivation feedback modal (Plugins page).
 *
 * Intercepts our plugin's "Deactivate" link, asks (optionally) for a reason,
 * and — only if the user chooses "send" — opens a pre-filled e-mail they
 * control. Nothing is transmitted automatically. Then it proceeds to the
 * original deactivation URL.
 */
( function () {
	'use strict';

	var cfg = window.wohnoFeedback || {};
	if ( ! cfg.plugin ) {
		return;
	}

	var overlay = document.querySelector( '[data-wohno-fb]' );
	var row = document.querySelector( 'tr[data-plugin="' + cfg.plugin + '"]' );
	var link = row ? row.querySelector( '.deactivate a' ) : null;
	if ( ! overlay || ! link ) {
		return;
	}

	var deactivateUrl = link.getAttribute( 'href' );

	function open() {
		overlay.classList.add( 'is-open' );
	}
	function close() {
		overlay.classList.remove( 'is-open' );
	}
	function go() {
		window.location.href = deactivateUrl;
	}

	link.addEventListener( 'click', function ( e ) {
		e.preventDefault();
		open();
	} );

	overlay.addEventListener( 'click', function ( e ) {
		if ( e.target === overlay ) {
			close();
		}
	} );
	document.addEventListener( 'keydown', function ( e ) {
		if ( 'Escape' === e.key && overlay.classList.contains( 'is-open' ) ) {
			close();
		}
	} );

	var skip = overlay.querySelector( '[data-wohno-fb-skip]' );
	if ( skip ) {
		skip.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			go();
		} );
	}

	var send = overlay.querySelector( '[data-wohno-fb-send]' );
	if ( send ) {
		send.addEventListener( 'click', function () {
			var checked = overlay.querySelector( 'input[name="wohno_fb_reason"]:checked' );
			var reasonLabel = checked ? checked.parentNode.textContent.trim() : '';
			var messageEl = overlay.querySelector( '[data-wohno-fb-message]' );
			var message = messageEl ? messageEl.value.trim() : '';

			var body = 'Grund: ' + reasonLabel + '\n\n' + message + '\n\n— ' + ( cfg.site || '' );
			var href = 'mailto:' + cfg.mailto +
				'?subject=' + encodeURIComponent( cfg.subject || 'Feedback' ) +
				'&body=' + encodeURIComponent( body );

			// Open the user's mail client, then continue to deactivate.
			window.location.href = href;
			setTimeout( go, 300 );
		} );
	}
} )();
