/**
 * Link Assassin — frontend AJAX batch processor.
 *
 * Wires:
 *   - Scan button       : sends URLs to the scan endpoint, renders preview table
 *   - Execute button    : init job, then loop process_batch until done
 *   - Restore buttons   : per-row restore in the Restore tab
 *   - Delete-backup     : per-row drop without restoring
 *
 * No external deps beyond jQuery (already in WP admin).
 *
 * @package Tshepho\Ops
 */

( function ( $ ) {
	'use strict';

	if ( typeof window.PlatformHelmLAS === 'undefined' ) {
		return;
	}

	var cfg = window.PlatformHelmLAS;
	var $urlsField = $( '#platform-helm-la-urls' );

	function setProgress( pct, text ) {
		$( '#platform-helm-la-progress-wrap' ).show();
		$( '#platform-helm-la-progress-bar' ).css( 'width', Math.min( 100, Math.max( 0, pct ) ) + '%' );
		$( '#platform-helm-la-progress-text' ).text( text || '' );
	}

	function escapeHtml( str ) {
		if ( null === str || 'undefined' === typeof str ) {
			return '';
		}
		return String( str )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' )
			.replace( /'/g, '&#039;' );
	}

	function formatString( template, args ) {
		var idx = 0;
		return template.replace( /%(\d+\$)?[ds]/g, function ( match, posToken ) {
			if ( posToken ) {
				var pos = parseInt( posToken, 10 ) - 1;
				return 'undefined' !== typeof args[ pos ] ? args[ pos ] : match;
			}
			var val = args[ idx ];
			idx += 1;
			return 'undefined' !== typeof val ? val : match;
		} );
	}

	/* ----------------------------------------------------------------- */
	/* Scan tab                                                          */
	/* ----------------------------------------------------------------- */

	$( '#platform-helm-la-scan-btn' ).on( 'click', function () {
		var urls = $urlsField.val();
		if ( ! urls || ! urls.trim() ) {
			window.alert( cfg.i18n.noUrls );
			return;
		}
		var $btn     = $( this );
		var $results = $( '#platform-helm-la-scan-results' );
		$btn.prop( 'disabled', true ).text( cfg.i18n.scanning );
		$results.html( '<p><em>' + escapeHtml( cfg.i18n.scanning ) + '</em></p>' );

		$.post( cfg.ajaxUrl, {
			action: 'tshephos_ops_la_scan',
			nonce:  cfg.nonce,
			urls:   urls
		} ).done( function ( response ) {
			if ( ! response || ! response.success ) {
				var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
				$results.html( '<div class="notice notice-error"><p>' + escapeHtml( msg ) + '</p></div>' );
				return;
			}
			renderScanResults( $results, response.data );
		} ).fail( function () {
			$results.html( '<div class="notice notice-error"><p>' + escapeHtml( cfg.i18n.networkError ) + '</p></div>' );
		} ).always( function () {
			$btn.prop( 'disabled', false ).text( 'Run scan' );
		} );
	} );

	function renderScanResults( $target, data ) {
		var rows  = data.rows || [];
		var total = data.total_posts || 0;
		var occ   = data.total_occurrences || 0;

		var html = '<h3>' + escapeHtml( 'Scan results' ) + '</h3>';
		html += '<p>' + escapeHtml( 'Found ' + occ + ' link occurrence(s) across ' + total + ' post(s).' ) + '</p>';

		if ( ! rows.length ) {
			html += '<p><em>' + escapeHtml( 'Nothing to do.' ) + '</em></p>';
			$target.html( html );
			return;
		}

		html += '<table class="widefat striped">';
		html += '<thead><tr>';
		html += '<th>ID</th><th>Title</th><th>Type</th><th>post_content</th><th>_elementor_data</th><th>Matched URLs</th>';
		html += '</tr></thead><tbody>';

		rows.forEach( function ( row ) {
			html += '<tr>';
			html += '<td>' + escapeHtml( row.id ) + '</td>';
			html += '<td>' + escapeHtml( row.title || '(no title)' ) + '</td>';
			html += '<td><code>' + escapeHtml( row.type ) + '</code></td>';
			html += '<td>' + escapeHtml( row.content_count ) + '</td>';
			html += '<td>' + escapeHtml( row.elementor_count ) + '</td>';
			html += '<td>';
			( row.urls || [] ).forEach( function ( u ) {
				html += '<div><code style="font-size:11px;">' + escapeHtml( u ) + '</code></div>';
			} );
			html += '</td></tr>';
		} );
		html += '</tbody></table>';
		$target.html( html );
	}

	/* ----------------------------------------------------------------- */
	/* Execute tab — batched delete                                      */
	/* ----------------------------------------------------------------- */

	$( '#platform-helm-la-execute-btn' ).on( 'click', function () {
		var urls = $urlsField.val();
		if ( ! urls || ! urls.trim() ) {
			window.alert( cfg.i18n.noUrls );
			return;
		}
		if ( ! window.confirm( cfg.i18n.confirmExecute ) ) {
			return;
		}
		var $btn = $( this );
		$btn.prop( 'disabled', true ).text( cfg.i18n.starting );
		setProgress( 0, cfg.i18n.starting );
		$( '#platform-helm-la-execute-results' ).empty();

		$.post( cfg.ajaxUrl, {
			action: 'tshephos_ops_la_init',
			nonce:  cfg.nonce,
			urls:   urls
		} ).done( function ( response ) {
			if ( ! response || ! response.success ) {
				var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
				$( '#platform-helm-la-execute-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( msg ) + '</p></div>' );
				$btn.prop( 'disabled', false ).text( 'Execute' );
				setProgress( 0, '' );
				$( '#platform-helm-la-progress-wrap' ).hide();
				return;
			}
			runBatchLoop( response.data, $btn );
		} ).fail( function () {
			$( '#platform-helm-la-execute-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( cfg.i18n.networkError ) + '</p></div>' );
			$btn.prop( 'disabled', false ).text( 'Execute' );
		} );
	} );

	function runBatchLoop( init, $btn ) {
		var jobId      = init.job_id;
		var total      = init.total_posts;
		var batchSize  = init.batch_size || cfg.batchSize || 25;

		if ( 0 === total ) {
			setProgress( 100, formatString( cfg.i18n.doneSummary, [ 0, 0, 0 ] ) );
			$btn.prop( 'disabled', false ).text( 'Execute' );
			$( '#platform-helm-la-execute-results' ).html(
				'<div class="notice notice-success"><p>' + escapeHtml( 'No posts matched.' ) + '</p></div>'
			);
			return;
		}

		function nextBatch() {
			$.post( cfg.ajaxUrl, {
				action: 'tshephos_ops_la_batch',
				nonce:  cfg.nonce,
				job_id: jobId
			} ).done( function ( response ) {
				if ( ! response || ! response.success ) {
					var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
					$( '#platform-helm-la-execute-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( msg ) + '</p></div>' );
					$btn.prop( 'disabled', false ).text( 'Execute' );
					return;
				}
				var d        = response.data;
				var done     = d.done;
				var cursor   = d.cursor;
				var pct      = Math.floor( ( cursor / total ) * 100 );
				var fromIdx  = Math.max( 1, cursor - batchSize + 1 );

				setProgress(
					pct,
					formatString( cfg.i18n.processing, [ fromIdx, cursor, total ] )
				);

				if ( done ) {
					setProgress( 100, '' );
					var t = d.totals || {};
					$( '#platform-helm-la-execute-results' ).html(
						'<div class="notice notice-success"><p><strong>' + escapeHtml( cfg.i18n.doneTitle ) + ':</strong> ' +
						escapeHtml( formatString( cfg.i18n.doneSummary, [
							t.posts_modified || 0,
							t.links_removed || 0,
							t.posts_errored || 0
						] ) ) +
						'</p></div>'
					);
					$btn.prop( 'disabled', false ).text( 'Execute' );
					return;
				}
				// Continue.
				nextBatch();
			} ).fail( function () {
				$( '#platform-helm-la-execute-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( cfg.i18n.networkError ) + '</p></div>' );
				$btn.prop( 'disabled', false ).text( 'Execute' );
			} );
		}
		nextBatch();
	}

	/* ----------------------------------------------------------------- */
	/* Restore tab                                                       */
	/* ----------------------------------------------------------------- */

	$( document ).on( 'click', '.platform-helm-la-restore-btn', function () {
		if ( ! window.confirm( cfg.i18n.restoreConfirm ) ) {
			return;
		}
		var $row    = $( this ).closest( 'tr' );
		var postId  = $row.data( 'post-id' );
		var metaKey = $row.data( 'meta-key' );
		var $btn    = $( this );

		$btn.prop( 'disabled', true );

		$.post( cfg.ajaxUrl, {
			action:   'tshephos_ops_la_restore',
			nonce:    cfg.nonce,
			post_id:  postId,
			meta_key: metaKey
		} ).done( function ( response ) {
			if ( ! response || ! response.success ) {
				var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
				window.alert( msg );
				$btn.prop( 'disabled', false );
				return;
			}
			$row.fadeOut( 200, function () { $row.remove(); } );
		} ).fail( function () {
			window.alert( cfg.i18n.networkError );
			$btn.prop( 'disabled', false );
		} );
	} );

	$( document ).on( 'click', '.platform-helm-la-delete-btn', function () {
		if ( ! window.confirm( cfg.i18n.deleteConfirm ) ) {
			return;
		}
		var $row    = $( this ).closest( 'tr' );
		var postId  = $row.data( 'post-id' );
		var metaKey = $row.data( 'meta-key' );
		var $btn    = $( this );

		$btn.prop( 'disabled', true );

		$.post( cfg.ajaxUrl, {
			action:   'tshephos_ops_la_delete_backup',
			nonce:    cfg.nonce,
			post_id:  postId,
			meta_key: metaKey
		} ).done( function ( response ) {
			if ( ! response || ! response.success ) {
				window.alert( ( response && response.data && response.data.message ) || cfg.i18n.networkError );
				$btn.prop( 'disabled', false );
				return;
			}
			$row.fadeOut( 200, function () { $row.remove(); } );
		} ).fail( function () {
			window.alert( cfg.i18n.networkError );
			$btn.prop( 'disabled', false );
		} );
	} );

} )( jQuery );
