/**
 * Agency Pulse — Admin Menu Organizer — Role Assignments UI
 *
 * Self-contained IIFE. All data supplied via aamoRoleData (wp_localize_script).
 *
 * Responsibilities:
 *  1. Mutual exclusion — a role may be checked under exactly one config card at
 *     a time. Checking a role here auto-unchecks it from every other card.
 *  2. Save — collects all checked checkboxes into a role => config_id map and
 *     posts it to the server. Does not reload on success.
 *
 * @package Agency_Pulse_Admin_Menu
 * @since   1.0.0
 */

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

	// -----------------------------------------------------------------
	// Mutual exclusion
	// -----------------------------------------------------------------

	/**
	 * When a role checkbox is checked, uncheck every other checkbox for
	 * that same role across all config cards.
	 * Unchecking a checkbox has no side effects on other cards.
	 */
	function onCheckboxChange() {
		var $cb = $( this );

		if ( ! $cb.is( ':checked' ) ) {
			return;
		}

		var role = $cb.data( 'role' );

		$( '.aamo-role-checkbox[data-role="' + role + '"]' )
			.not( $cb )
			.prop( 'checked', false );
	}

	// -----------------------------------------------------------------
	// Save
	// -----------------------------------------------------------------

	/**
	 * Walk all checked checkboxes and build the role => config_id map.
	 *
	 * @return {Object}
	 */
	function buildAssignments() {
		var assignments = {};

		$( '.aamo-role-checkbox:checked' ).each( function () {
			assignments[ $( this ).data( 'role' ) ] = $( this ).data( 'config' );
		} );

		return assignments;
	}

	function saveAssignments() {
		var $btn    = $( '#aamo-save-assignments' );
		var $status = $( '#aamo-assignments-status' );

		$btn.prop( 'disabled', true );
		$status.text( data.i18n.saving );

		$.post( data.ajaxUrl, {
			action:      data.action,
			nonce:       data.nonce,
			assignments: JSON.stringify( buildAssignments() ),
		} )
		.done( function ( resp ) {
			if ( resp.success ) {
				$status.text( data.i18n.saved );
			} else {
				var msg = ( resp.data && resp.data.message )
					? resp.data.message
					: data.i18n.error;
				$status.text( msg );
			}
		} )
		.fail( function () {
			$status.text( data.i18n.error );
		} )
		.always( function () {
			$btn.prop( 'disabled', false );
		} );
	}

	// -----------------------------------------------------------------
	// Boot
	// -----------------------------------------------------------------

	$( function () {
		$( document ).on( 'change', '.aamo-role-checkbox', onCheckboxChange );
		$( '#aamo-save-assignments' ).on( 'click', saveAssignments );
	} );

} )( jQuery, window.aamoRoleData || {} );
