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

	// -------------------------------------------------------------------------
	// Orphan scanner
	// -------------------------------------------------------------------------

	var allOrphans   = [];
	var totalScanned = 0;
	var totalAttachments = 0;

	function resetScan() {
		allOrphans       = [];
		totalScanned     = 0;
		totalAttachments = 0;
		$( '#smc-orphan-tbody' ).empty();
		$( '#smc-results' ).hide();
		$( '#smc-empty' ).hide();
		$( '#smc-summary' ).empty();
		$( '#smc-delete-status' ).text( '' );
		$( '#smc-select-all' ).prop( 'checked', false );
	}

	function setProgress( scanned, total ) {
		var pct = total > 0 ? Math.round( ( scanned / total ) * 100 ) : 0;
		$( '#smc-progress-bar-inner' ).css( 'width', pct + '%' );
		$( '#smc-progress-label' ).text( scanned + ' / ' + total + ' (' + pct + '%)' );
	}

	function buildRow( item ) {
		var thumb = item.thumbnail_url
			? '<img src="' + escAttr( item.thumbnail_url ) + '" class="smc-thumb" alt="" loading="lazy">'
			: '<span style="color:#aaa">—</span>';

		var preview = item.url
			? '<a href="' + escAttr( item.url ) + '" target="_blank" rel="noopener">' + smcData.i18n.view + '</a>'
			: '';

		return '<tr data-id="' + parseInt( item.id, 10 ) + '">' +
			'<td><input type="checkbox" class="smc-cb" value="' + parseInt( item.id, 10 ) + '"></td>' +
			'<td>' + thumb + '</td>' +
			'<td><strong>' + escHtml( item.filename || item.title ) + '</strong></td>' +
			'<td>' + escHtml( item.filesize_human ) + '</td>' +
			'<td>' + escHtml( item.upload_date ) + '</td>' +
			'<td>' + preview + '</td>' +
		'</tr>';
	}

	function scanBatch( offset ) {
		$.post( smcData.ajaxUrl, {
			action : 'smc_scan_orphans',
			nonce  : smcData.nonce,
			offset : offset,
			limit  : 50,
		} )
		.done( function ( res ) {
			if ( ! res.success ) {
				showScanError( res.data && res.data.message ? res.data.message : smcData.i18n.error );
				return;
			}

			var data = res.data;
			totalAttachments = data.total;
			totalScanned     = offset + 50;
			if ( totalScanned > totalAttachments ) {
				totalScanned = totalAttachments;
			}

			setProgress( totalScanned, totalAttachments );

			if ( data.orphans && data.orphans.length ) {
				$.each( data.orphans, function ( i, item ) {
					allOrphans.push( item );
					$( '#smc-orphan-tbody' ).append( buildRow( item ) );
				} );
			}

			if ( data.done ) {
				finishScan();
			} else {
				scanBatch( offset + 50 );
			}
		} )
		.fail( function () {
			showScanError( smcData.i18n.error );
		} );
	}

	function finishScan() {
		$( '#smc-progress-wrap' ).hide();
		$( '#smc-scan-btn' ).prop( 'disabled', false ).text( smcData.i18n.scanAgain || 'Scan Again' );
		$( '#smc-scan-status' ).text( smcData.i18n.scanComplete );

		if ( allOrphans.length === 0 ) {
			$( '#smc-empty' ).show();
		} else {
			var totalSize = 0;
			$.each( allOrphans, function ( i, item ) {
				totalSize += parseInt( item.filesize, 10 ) || 0;
			} );

			$( '#smc-summary' ).html(
				'<strong>' +
				allOrphans.length + ' ' + ( smcData.i18n.orphansFound || 'orphan file(s) found' ) +
				' — ' + formatBytes( totalSize ) + ' ' + ( smcData.i18n.total || 'total' ) +
				'</strong>'
			);
			$( '#smc-results' ).show();
		}
	}

	function showScanError( msg ) {
		$( '#smc-progress-wrap' ).hide();
		$( '#smc-scan-btn' ).prop( 'disabled', false );
		$( '#smc-scan-status' ).text( msg ).css( 'color', '#cc1818' );
	}

	// -------------------------------------------------------------------------
	// Delete selected
	// -------------------------------------------------------------------------

	function getSelectedIds() {
		var ids = [];
		$( '.smc-cb:checked' ).each( function () {
			ids.push( $( this ).val() );
		} );
		return ids;
	}

	function deleteBatch( ids ) {
		$( '#smc-delete-btn' ).prop( 'disabled', true );
		$( '#smc-delete-status' ).text( smcData.i18n.deleting ).css( 'color', '#646970' );

		$.post( smcData.ajaxUrl, {
			action : 'smc_delete_orphans',
			nonce  : smcData.nonce,
			ids    : ids,
		} )
		.done( function ( res ) {
			if ( ! res.success ) {
				$( '#smc-delete-status' ).text( res.data && res.data.message ? res.data.message : smcData.i18n.error ).css( 'color', '#cc1818' );
				$( '#smc-delete-btn' ).prop( 'disabled', false );
				return;
			}

			var deleted = res.data.deleted || [];
			var skipped = res.data.skipped || [];

			// Remove deleted rows from the table.
			$.each( deleted, function ( i, id ) {
				$( '#smc-orphan-tbody tr[data-id="' + id + '"]' ).remove();
				allOrphans = allOrphans.filter( function ( o ) { return parseInt( o.id, 10 ) !== parseInt( id, 10 ); } );
			} );

			var msg = smcData.i18n.deleteComplete.replace( '%d', deleted.length );
			if ( skipped.length ) {
				msg += ' (' + skipped.length + ' ' + ( smcData.i18n.skipped || 'skipped — still in use' ) + ')';
			}
			$( '#smc-delete-status' ).text( msg ).css( 'color', '#2e7d32' );
			$( '#smc-delete-btn' ).prop( 'disabled', false );
			$( '#smc-select-all' ).prop( 'checked', false );

			// Update summary.
			if ( allOrphans.length === 0 ) {
				$( '#smc-results' ).hide();
				$( '#smc-empty' ).show();
			} else {
				$( '#smc-summary strong' ).text( allOrphans.length + ' ' + ( smcData.i18n.orphansFound || 'orphan file(s) found' ) );
			}
		} )
		.fail( function () {
			$( '#smc-delete-status' ).text( smcData.i18n.error ).css( 'color', '#cc1818' );
			$( '#smc-delete-btn' ).prop( 'disabled', false );
		} );
	}

	// -------------------------------------------------------------------------
	// Modal
	// -------------------------------------------------------------------------

	function showModal( message, onConfirm ) {
		$( '#smc-modal-message' ).text( message );
		$( '#smc-modal-overlay' ).show();

		$( '#smc-modal-confirm' ).off( 'click' ).on( 'click', function () {
			hideModal();
			onConfirm();
		} );

		$( '#smc-modal-cancel' ).off( 'click' ).on( 'click', hideModal );
		$( '#smc-modal-overlay' ).off( 'click' ).on( 'click', function ( e ) {
			if ( e.target === this ) { hideModal(); }
		} );
	}

	function hideModal() {
		$( '#smc-modal-overlay' ).hide();
	}

	// -------------------------------------------------------------------------
	// Helpers
	// -------------------------------------------------------------------------

	function escHtml( str ) {
		return $( '<div>' ).text( str || '' ).html();
	}

	function escAttr( str ) {
		return $( '<div>' ).text( str || '' ).html().replace( /"/g, '&quot;' );
	}

	function formatBytes( bytes ) {
		if ( bytes >= 1073741824 ) { return ( bytes / 1073741824 ).toFixed( 1 ) + ' GB'; }
		if ( bytes >= 1048576 )    { return ( bytes / 1048576 ).toFixed( 1 ) + ' MB'; }
		if ( bytes >= 1024 )       { return ( bytes / 1024 ).toFixed( 1 ) + ' KB'; }
		return bytes + ' B';
	}

	// -------------------------------------------------------------------------
	// Event bindings (run after DOM ready)
	// -------------------------------------------------------------------------

	$( function () {

		// Scan button.
		$( '#smc-scan-btn' ).on( 'click', function () {
			resetScan();
			$( this ).prop( 'disabled', true );
			$( '#smc-scan-status' ).text( smcData.i18n.scanning ).css( 'color', '#646970' );
			$( '#smc-progress-wrap' ).show();
			setProgress( 0, 1 );
			scanBatch( 0 );
		} );

		// Select all checkbox.
		$( '#smc-select-all' ).on( 'change', function () {
			$( '.smc-cb' ).prop( 'checked', $( this ).is( ':checked' ) );
		} );

		// Uncheck "select all" if any individual checkbox is unchecked.
		$( '#smc-orphan-tbody' ).on( 'change', '.smc-cb', function () {
			if ( ! $( this ).is( ':checked' ) ) {
				$( '#smc-select-all' ).prop( 'checked', false );
			}
		} );

		// Delete selected button.
		$( '#smc-delete-btn' ).on( 'click', function () {
			var ids = getSelectedIds();
			if ( ids.length === 0 ) {
				alert( smcData.i18n.noSelection );
				return;
			}
			showModal(
				smcData.i18n.confirmDelete + ' (' + ids.length + ' file(s))',
				function () { deleteBatch( ids ); }
			);
		} );

		// Close modal on Escape key.
		$( document ).on( 'keydown', function ( e ) {
			if ( e.key === 'Escape' ) { hideModal(); }
		} );

		// Sync folders button (Settings page).
		$( document ).on( 'click', '#smc-sync-folders', function () {
			var $btn    = $( this );
			var $result = $( '#smc-sync-result' );
			var nonce   = $btn.data( 'nonce' );

			$btn.prop( 'disabled', true );
			$result.text( 'Syncing…' );

			$.post(
				( typeof smcData !== 'undefined' ? smcData.ajaxUrl : ajaxurl ),
				{ action: 'smc_sync_folders', nonce: nonce }
			).done( function ( response ) {
				if ( response.success ) {
					$result.text( response.data.message );
				} else {
					$result.text( response.data && response.data.message ? response.data.message : 'Error.' );
				}
			} ).fail( function () {
				$result.text( 'Request failed.' );
			} ).always( function () {
				$btn.prop( 'disabled', false );
			} );
		} );

	} );

} )( jQuery );
