/* MerchantKits Attendance Manager — AI insights dashboard */
( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		bind( 'mkam-generate-summary', 'mkam-summary-result', summaryRequest );
		bind( 'mkam-detect-patterns', 'mkam-patterns-result', patternsRequest );
		// Pro: natural-language query (elements only present with an active license).
		bind( 'mkam-nl-query', 'mkam-nl-result', nlQueryRequest );
	} );

	/**
	 * Build the natural-language query request.
	 *
	 * @return {Object} Request descriptor.
	 */
	function nlQueryRequest() {
		return {
			path: '/ai/query',
			body: { question: val( 'mkam-nl-query-input' ) }
		};
	}

	/**
	 * Bind a generate button to a REST request and result container.
	 *
	 * @param {string}   buttonId  Button element ID.
	 * @param {string}   resultId  Result container ID.
	 * @param {Function} builder   Returns { path, body }.
	 */
	function bind( buttonId, resultId, builder ) {
		var button = document.getElementById( buttonId );
		var result = document.getElementById( resultId );
		if ( ! button || ! result ) {
			return;
		}

		button.addEventListener( 'click', function () {
			var req = builder();
			button.disabled = true;
			result.innerHTML = '<span class="mkam-spinner"></span>';

			fetch( mkamAdmin.restUrl + req.path, {
				method: 'POST',
				credentials: 'same-origin',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': mkamAdmin.restNonce
				},
				body: JSON.stringify( req.body )
			} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( res ) {
					result.textContent = extract( res );
				} )
				.catch( function () {
					result.textContent = 'Request failed.';
				} )
				.finally( function () {
					button.disabled = false;
				} );
		} );
	}

	/**
	 * Build the monthly summary request.
	 *
	 * @return {Object} Request descriptor.
	 */
	function summaryRequest() {
		return {
			path: '/ai/summary',
			body: {
				month: parseInt( val( 'mkam-summary-month' ), 10 ),
				year: parseInt( val( 'mkam-summary-year' ), 10 )
			}
		};
	}

	/**
	 * Build the pattern detection request.
	 *
	 * @return {Object} Request descriptor.
	 */
	function patternsRequest() {
		return {
			path: '/ai/patterns',
			body: {
				date_from: val( 'mkam-patterns-from' ),
				date_to: val( 'mkam-patterns-to' )
			}
		};
	}

	/**
	 * Extract a human-readable string from the API response.
	 *
	 * @param {Object} res Response object.
	 * @return {string} Text to display.
	 */
	function extract( res ) {
		if ( res && res.summary ) {
			return res.summary;
		}
		if ( res && res.patterns ) {
			return res.patterns;
		}
		if ( res && res.answer ) {
			return res.answer;
		}
		if ( res && res.message ) {
			return res.message;
		}
		return 'No response.';
	}

	/**
	 * Read a field value by ID.
	 *
	 * @param {string} id Element ID.
	 * @return {string} Value.
	 */
	function val( id ) {
		var el = document.getElementById( id );
		return el ? el.value : '';
	}
} )();
