import jQuery from 'jquery';

( function ( $, wp, wdceoData ) {
	'use strict';
	$( function () {
		const { __ } = wp.i18n; // Import __() from wp.i18n

		const submitButton = $( '#download-preview-button' );
		if ( ! submitButton.length ) {
			return;
		}

		const sectionInput = $( '#wdevs_coe_preview_section_id' );
		submitButton.prop( 'disabled', ! sectionInput.val() );

		sectionInput.on( 'change input', function () {
			submitButton.prop( 'disabled', ! $( this ).val() );
		} );

		$( submitButton ).on( 'click', function () {
			const sectionId = $( '#wdevs_coe_preview_section_id' ).val() || 0;
			const orderId = $( '#wdevs_coe_preview_order_id' ).val() || 0;

			const $form = $( '<form>', {
				method: 'POST',
				action: wdceoData.postUrl,
				style: 'display: none;',
			} ).appendTo( 'body' );

			$form.append(
				$( '<input>', {
					type: 'hidden',
					name: 'action',
					value: wdceoData.previewAction,
				} ),
				$( '<input>', {
					type: 'hidden',
					name: 'nonce',
					value: wdceoData.nonce,
				} ),
				$( '<input>', {
					type: 'hidden',
					name: 'section_id',
					value: sectionId,
				} ),
				$( '<input>', {
					type: 'hidden',
					name: 'order_id',
					value: orderId,
				} )
			);

			$form.submit();

			setTimeout( function () {
				wp.data
					.dispatch( 'core/notices' )
					.createNotice(
						'success',
						__(
							'The file is now downloading. Please check your downloads folder.'
						)
					);
			}, 500 );
		} );
	} );
} )( jQuery, wp, wdceoData );
