/**
 * Modal dialog management for Cart Recovery
 *
 * @package EDD\Pro\CartRecovery\Admin
 */

import { setupEddModal } from '@easy-digital-downloads/modal';
import { ajaxPost } from './ajax.js';
import { normalizeMessage } from './utils.js';

/**
 * Creates a modal manager for the cart modal dialog.
 *
 * @param {HTMLDialogElement} cartModal - The modal dialog element.
 * @param {Object}            config    - Configuration object with messages, nonce, ajaxurl.
 * @return {Object|null} Modal manager object with control methods, or null if invalid.
 */
export function createModalManager( cartModal, config ) {
	if ( ! cartModal || typeof cartModal.showModal !== 'function' ) {
		console.error( 'Cart modal dialog not found or unsupported' );
		return null;
	}

	const modalApi = setupEddModal( { dialog: cartModal } );
	if ( ! modalApi ) {
		return null;
	}

	const modalContent = cartModal.querySelector( '.edd-modal__content' );
	const modalLoading = cartModal.querySelector( '.edd-modal__loading' );
	const { messages, nonce, ajaxurl } = config;

	/**
	 * Sets the modal content HTML.
	 *
	 * @param {string} html - The HTML content to display.
	 */
	function setContent( html ) {
		modalContent.innerHTML = html;
	}

	/**
	 * Shows the loading spinner.
	 */
	function showLoading() {
		modalContent.classList.add( 'edd-hidden' );
		modalLoading.classList.remove( 'edd-hidden' );
	}

	/**
	 * Hides the loading spinner.
	 */
	function hideLoading() {
		modalLoading.classList.add( 'edd-hidden' );
		modalContent.classList.remove( 'edd-hidden' );
	}

	/**
	 * Displays an error message in the modal.
	 *
	 * @param {string|Object} text - The error message or response object.
	 */
	function showMessage( text ) {
		const message = normalizeMessage( text, messages, 'genericFailure' );
		setContent( '<div class="notice notice-error"><p>' + message + '</p></div>' );
	}

	/**
	 * Loads and displays cart details for the given cart ID.
	 *
	 * @param {string} cartId - The cart ID to load.
	 */
	function loadCartDetails( cartId ) {
		if ( ! cartId ) {
			return;
		}

		modalApi.open();
		showLoading();

		ajaxPost( ajaxurl, {
			action: 'edd_acr_load_cart_details',
			cart_id: cartId,
			nonce: nonce,
		} )
			.then( function ( res ) {
				hideLoading();
				if ( res?.success && res?.data?.html ) {
					setContent( res.data.html );
				} else {
					showMessage( res );
				}
			} )
			.catch( function ( error ) {
				hideLoading();
				console.error( 'ACR admin action failed:', error );
				showMessage( messages.networkError );
			} );
	}

	/**
	 * Resets modal to initial state.
	 */
	function reset() {
		setContent( '' );
		modalLoading.classList.add( 'edd-hidden' );
		modalContent.classList.remove( 'edd-hidden' );
	}

	cartModal.addEventListener( 'close', reset );

	return {
		loadCartDetails,
		close: modalApi.close,
		reset,
		showMessage,
	};
}
