/**
 * STRYKE WP — Admin JavaScript
 *
 * Handles:
 * - Module enable/disable toggle via AJAX
 * - Toast notification system
 * - Card active state updates
 */

(function () {
	'use strict';

	// Bail if our global config isn't available.
	if ( typeof strykeWP === 'undefined' ) {
		return;
	}

	const cfg = strykeWP;

	// =========================================================================
	// Toast system
	// =========================================================================

	function getToastWrap() {
		let wrap = document.getElementById( 'stryke-toast-wrap' );
		if ( ! wrap ) {
			wrap = document.createElement( 'div' );
			wrap.id = 'stryke-toast-wrap';
			wrap.className = 'stryke-toast-wrap';
			document.body.appendChild( wrap );
		}
		return wrap;
	}

	/**
	 * Shows a temporary toast notification.
	 *
	 * @param {string} message  - Text to display.
	 * @param {'success'|'error'|'info'} type - Visual variant.
	 * @param {number} duration - Auto-dismiss delay in ms.
	 */
	function showToast( message, type = 'info', duration = 3000 ) {
		const wrap = getToastWrap();
		const icons = {
			success: 'dashicons-yes-alt',
			error:   'dashicons-warning',
			info:    'dashicons-info',
		};

		const toast = document.createElement( 'div' );
		// SEC: Only accept known toast types to keep the className path strictly bounded.
		const safeType = Object.prototype.hasOwnProperty.call( icons, type ) ? type : 'info';
		toast.className = `stryke-toast stryke-toast--${ safeType }`;

		// SEC: Build the toast via DOM APIs instead of innerHTML — no string-to-HTML sink.
		const iconSpan = document.createElement( 'span' );
		iconSpan.className = `dashicons ${ icons[ safeType ] }`;
		iconSpan.setAttribute( 'aria-hidden', 'true' );
		toast.appendChild( iconSpan );

		const msgSpan = document.createElement( 'span' );
		msgSpan.textContent = String( message );
		toast.appendChild( msgSpan );

		wrap.appendChild( toast );

		setTimeout( () => {
			toast.style.opacity = '0';
			toast.style.transform = 'translateX(16px)';
			toast.style.transition = 'opacity 200ms, transform 200ms';
			setTimeout( () => toast.remove(), 200 );
		}, duration );
	}

	// =========================================================================
	// Utility
	// =========================================================================

	function escHtml( str ) {
		return String( str )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' );
	}

	// =========================================================================
	// Module toggle
	// =========================================================================

	/**
	 * Sends an AJAX request to toggle a module and updates the UI.
	 *
	 * @param {HTMLInputElement} checkbox - The toggle checkbox element.
	 */
	function handleModuleToggle( checkbox ) {
		const moduleId = checkbox.dataset.moduleId;
		const enabled  = checkbox.checked;
		const toggle   = checkbox.closest( '.stryke-toggle' );
		const label    = toggle ? toggle.querySelector( '.stryke-toggle__label' ) : null;
		const card     = checkbox.closest( '.stryke-card' );

		// Disable the checkbox during the request.
		checkbox.disabled = true;
		if ( toggle ) toggle.classList.add( 'stryke-toggle--saving' );

		const body = new FormData();
		body.append( 'action',    'stryke_wp_toggle_module' );
		body.append( 'nonce',     cfg.nonce );
		body.append( 'module_id', moduleId );
		body.append( 'enabled',   enabled ? '1' : '0' );

		fetch( cfg.ajaxUrl, { method: 'POST', body } )
			.then( ( res ) => {
				if ( ! res.ok ) throw new Error( `HTTP ${ res.status }` );
				return res.json();
			} )
			.then( ( data ) => {
				if ( ! data.success ) {
					throw new Error( data.data?.message || cfg.i18n.error );
				}

				// Update label text.
				if ( label ) {
					label.textContent = enabled ? cfg.i18n.enabled : cfg.i18n.disabled;
				}

				// Update card active state.
				if ( card ) {
					card.classList.toggle( 'stryke-card--active', enabled );
				}

				// Update sidebar badge for this module.
				const sidebarLink = document.querySelector(
					`.stryke-nav__item[href*="stryke-wp-${ moduleId }"]`
				);
				if ( sidebarLink ) {
					let badge = sidebarLink.querySelector( '.stryke-badge--on' );
					if ( enabled && ! badge ) {
						badge = document.createElement( 'span' );
						badge.className = 'stryke-badge stryke-badge--on';
						badge.setAttribute( 'aria-label', cfg.i18n.enabled );
						sidebarLink.appendChild( badge );
					} else if ( ! enabled && badge ) {
						badge.remove();
					}
				}

				showToast( data.data.message, 'success' );
			} )
			.catch( ( err ) => {
				// Revert checkbox state on failure.
				checkbox.checked = ! enabled;
				showToast( err.message || cfg.i18n.error, 'error' );
			} )
			.finally( () => {
				checkbox.disabled = false;
				if ( toggle ) toggle.classList.remove( 'stryke-toggle--saving' );
			} );
	}

	// =========================================================================
	// Event delegation — single listener on document for all toggles
	// =========================================================================

	document.addEventListener( 'change', function ( event ) {
		const checkbox = event.target;
		if (
			checkbox.tagName === 'INPUT' &&
			checkbox.type === 'checkbox' &&
			checkbox.classList.contains( 'stryke-toggle__input' ) &&
			checkbox.dataset.moduleId
		) {
			handleModuleToggle( checkbox );
		}
	} );

	// =========================================================================
	// Init
	// =========================================================================

	document.addEventListener( 'DOMContentLoaded', function () {
		// Nothing more needed for Phase 1.
		// Future phases will wire up module-specific JS here.
	} );

} )();
