/**
 * Biscotti CMP — Tools / Website Scanner (local admin script)
 *
 * Triggers an asynchronous website scan through the authenticated admin-ajax
 * proxy (biscotti_proxy -> trigger-scan). The scan is queued server-side and
 * processed by a worker, so on success the page reloads after a short delay to
 * surface the new entry in the scan-history table. All local, no remote code.
 *
 * @package Biscotti_CMP
 */
( function ( $ ) {
	'use strict';

	var cfg = window.biscottiAdmin || {};
	var i18n = cfg.i18n || {};
	function t( k, f ) { return i18n[ k ] || f; }

	function setStatus( msg, isError ) {
		var el = document.getElementById( 'biscotti-scan-status' );
		if ( ! el ) { return; }
		el.textContent = msg;
		el.style.color = isError ? '#dc2626' : '#64748b';
	}

	$( function () {
		var $btn = $( '#biscotti-start-scan' );
		if ( ! $btn.length ) { return; }

		$btn.on( 'click', function () {
			var original = $btn.html();
			$btn.prop( 'disabled', true ).text( t( 'scanning', 'Scanning…' ) );
			setStatus( t( 'scanStarted', 'Scan started — analyzing your site…' ), false );

			$.ajax( {
				url: cfg.ajaxUrl,
				method: 'POST',
				data: {
					action: 'biscotti_proxy',
					nonce: cfg.nonce,
					proxy_action: 'trigger-scan',
					payload: JSON.stringify( {} )
				}
			} )
				.done( function ( res ) {
					if ( res && res.success ) {
						setStatus( '✅ ' + t( 'scanQueued', 'Scan queued. Refreshing…' ), false );
						setTimeout( function () { window.location.reload(); }, 3000 );
					} else {
						$btn.prop( 'disabled', false ).html( original );
						setStatus( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
					}
				} )
				.fail( function () {
					$btn.prop( 'disabled', false ).html( original );
					setStatus( '❌ ' + t( 'connectionError', 'Connection error' ), true );
				} );
		} );
	} );
} )( jQuery );
