/**
 * AccessLens — Admin JavaScript
 *
 * Handles:
 *   - EAA scope questionnaire verdict
 *   - Scan form submission via AJAX
 *   - 3-second polling loop
 *   - Results table rendering
 *   - Report download proxy
 *
 * Depends on: jQuery, accessLensData (wp_localize_script)
 *
 * @package AccessLens
 */

/* global accessLensData, jQuery */
( function ( $, config ) {
	'use strict';

	// ----------------------------------------------------------------
	// State
	// ----------------------------------------------------------------
	var pollInterval  = null;
	var POLL_MS       = 3000;
	var currentJobId  = null;

	// ----------------------------------------------------------------
	// EAA Scope Checker
	// ----------------------------------------------------------------

	/**
	 * Compute scope verdict from questionnaire inputs.
	 *
	 * Rules (orientative, not legal advice):
	 *   - Microempresa (<10 emp AND <2M EUR) con servicio digital => posible exenta
	 *   - Entidades publicas => siempre en scope
	 *   - Cualquier otra empresa digital => obligada o probablemente obligada
	 */
	function computeScopeVerdict( employees, revenue, serviceType ) {
		if ( ! employees || ! revenue || ! serviceType ) {
			return null;
		}
		if ( serviceType === 'not_digital' ) {
			return {
				type   : 'info',
				message: 'Tu actividad principal no parece ser un servicio digital en el ambito de la EAA. Consulta con un asesor legal para confirmarlo.'
			};
		}
		if ( employees === 'micro' && revenue === 'micro' ) {
			return {
				type   : 'warning',
				message: 'Posible microempresa exenta segun la EAA (Art. 4.5): menos de 10 empleados y facturacion inferior a 2 M EUR. Verifica con tu asesor legal, ya que algunas actividades pueden estar igualmente obligadas.'
			};
		}
		return {
			type   : 'error',
			message: 'Tu empresa probablemente esta en el ambito de aplicacion de la EAA y debe garantizar la accesibilidad de sus productos y servicios digitales antes del 28 de junio de 2025. Consulta con un especialista.'
		};
	}

	$( '#accesslens-check-scope' ).on( 'click', function () {
		var employees   = $( '#accesslens_employees' ).val();
		var revenue     = $( '#accesslens_revenue' ).val();
		var serviceType = $( '#accesslens_service_type' ).val();
		var verdict     = computeScopeVerdict( employees, revenue, serviceType );
		var $box        = $( '#accesslens-scope-verdict' );

		if ( ! verdict ) {
			$box.html( '<p>Completa todas las opciones para ver el diagnostico.</p>' )
				.attr( 'class', 'accesslens-scope-verdict notice notice-info' )
				.removeClass( 'hidden' );
			return;
		}

		var cssClass = {
			info   : 'notice-info',
			warning: 'notice-warning',
			error  : 'notice-error'
		}[ verdict.type ] || 'notice-info';

		$box.html( '<p><strong>Diagnostico orientativo:</strong> ' + escapeHtml( verdict.message ) + '</p>' )
			.attr( 'class', 'accesslens-scope-verdict notice ' + cssClass )
			.removeClass( 'hidden' );
	} );

	// ----------------------------------------------------------------
	// Scan form
	// ----------------------------------------------------------------

	$( '#accesslens-start-scan' ).on( 'click', function () {
		var url  = $( '#accesslens_scan_url' ).val().trim();
		var mode = $( '#accesslens_scan_mode' ).val();

		if ( ! url ) {
			alert( config.i18n.startError );
			return;
		}

		stopPolling();
		resetResults();
		showStatus( config.i18n.queued, 0, 0 );

		$.ajax( {
			url    : config.ajaxUrl,
			method : 'POST',
			data   : {
				action   : 'accesslens_start_scan',
				nonce    : config.nonce,
				scan_url : url,
				scan_mode: mode
			},
			success: function ( response ) {
				if ( ! response.success ) {
					showError( response.data.message || config.i18n.startError );
					return;
				}
				currentJobId = response.data.jobId;
				startPolling();
			},
			error: function () {
				showError( config.i18n.startError );
			}
		} );
	} );

	// ----------------------------------------------------------------
	// Polling
	// ----------------------------------------------------------------

	function startPolling() {
		pollInterval = setInterval( doPoll, POLL_MS );
		doPoll(); // immediate first poll
	}

	function stopPolling() {
		if ( pollInterval ) {
			clearInterval( pollInterval );
			pollInterval = null;
		}
	}

	function doPoll() {
		$.ajax( {
			url   : config.ajaxUrl,
			method: 'POST',
			data  : {
				action: 'accesslens_poll_scan',
				nonce : config.nonce
			},
			success: function ( response ) {
				if ( ! response.success ) {
					stopPolling();
					showError( response.data.message || config.i18n.pollError );
					return;
				}
				handleStatusUpdate( response.data );
			},
			error: function () {
				stopPolling();
				showError( config.i18n.pollError );
			}
		} );
	}

	function handleStatusUpdate( data ) {
		var status   = data.status;
		var progress = data.progress || { total: 0, done: 0 };
		var pct      = progress.total > 0 ? Math.round( ( progress.done / progress.total ) * 100 ) : 0;

		var labelMap = {
			queued     : config.i18n.queued,
			discovering: config.i18n.discovering,
			running    : config.i18n.running,
			done       : config.i18n.done,
			error      : config.i18n.error
		};
		var label = labelMap[ status ] || status;

		showStatus( label, progress.done, progress.total );
		$( '#accesslens-progress-bar' ).val( pct );
		$( '#accesslens-progress-label' ).text( progress.done + ' / ' + progress.total );

		if ( status === 'done' || status === 'error' ) {
			stopPolling();
		}

		if ( status === 'done' && Array.isArray( data.results ) && data.results.length > 0 ) {
			renderResults( data.results );
		}

		if ( status === 'error' && data.error ) {
			showError( data.error );
		}
	}

	// ----------------------------------------------------------------
	// Results rendering
	// ----------------------------------------------------------------

	function renderResults( results ) {
		var $body    = $( '#accesslens-results-body' ).empty();
		var $wrap    = $( '#accesslens-results-wrap' ).removeClass( 'hidden' );
		var totalAll = 0;

		results.forEach( function ( page ) {
			var sum      = page.summary || {};
			var topRules = buildTopRules( page.violations );

			$body.append(
				'<tr>' +
				'<td><a href="' + escapeAttr( page.url ) + '" target="_blank" rel="noopener">' + escapeHtml( page.url ) + '</a></td>' +
				'<td>' + escapeHtml( page.pageTitle ) + '</td>' +
				'<td class="accesslens-col-critical accesslens-severity-critical">' + escapeHtml( String( sum.critical || 0 ) ) + '</td>' +
				'<td class="accesslens-col-serious accesslens-severity-serious">' + escapeHtml( String( sum.serious || 0 ) ) + '</td>' +
				'<td class="accesslens-col-moderate accesslens-severity-moderate">' + escapeHtml( String( sum.moderate || 0 ) ) + '</td>' +
				'<td class="accesslens-col-minor accesslens-severity-minor">' + escapeHtml( String( sum.minor || 0 ) ) + '</td>' +
				'<td>' + escapeHtml( String( sum.total || 0 ) ) + '</td>' +
				'<td><small>' + escapeHtml( topRules ) + '</small></td>' +
				'</tr>'
			);
			totalAll += ( sum.total || 0 );
		} );

		$( '#accesslens-results-summary' ).html(
			'<p>' +
			escapeHtml( String( results.length ) ) + ' pagina(s) analizadas. ' +
			escapeHtml( String( totalAll ) ) + ' violaciones detectadas en total.' +
			'</p>'
		);

		$wrap.get( 0 ).scrollIntoView( { behavior: 'smooth' } );
	}

	/**
	 * Build a short string of top rule IDs from violations array.
	 *
	 * @param {Array} violations
	 * @returns {string}
	 */
	function buildTopRules( violations ) {
		if ( ! Array.isArray( violations ) || violations.length === 0 ) {
			return '—';
		}
		var sorted = violations.slice().sort( function ( a, b ) {
			return ( b.nodes || 0 ) - ( a.nodes || 0 );
		} );
		return sorted.slice( 0, 3 ).map( function ( v ) {
			return v.id + ' (' + v.impact + ')';
		} ).join( ', ' );
	}

	// ----------------------------------------------------------------
	// Report download
	// ----------------------------------------------------------------

	$( '#accesslens-download-report' ).on( 'click', function () {
		var form = document.createElement( 'form' );
		form.method = 'POST';
		form.action = config.ajaxUrl;

		var fields = {
			action           : 'accesslens_get_report',
			nonce            : config.nonce,
			site_name        : $( '#accesslens_report_site_name' ).val(),
			entity_type      : $( '#accesslens_report_entity_type' ).val(),
			contact_email    : $( '#accesslens_report_contact_email' ).val(),
			contact_url      : $( '#accesslens_report_contact_url' ).val(),
			prepared_by      : $( '#accesslens_report_prepared_by' ).val(),
			site_url         : $( '#accesslens_scan_url' ).val()
		};

		Object.keys( fields ).forEach( function ( key ) {
			var input = document.createElement( 'input' );
			input.type  = 'hidden';
			input.name  = key;
			input.value = fields[ key ];
			form.appendChild( input );
		} );

		document.body.appendChild( form );
		form.submit();
		document.body.removeChild( form );
	} );

	// ----------------------------------------------------------------
	// UI helpers
	// ----------------------------------------------------------------

	function showStatus( label, done, total ) {
		$( '#accesslens-scan-status' ).removeClass( 'hidden' );
		$( '#accesslens-status-text' ).text( label );
		$( '#accesslens-progress-bar' ).val( total > 0 ? Math.round( ( done / total ) * 100 ) : 0 );
		$( '#accesslens-progress-label' ).text( total > 0 ? done + ' / ' + total : '' );
	}

	function showError( msg ) {
		$( '#accesslens-scan-status' ).removeClass( 'hidden' );
		$( '#accesslens-status-text' ).text( config.i18n.error + ': ' + msg );
	}

	function resetResults() {
		$( '#accesslens-results-wrap' ).addClass( 'hidden' );
		$( '#accesslens-results-body' ).empty();
		$( '#accesslens-results-summary' ).empty();
		currentJobId = null;
	}

	/**
	 * Escape string for HTML text content.
	 *
	 * @param {string} str
	 * @returns {string}
	 */
	function escapeHtml( str ) {
		var div = document.createElement( 'div' );
		div.appendChild( document.createTextNode( str ) );
		return div.innerHTML;
	}

	/**
	 * Escape string for use in an HTML attribute.
	 *
	 * @param {string} str
	 * @returns {string}
	 */
	function escapeAttr( str ) {
		return String( str )
			.replace( /&/g, '&amp;' )
			.replace( /"/g, '&quot;' )
			.replace( /'/g, '&#39;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' );
	}

}( jQuery, accessLensData ) );
