/**
 * Truebe deactivate survey. Intercepts the plugin's Deactivate link on
 * plugins.php, shows one optional question, then follows the original
 * deactivate URL. Skip, close, Escape, and backdrop click all deactivate
 * immediately. The answer posts to truebe.io with keepalive so it
 * survives the page navigation.
 */
( function () {
	'use strict';

	if ( typeof truebeDeactivate === 'undefined' ) { return; }

	var deactivateUrl = '';

	function findLink() {
		// Row id is set by WP: tr[data-slug] with the deactivate action link.
		var row = document.querySelector( 'tr[data-slug="truebe"], tr[data-slug="truebe-fact-based-ai-chatbot"]' );
		if ( ! row ) { return null; }
		return row.querySelector( '.deactivate a' );
	}

	function sendFeedback( reason, detail ) {
		try {
			var payload = JSON.stringify( {
				kind:    'deactivate',
				reason:  reason || '',
				detail:  detail || '',
				site:    truebeDeactivate.site,
				version: truebeDeactivate.version,
			} );
			if ( navigator.sendBeacon ) {
				navigator.sendBeacon( truebeDeactivate.feedbackUrl, new Blob( [ payload ], { type: 'application/json' } ) );
			} else {
				fetch( truebeDeactivate.feedbackUrl, {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: payload,
					keepalive: true,
				} );
			}
		} catch ( e ) { /* never block deactivation */ }
	}

	function proceed() {
		window.location.href = deactivateUrl;
	}

	function closeModal() {
		var overlay = document.getElementById( 'truebe-deactivate-overlay' );
		if ( overlay ) { overlay.remove(); }
	}

	function buildModal() {
		var overlay = document.createElement( 'div' );
		overlay.id = 'truebe-deactivate-overlay';
		overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:100000;display:flex;align-items:center;justify-content:center;';

		var box = document.createElement( 'div' );
		box.style.cssText = 'background:#fff;border-radius:10px;width:min(440px,92vw);padding:24px 28px;font-size:14px;';

		var html = '<h2 style="margin:0 0 4px;font-size:17px;">' + truebeDeactivate.title + '</h2>';
		html += '<p style="margin:0 0 14px;color:#646970;">' + truebeDeactivate.question + '</p>';

		Object.keys( truebeDeactivate.reasons ).forEach( function ( key ) {
			html += '<label style="display:block;margin-bottom:8px;cursor:pointer;">';
			html += '<input type="radio" name="truebe-deactivate-reason" value="' + key + '" style="margin-right:8px;">';
			html += truebeDeactivate.reasons[ key ];
			html += '</label>';
		} );

		html += '<textarea id="truebe-deactivate-detail" rows="2" placeholder="' + truebeDeactivate.detailPlaceholder + '" style="width:100%;margin:8px 0 16px;border:1px solid #dcdcde;border-radius:6px;padding:8px 10px;box-sizing:border-box;"></textarea>';
		html += '<div style="display:flex;justify-content:flex-end;gap:10px;">';
		html += '<button type="button" id="truebe-deactivate-skip" class="button">' + truebeDeactivate.skipLabel + '</button>';
		html += '<button type="button" id="truebe-deactivate-send" class="button button-primary">' + truebeDeactivate.submitLabel + '</button>';
		html += '</div>';

		box.innerHTML = html;
		overlay.appendChild( box );
		document.body.appendChild( overlay );

		overlay.addEventListener( 'click', function ( e ) {
			if ( e.target === overlay ) { closeModal(); proceed(); }
		} );
		document.addEventListener( 'keydown', function esc( e ) {
			if ( 'Escape' === e.key ) {
				document.removeEventListener( 'keydown', esc );
				closeModal();
				proceed();
			}
		} );
		document.getElementById( 'truebe-deactivate-skip' ).addEventListener( 'click', function () {
			closeModal();
			proceed();
		} );
		document.getElementById( 'truebe-deactivate-send' ).addEventListener( 'click', function () {
			var checked = document.querySelector( 'input[name="truebe-deactivate-reason"]:checked' );
			var detail  = document.getElementById( 'truebe-deactivate-detail' ).value;
			sendFeedback( checked ? checked.value : '', detail );
			closeModal();
			proceed();
		} );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		var link = findLink();
		if ( ! link ) { return; }
		link.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			deactivateUrl = link.href;
			buildModal();
		} );
	} );
} )();