/* MerchantKits Attendance Manager — admin scripts */
( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		bindConfirmations();
		bindTestConnection();
	} );

	/**
	 * Confirm destructive links flagged with .mkam-delete.
	 */
	function bindConfirmations() {
		var links = document.querySelectorAll( '.mkam-delete' );
		Array.prototype.forEach.call( links, function ( link ) {
			link.addEventListener( 'click', function ( e ) {
				if ( ! window.confirm( mkamAdmin.i18n.confirmDelete ) ) {
					e.preventDefault();
				}
			} );
		} );
	}

	/**
	 * Wire the "Test Connection" button on the AI settings tab.
	 */
	function bindTestConnection() {
		var button = document.getElementById( 'mkam-test-connection' );
		if ( ! button ) {
			return;
		}

		button.addEventListener( 'click', function () {
			var result = document.getElementById( 'mkam-test-connection-result' );
			result.textContent = '';
			button.disabled = true;

			var body = new FormData();
			body.append( 'action', 'mkam_test_connection' );
			body.append( 'nonce', mkamAdmin.nonce );

			fetch( mkamAdmin.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				body: body
			} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( res ) {
					result.textContent = ' ' + ( res.data && res.data.message ? res.data.message : '' );
					result.style.color = res.success ? '#16a34a' : '#dc2626';
				} )
				.catch( function () {
					result.textContent = ' Error';
					result.style.color = '#dc2626';
				} )
				.finally( function () {
					button.disabled = false;
				} );
		} );
	}
} )();
