/**
 * Guardian Shield — Admin JavaScript
 *
 * Handles:
 *  - Dashboard stats refresh & Chart.js rendering
 *  - AJAX scan triggers (malware, file integrity baseline)
 *  - IP management (blacklist / whitelist / remove)
 *  - Settings form save
 *  - Log clearing / lockout clearing
 *  - Tab switching (settings, logs)
 *  - Progress bars & toast notifications
 *
 * All AJAX calls use window.gs_admin (localised via wp_localize_script).
 *   gs_admin.ajax_url  — admin-ajax.php URL
 *   gs_admin.nonce     — wp_create_nonce('gs_admin_nonce')
 *   gs_admin.strings   — localised UI strings
 *
 * @package GuardianShield
 * @since   1.0.0
 */

/* global Chart, gs_admin */
( function ( $ ) {
	'use strict';

	// =========================================================
	// Utility helpers
	// =========================================================

	/**
	 * Display a floating toast notification.
	 *
	 * @param {string} message   Human-readable message.
	 * @param {string} type      'success' | 'error' | 'warning' | 'info'
	 * @param {number} duration  Auto-dismiss delay in ms (0 = no auto-dismiss).
	 */
	function showToast( message, type = 'info', duration = 4000 ) {
		const colours = {
			success : '#22c55e',
			error   : '#ef4444',
			warning : '#f59e0b',
			info    : '#3b82f6',
		};

		const $toast = $( '<div class="gs-toast"></div>' )
			.css( {
				borderLeftColor : colours[ type ] || colours.info,
			} )
			.html( `<span class="gs-toast-icon gs-toast-${type}"></span><span class="gs-toast-msg">${ message }</span>` )
			.appendTo( '#gs-toast-container' );

		// Slide in
		setTimeout( () => $toast.addClass( 'gs-toast--visible' ), 10 );

		if ( duration > 0 ) {
			setTimeout( () => {
				$toast.removeClass( 'gs-toast--visible' );
				setTimeout( () => $toast.remove(), 400 );
			}, duration );
		}

		// Click to dismiss
		$toast.on( 'click', function () {
			$( this ).removeClass( 'gs-toast--visible' );
			setTimeout( () => $( this ).remove(), 400 );
		} );
	}

	/**
	 * Build and inject the toast container once on DOM ready.
	 */
	function initToastContainer() {
		if ( ! $( '#gs-toast-container' ).length ) {
			$( 'body' ).append( '<div id="gs-toast-container"></div>' );
		}
	}

	/**
	 * Animate a progress bar element.
	 *
	 * @param {jQuery} $bar       The .gs-progress-bar element.
	 * @param {number} targetPct  Target percentage (0-100).
	 * @param {number} duration   Animation duration in ms.
	 */
	function animateProgressBar( $bar, targetPct, duration = 800 ) {
		$bar.css( 'width', '0%' );
		setTimeout( () => {
			$bar.css( {
				transition : `width ${ duration }ms ease`,
				width      : `${ Math.min( Math.max( targetPct, 0 ), 100 ) }%`,
			} );
		}, 50 );
	}

	/**
	 * Generic AJAX helper.
	 *
	 * @param {string}   action    wp_ajax_{action} action name.
	 * @param {Object}   data      Extra POST data.
	 * @param {Function} onSuccess Success callback( responseData ).
	 * @param {Function} onError   Error callback( message ).
	 */
	function gsAjax( action, data = {}, onSuccess = null, onError = null ) {
		$.ajax( {
			url    : gs_admin.ajax_url,
			method : 'POST',
			data   : {
				action,
				nonce : gs_admin.nonce,
				...data,
			},
			success( response ) {
				if ( response.success ) {
					if ( onSuccess ) onSuccess( response.data );
				} else {
					const msg = response.data?.message || gs_admin.strings.generic_error;
					if ( onError ) onError( msg );
					else showToast( msg, 'error' );
				}
			},
			error( _jqXHR, _textStatus, errorThrown ) {
				const msg = errorThrown || gs_admin.strings.generic_error;
				if ( onError ) onError( msg );
				else showToast( msg, 'error' );
			},
		} );
	}

	// =========================================================
	// Tab switching (shared across settings & logs pages)
	// =========================================================

	function initTabs() {
		$( document ).on( 'click', '.gs-tab-btn', function () {
			const $btn    = $( this );
			const target  = $btn.data( 'tab' );
			const $parent = $btn.closest( '.gs-tabs-wrapper, .gs-settings-wrap, .gs-logs-wrap' );

			$parent.find( '.gs-tab-btn' ).removeClass( 'gs-tab-btn--active' );
			$btn.addClass( 'gs-tab-btn--active' );

			$parent.find( '.gs-tab-panel' ).hide().removeClass( 'gs-tab-panel--active' );
			$parent.find( `#gs-tab-${ target }` ).show().addClass( 'gs-tab-panel--active' );
		} );

		// Activate first tab in each group on load
		$( '.gs-tab-btn:first-of-type' ).trigger( 'click' );
	}

	// =========================================================
	// Security score gauge (SVG arc animation)
	// =========================================================

	function initSecurityGauge() {
		const $gauge = $( '#gs-security-gauge' );
		if ( ! $gauge.length ) return;

		const score = parseInt( $gauge.data( 'score' ), 10 ) || 0;
		const arc   = $gauge.find( '.gs-gauge-arc' );

		if ( ! arc.length ) return;

		// Arc is a semicircle: total circumference depends on r=90 → C = π * r ≈ 282.7
		const circumference = Math.PI * 90;
		const dashOffset    = circumference - ( circumference * score ) / 100;

		setTimeout( () => {
			arc.css( {
				strokeDasharray  : circumference,
				strokeDashoffset : dashOffset,
				transition       : 'stroke-dashoffset 1s ease',
			} );

			// Colour by score
			let colour = '#ef4444'; // red
			if ( score >= 80 )      colour = '#22c55e'; // green
			else if ( score >= 60 ) colour = '#f59e0b'; // amber

			arc.attr( 'stroke', colour );
		}, 200 );
	}

	// =========================================================
	// Dashboard — Chart.js attack breakdown chart
	// =========================================================

	let attackChart = null;

	function initAttackChart() {
		const canvas = document.getElementById( 'gs-attack-chart' );
		if ( ! canvas ) return;

		const labels = JSON.parse( canvas.dataset.labels || '[]' );
		const counts = JSON.parse( canvas.dataset.counts || '[]' );

		if ( attackChart ) {
			attackChart.destroy();
		}

		attackChart = new Chart( canvas, {
			type : 'bar',
			data : {
				labels,
				datasets : [
					{
						label           : gs_admin.strings.attacks_label || 'Attacks',
						data            : counts,
						backgroundColor : 'rgba(59,130,246,0.75)',
						borderColor     : 'rgba(59,130,246,1)',
						borderWidth     : 1,
						borderRadius    : 4,
					},
				],
			},
			options : {
				responsive          : true,
				maintainAspectRatio : false,
				plugins             : {
					legend : { display : false },
					tooltip : {
						callbacks : {
							label : ( ctx ) => ` ${ ctx.parsed.y } ${ gs_admin.strings.attacks_label || 'attacks' }`,
						},
					},
				},
				scales : {
					y : {
						beginAtZero : true,
						ticks       : { color : '#94a3b8', precision : 0 },
						grid        : { color : 'rgba(255,255,255,0.05)' },
					},
					x : {
						ticks : { color : '#94a3b8' },
						grid  : { display : false },
					},
				},
			},
		} );
	}

	// =========================================================
	// Dashboard — live stats refresh
	// =========================================================

	function refreshDashboardStats() {
		gsAjax( 'gs_get_dashboard_stats', {}, function ( data ) {
			[
				[ '#gs-stat-attacks',  data.attacks_24h  ],
				[ '#gs-stat-blocked',  data.blocked_24h  ],
				[ '#gs-stat-logins',   data.logins_24h   ],
				[ '#gs-stat-threats',  data.scan_threats ],
			].forEach( ( [ selector, value ] ) => {
				const $el = $( selector );
				if ( $el.length ) $el.text( value ?? 0 );
			} );
		} );
	}

	// =========================================================
	// Malware Scanner — run scan button
	// =========================================================

	function initRunScan() {
		$( document ).on( 'click', '#gs-run-scan, .gs-quick-scan', function () {
			const $btn   = $( this );
			const $wrap  = $( '#gs-scan-progress-wrap' );
			const $bar   = $( '#gs-scan-progress-bar' );
			const $msg   = $( '#gs-scan-message' );

			$btn.prop( 'disabled', true ).text( gs_admin.strings.scanning || 'Scanning…' );
			$wrap.show();
			animateProgressBar( $bar, 30 );
			if ( $msg.length ) $msg.text( gs_admin.strings.scan_running || 'Scan in progress, please wait…' );

			gsAjax(
				'gs_run_scan',
				{},
				function ( data ) {
					animateProgressBar( $bar, 100 );
					$btn.prop( 'disabled', false ).text( gs_admin.strings.run_scan || 'Run Scan' );

					const msg = data.message || gs_admin.strings.scan_complete;
					showToast( msg, 'success' );
					if ( $msg.length ) $msg.text( msg );

					// Reload table if present
					if ( $( '#gs-scan-results-table' ).length ) {
						setTimeout( () => window.location.reload(), 1500 );
					}
				},
				function ( err ) {
					animateProgressBar( $bar, 0 );
					$btn.prop( 'disabled', false ).text( gs_admin.strings.run_scan || 'Run Scan' );
					showToast( err, 'error' );
				}
			);
		} );
	}

	// =========================================================
	// File Monitor — rebuild baseline
	// =========================================================

	function initRebuildBaseline() {
		$( document ).on( 'click', '#gs-rebuild-baseline, .gs-quick-baseline', function () {
			const $btn = $( this );

			if ( ! window.confirm( gs_admin.strings.confirm_baseline || 'Rebuild the file hash baseline? This may take a moment.' ) ) {
				return;
			}

			$btn.prop( 'disabled', true ).text( gs_admin.strings.rebuilding || 'Rebuilding…' );

			gsAjax(
				'gs_build_baseline',
				{},
				function ( data ) {
					$btn.prop( 'disabled', false ).text( gs_admin.strings.rebuild_baseline || 'Rebuild Baseline' );
					showToast( data.message || gs_admin.strings.baseline_done, 'success' );
				},
				function ( err ) {
					$btn.prop( 'disabled', false ).text( gs_admin.strings.rebuild_baseline || 'Rebuild Baseline' );
					showToast( err, 'error' );
				}
			);
		} );
	}

	// =========================================================
	// IP Management (Firewall page)
	// =========================================================

	function initIpManagement() {

		// Add IP (blacklist / whitelist)
		$( document ).on( 'submit', '#gs-add-ip-form', function ( e ) {
			e.preventDefault();

			const $form   = $( this );
			const $btn    = $form.find( 'button[type="submit"]' );
			const ip      = $form.find( '[name="gs_ip_address"]' ).val().trim();
			const type    = $form.find( '[name="gs_rule_type"]' ).val();
			const reason  = $form.find( '[name="gs_reason"]' ).val().trim();

			if ( ! ip ) {
				showToast( gs_admin.strings.ip_required || 'Please enter an IP address.', 'warning' );
				return;
			}

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

			gsAjax(
				'gs_manage_ip',
				{ ip_action: 'add', ip, reason, rule_type: type },
				function ( data ) {
					showToast( data.message || gs_admin.strings.ip_added, 'success' );
					$form[ 0 ].reset();
					$btn.prop( 'disabled', false );
					setTimeout( () => window.location.reload(), 1000 );
				},
				function ( err ) {
					showToast( err, 'error' );
					$btn.prop( 'disabled', false );
				}
			);
		} );

		// Remove IP rule
		$( document ).on( 'click', '.gs-remove-ip', function () {
			const $btn = $( this );
			const id   = $btn.data( 'id' );

			if ( ! window.confirm( gs_admin.strings.confirm_remove_ip || 'Remove this IP rule?' ) ) {
				return;
			}

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

			gsAjax(
				'gs_manage_ip',
				{ ip_action: 'remove', rule_id: id },
				function ( data ) {
					showToast( data.message || gs_admin.strings.ip_removed, 'success' );
					$btn.closest( 'tr' ).fadeOut( 400, function () { $( this ).remove(); } );
				},
				function ( err ) {
					showToast( err, 'error' );
					$btn.prop( 'disabled', false ).text( gs_admin.strings.remove || 'Remove' );
				}
			);
		} );
	}

	// =========================================================
	// Settings — AJAX save
	// =========================================================

	function initSettingsSave() {
		$( document ).on( 'click', '#gs-save-settings', function () {
			const $btn  = $( this );
			const $form = $( '#gs-settings-form' );

			if ( ! $form.length ) return;

			$btn.prop( 'disabled', true ).text( gs_admin.strings.saving || 'Saving…' );

			// Collect all form fields (including unchecked checkboxes)
			const formData = {};
			$form.find( 'input[type="checkbox"]' ).each( function () {
				formData[ $( this ).attr( 'name' ) ] = $( this ).is( ':checked' ) ? '1' : '0';
			} );
			$form.find( 'input:not([type="checkbox"]), select, textarea' ).each( function () {
				formData[ $( this ).attr( 'name' ) ] = $( this ).val();
			} );

			gsAjax(
				'gs_save_settings',
				formData,  // send flat — PHP reads $_POST['gs_*'] directly
				function ( data ) {
					$btn.prop( 'disabled', false ).text( gs_admin.strings.save_settings || 'Save Settings' );
					// data may be a plain string or an object with .message
					const msg = ( typeof data === 'string' ? data : data?.message ) || gs_admin.strings.settings_saved || 'Settings saved.';
					showToast( msg, 'success' );

					// Slide-in confirmation notice
					const $notice = $( '#gs-settings-saved-notice' );
					if ( $notice.length ) {
						$notice.slideDown( 300 );
						setTimeout( () => $notice.slideUp( 300 ), 3000 );
					}
				},
				function ( err ) {
					$btn.prop( 'disabled', false ).text( gs_admin.strings.save_settings || 'Save Settings' );
					showToast( err, 'error' );
				}
			);
		} );
	}

	// =========================================================
	// Logs — clear logs
	// =========================================================

	function initClearLogs() {
		$( document ).on( 'click', '.gs-clear-logs', function () {
			const $btn    = $( this );
			const logType = $btn.data( 'log-type' ) || 'attack';

			if ( ! window.confirm( gs_admin.strings.confirm_clear_logs || 'Clear all logs? This cannot be undone.' ) ) {
				return;
			}

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

			gsAjax(
				'gs_clear_logs',
				{ log_type: logType },
				function ( data ) {
					showToast( data.message || gs_admin.strings.logs_cleared, 'success' );

					// Empty matching table body
					$( `.gs-log-table[data-log-type="${ logType }"] tbody` ).html(
						`<tr><td colspan="10" style="text-align:center;padding:2rem;color:#64748b">${ gs_admin.strings.no_logs || 'No log entries found.' }</td></tr>`
					);
					$btn.prop( 'disabled', false );
				},
				function ( err ) {
					showToast( err, 'error' );
					$btn.prop( 'disabled', false );
				}
			);
		} );
	}

	// =========================================================
	// Login Security — clear lockout for a specific IP
	// =========================================================

	function initClearLockout() {
		$( document ).on( 'click', '.gs-clear-lockout', function () {
			const $btn = $( this );
			const ip   = $btn.data( 'ip' );

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

			gsAjax(
				'gs_clear_lockout',
				{ ip: ip },
				function ( data ) {
					showToast( data.message || `Lockout cleared for ${ ip }`, 'success' );
					$btn.closest( 'tr' ).fadeOut( 400, function () { $( this ).remove(); } );
				},
				function ( err ) {
					showToast( err, 'error' );
					$btn.prop( 'disabled', false ).text( gs_admin.strings.clear || 'Clear' );
				}
			);
		} );
	}

	// =========================================================
	// Security score — quick actions on overview page
	// =========================================================

	function initQuickActions() {
		// "Run Scan" and "Rebuild Baseline" delegated above.
		// The Settings shortcut is a simple link — no JS needed.

		// Auto-refresh stats every 60 seconds on overview page
		if ( $( '#gs-overview-page' ).length ) {
			setInterval( refreshDashboardStats, 60_000 );
		}
	}

	// =========================================================
	// Toggle password visibility (API key fields, etc.)
	// =========================================================

	function initPasswordToggle() {
		$( document ).on( 'click', '.gs-toggle-visibility', function () {
			const $btn   = $( this );
			const $input = $btn.prev( 'input' );

			if ( $input.attr( 'type' ) === 'password' ) {
				$input.attr( 'type', 'text' );
				$btn.text( gs_admin.strings.hide || 'Hide' );
			} else {
				$input.attr( 'type', 'password' );
				$btn.text( gs_admin.strings.show || 'Show' );
			}
		} );
	}

	// =========================================================
	// Confirm-before-submit for destructive inline forms
	// =========================================================

	function initDestructiveConfirm() {
		$( document ).on( 'click', '[data-gs-confirm]', function ( e ) {
			const message = $( this ).data( 'gs-confirm' );
			if ( ! window.confirm( message ) ) {
				e.preventDefault();
				e.stopImmediatePropagation();
			}
		} );
	}

	// =========================================================
	// Copy-to-clipboard helper (used for secret key display)
	// =========================================================

	function initCopyToClipboard() {
		$( document ).on( 'click', '.gs-copy-btn', function () {
			const $btn    = $( this );
			const target  = $btn.data( 'copy-target' );
			const $source = $( target );

			if ( ! $source.length ) return;

			navigator.clipboard
				.writeText( $source.text() || $source.val() )
				.then( () => {
					const original = $btn.text();
					$btn.text( gs_admin.strings.copied || 'Copied!' );
					setTimeout( () => $btn.text( original ), 2000 );
				} )
				.catch( () => showToast( gs_admin.strings.copy_failed || 'Copy failed.', 'error' ) );
		} );
	}

	// =========================================================
	// Collapsible sections (advanced settings panel)
	// =========================================================

	function initCollapsibles() {
		$( document ).on( 'click', '.gs-collapsible-header', function () {
			const $body = $( this ).next( '.gs-collapsible-body' );
			const $icon = $( this ).find( '.gs-collapse-icon' );

			$body.slideToggle( 250 );
			$icon.toggleClass( 'gs-collapse-icon--open' );
		} );
	}

	// =========================================================
	// DOM-ready entry point
	// =========================================================

	$( function () {
		initToastContainer();
		initTabs();
		initSecurityGauge();
		initAttackChart();
		initRunScan();
		initRebuildBaseline();
		initIpManagement();
		initSettingsSave();
		initClearLogs();
		initClearLockout();
		initQuickActions();
		initPasswordToggle();
		initDestructiveConfirm();
		initCopyToClipboard();
		initCollapsibles();

		// Initial stats load on overview
		if ( $( '#gs-overview-page' ).length ) {
			refreshDashboardStats();
		}
	} );

} )( jQuery );
