/**
 * Copyfend — content locker (front-end gate).
 * Submits the email/password, and on success reloads so the server renders the
 * now-unlocked content. The protected content is never present until unlocked.
 */
( function () {
	'use strict';

	var cfg = window.cshieldLocker || {};
	var i18n = cfg.i18n || {};

	function submit( gate ) {
		var type  = gate.getAttribute( 'data-type' );
		var post  = gate.getAttribute( 'data-post' );
		var input = gate.querySelector( '.cs-gate-input' );
		var msg   = gate.querySelector( '.cs-gate-msg' );
		var btn   = gate.querySelector( '.cs-gate-btn' );
		var value = input ? input.value.trim() : '';

		if ( ! value ) {
			if ( input ) {
				input.focus();
			}
			return;
		}

		if ( btn ) {
			btn.disabled = true;
		}
		if ( msg ) {
			msg.textContent = '';
		}

		var body = 'action=cshield_unlock' +
			'&nonce=' + encodeURIComponent( cfg.nonce ) +
			'&type=' + encodeURIComponent( type ) +
			'&post=' + encodeURIComponent( post ) +
			( 'gate' === type ? '&email=' : '&password=' ) + encodeURIComponent( value );

		window.fetch( cfg.ajax, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body
		} ).then( function ( r ) {
			return r.json();
		} ).then( function ( res ) {
			if ( res && res.success ) {
				window.location.reload();
				return;
			}
			if ( btn ) {
				btn.disabled = false;
			}
			if ( msg ) {
				msg.textContent = ( res && res.data && res.data.message ) ? res.data.message : ( i18n.errGeneric || 'Something went wrong.' );
			}
		} ).catch( function () {
			if ( btn ) {
				btn.disabled = false;
			}
			if ( msg ) {
				msg.textContent = ( i18n.errNetwork || 'Network error. Please try again.' );
			}
		} );
	}

	document.addEventListener( 'click', function ( e ) {
		var btn = e.target.closest ? e.target.closest( '.cs-gate-btn' ) : null;
		if ( ! btn ) {
			return;
		}
		var gate = btn.closest( '.cs-gate' );
		if ( gate ) {
			e.preventDefault();
			submit( gate );
		}
	} );

	document.addEventListener( 'keydown', function ( e ) {
		if ( 'Enter' !== e.key || ! e.target || ! e.target.classList || ! e.target.classList.contains( 'cs-gate-input' ) ) {
			return;
		}
		var gate = e.target.closest( '.cs-gate' );
		if ( gate ) {
			e.preventDefault();
			submit( gate );
		}
	} );
} )();
