/* Aura — the Settings page.
   Two behaviours, both optional: checking the service without leaving the page, and copying a
   request id so it can be pasted into a support message. Everything else on the page is a plain
   form that works with JavaScript switched off. */

var _aipbI = ( window.wp && window.wp.i18n ) || {};
var __ = _aipbI.__ ? function ( s ) { return _aipbI.__( s, 'aipb' ); } : function ( s ) { return s; };

( function () {
	'use strict';

	var cfg = window.AIPB_SETTINGS || {};

	/* ------------------------------ Check the service ----------------------------- */

	var btn = document.getElementById( 'aipb-server-check' );
	var out = document.getElementById( 'aipb-server-status' );

	if ( btn && out ) {
		btn.addEventListener( 'click', function () {
			var field = document.getElementById( 'aipb-key' );

			say( __( 'Checking…' ), 'is-busy' );
			btn.disabled = true;

			fetch( window.ajaxurl, {
				method: 'POST',
				credentials: 'same-origin',
				body: new URLSearchParams( {
					action: 'aipb_server_health',
					_ajax_nonce: cfg.nonce || '',
					key: field ? field.value : ''
				} )
			} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( j ) {
					var ok = !! ( j && j.success );
					var msg = ( j && j.data && j.data.message ) ? j.data.message : '';
					say( msg, ok ? 'is-ok' : 'is-bad' );
				} )
				.catch( function () {
					say( __( 'check failed' ), 'is-bad' );
				} )
				.then( function () { btn.disabled = false; } );
		} );
	}

	function say( text, state ) {
		out.textContent = text;
		out.className = 'aipb-check-out ' + ( state || '' );
	}

	/* -------------------------------- Copy an id ---------------------------------- */

	// The request id is the only thing a customer can quote so that support opens the precise case:
	// selecting it by hand out of a table row is exactly the kind of friction that stops them.
	document.addEventListener( 'click', function ( e ) {
		var chip = e.target.closest ? e.target.closest( '.aipb-req' ) : null;
		if ( ! chip ) { return; }

		var id = chip.getAttribute( 'data-req' ) || chip.textContent.trim();
		copy( id ).then( function ( ok ) {
			if ( ! ok ) { return; }
			var label = chip.querySelector( 'span' );
			var was = label ? label.textContent : '';

			chip.classList.add( 'is-copied' );
			if ( label ) { label.textContent = __( 'copied' ); }

			window.setTimeout( function () {
				chip.classList.remove( 'is-copied' );
				if ( label ) { label.textContent = was; }
			}, 1200 );
		} );
	} );

	// navigator.clipboard needs a secure context: a plugin installed on plain http would lose the
	// feature entirely, so the old execCommand road stays as the fallback.
	function copy( text ) {
		if ( window.navigator.clipboard && window.isSecureContext ) {
			return window.navigator.clipboard.writeText( text )
				.then( function () { return true; } )
				.catch( function () { return legacyCopy( text ); } );
		}

		return Promise.resolve( legacyCopy( text ) );
	}

	function legacyCopy( text ) {
		var ta = document.createElement( 'textarea' );
		ta.value = text;
		ta.setAttribute( 'readonly', '' );
		ta.style.position = 'fixed';
		ta.style.opacity = '0';
		document.body.appendChild( ta );
		ta.select();

		var ok = false;
		try { ok = document.execCommand( 'copy' ); } catch ( err ) { ok = false; }
		document.body.removeChild( ta );

		return ok;
	}
}() );
