/**
 * @file assets/js/adminjs/mbs-admin-csv-export.js
 * CSV, XLSX, and Settings JSON export handlers on Settings -> Import / Export.
 * Uses MBS_AdminUtils.triggerBlobDownload() and setExportButtonState() (D-007).
 * XHR with responseType='blob' is used for XLSX to preserve binary data.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;
	var sprintf = wp.i18n.sprintf;

	// -- Helpers --------------------------------------------------------------

	/* escHtml / escAttr -- use shared MBS_AdminUtils (mbs-admin-utils.js) */
	var escHtml             = MBS_AdminUtils.escHtml;
	var escAttr             = MBS_AdminUtils.escAttr;
	var triggerBlobDownload = MBS_AdminUtils.triggerBlobDownload;
	var setExportBtnState   = MBS_AdminUtils.setExportButtonState;

	/**
	 * Show or clear an inline status panel adjacent to the given anchor element.
	 *
	 * @param {jQuery} $anchor  Element after which the panel is inserted.
	 * @param {string} msgId    Unique ID for the message div (without '#').
	 * @param {string} text     Message text. Empty string clears the panel.
	 * @param {string} type     'error' | 'success' | 'info'
	 */
	function mbsExportMsg( $anchor, msgId, text, type ) {
		var $msg = $( '#' + msgId );
		if ( ! $msg.length ) {
			$anchor.after( '<div id="' + escAttr( msgId ) + '" style="margin-top:8px; display:none;"></div>' );
			$msg = $( '#' + msgId );
		}
		if ( ! text ) {
			$msg.hide().empty();
			return;
		}
		var cls = { error: 'notice-error', success: 'notice-success', info: 'notice-info' }[ type ] || 'notice-info';
		$msg
			.removeClass( 'notice-error notice-success notice-info' )
			.addClass( 'notice ' + cls )
			.html( '<p>' + escHtml( text ) + '</p>' )
			.show();
	}

	// -- Export All Books as CSV ----------------------------------------------

	$( document ).on( 'click', '#mbs-export-csv-btn', function( e ) {
		e.preventDefault();

		const $btn         = $( this );
		const $anchor      = $( '.mbs-export-actions' );
		const msgId        = 'mbs-export-books-message';
		const nonce        = $btn.data( 'nonce' );
		const originalText = $btn.text();

		if ( ! nonce ) {
			mbsExportMsg( $anchor, msgId, __( 'Missing security token. Please refresh the page.', 'my-book-showroom' ), 'error' );
			return;
		}

		setExportBtnState( $btn, originalText, true );
		mbsExportMsg( $anchor, msgId, '', '' ); // clear previous message

		$.post( MBS_Settings.ajaxUrl, {
			action: 'mbs_export_csv',
			nonce:  nonce
		}, function( response ) {
			if ( typeof response === 'string' && response.trim().length > 0 && response.includes( ',' ) ) {
				const blob = new Blob( [ response ], { type: 'text/csv;charset=utf-8;' } );
				triggerBlobDownload( blob, 'mbs-books-' + new Date().toISOString().slice( 0, 10 ) + '.csv' );
				mbsExportMsg( $anchor, msgId, __( 'CSV exported successfully \u2014 your download will begin shortly.', 'my-book-showroom' ), 'success' );
			} else if ( response.success ) {
				if ( response.data && response.data.download_url ) {
					const link = document.createElement( 'a' );
					link.href     = response.data.download_url;
					link.download = response.data.filename || 'mbs-books-export.csv';
					document.body.appendChild( link );
					link.click();
					document.body.removeChild( link );
				}
				mbsExportMsg( $anchor, msgId, __( 'CSV exported successfully \u2014 your download will begin shortly.', 'my-book-showroom' ), 'success' );
			} else {
				mbsExportMsg( $anchor, msgId, sprintf( __( 'Export failed: %s', 'my-book-showroom' ), response.message || response.data || __( 'Unknown error', 'my-book-showroom' ) ), 'error' );
			}
		} ).fail( function() {
			mbsExportMsg( $anchor, msgId, __( 'Export request failed. Please try again.', 'my-book-showroom' ), 'error' );
		} ).always( function() {
			setExportBtnState( $btn, originalText, false );
		} );
	} );

	// -- Export All Books as XLSX ---------------------------------------------
	//
	// Uses XMLHttpRequest with responseType = 'blob' so binary OOXML data is
	// not corrupted by jQuery's string coercion. The PHP handler streams the
	// XLSX file directly with Content-Type: application/vnd...spreadsheetml.
	// On any error (PRO gate, permissions, server error) the server sends a
	// JSON error payload -- we read that Blob as text and parse it to surface
	// a readable message.

	$( document ).on( 'click', '#mbs-export-xlsx-btn', function( e ) {
		e.preventDefault();

		const $btn         = $( this );
		const $anchor      = $( '.mbs-export-actions' );
		const msgId        = 'mbs-export-books-message';
		const nonce        = $btn.data( 'nonce' );
		const originalText = $btn.text();

		if ( ! nonce ) {
			mbsExportMsg( $anchor, msgId, __( 'Missing security token. Please refresh the page.', 'my-book-showroom' ), 'error' );
			return;
		}

		setExportBtnState( $btn, originalText, true );
		mbsExportMsg( $anchor, msgId, '', '' ); // clear previous message

		const xhr = new XMLHttpRequest();
		xhr.open( 'POST', MBS_Settings.ajaxUrl, true );
		xhr.responseType = 'blob';
		xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );

		xhr.onload = function() {
			const contentType = xhr.getResponseHeader( 'Content-Type' ) || '';

			if ( xhr.status === 200 && contentType.indexOf( 'spreadsheetml' ) !== -1 ) {
				// Success -- download the binary blob.
				triggerBlobDownload( xhr.response, 'mbs-books-' + new Date().toISOString().slice( 0, 10 ) + '.xlsx' );
				mbsExportMsg( $anchor, msgId, __( 'XLSX exported successfully \u2014 your download will begin shortly.', 'my-book-showroom' ), 'success' );
				setExportBtnState( $btn, originalText, false );
			} else {
				// Error response -- read the Blob as text, try to parse JSON.
				const reader = new FileReader();
				reader.onload = function() {
					let message = __( 'Export failed. Please check your license and try again.', 'my-book-showroom' );
					try {
						const json = JSON.parse( reader.result );
						if ( json && json.data && json.data.message ) {
							message = sprintf( __( 'Export failed: %s', 'my-book-showroom' ), json.data.message );
						} else if ( json && json.message ) {
							message = sprintf( __( 'Export failed: %s', 'my-book-showroom' ), json.message );
						}
					} catch ( parseErr ) {
						// Not JSON -- keep the default message.
					}
					mbsExportMsg( $anchor, msgId, message, 'error' );
					setExportBtnState( $btn, originalText, false );
				};
				reader.readAsText( xhr.response );
			}
		};

		xhr.onerror = function() {
			mbsExportMsg( $anchor, msgId, __( 'Export request failed. Please try again.', 'my-book-showroom' ), 'error' );
			setExportBtnState( $btn, originalText, false );
		};

		xhr.send( 'action=mbs_export_xlsx&nonce=' + encodeURIComponent( nonce ) );
	} );

	// -- Export Settings as JSON ----------------------------------------------

	$( document ).on( 'click', '#mbs-export-settings-btn', function( e ) {
		e.preventDefault();

		const $btn         = $( this );
		const $anchor      = $btn.parent();
		const msgId        = 'mbs-export-settings-message';
		const nonce        = $btn.data( 'nonce' );
		const originalText = $btn.text();

		if ( ! nonce ) {
			mbsExportMsg( $anchor, msgId, __( 'Missing security token. Please refresh the page.', 'my-book-showroom' ), 'error' );
			return;
		}

		setExportBtnState( $btn, originalText, true );
		mbsExportMsg( $anchor, msgId, '', '' ); // clear previous message

		$.post( MBS_Settings.ajaxUrl, {
			action: 'mbs_export_settings',
			nonce:  nonce
		}, function( response ) {
			let settingsData = response;
			if ( response.success && response.data ) {
				settingsData = response.data;
			}

			if ( settingsData && typeof settingsData === 'object' && Object.keys( settingsData ).length > 0 ) {
				const jsonString = JSON.stringify( settingsData, null, 2 );
				const blob = new Blob( [ jsonString ], { type: 'application/json;charset=utf-8;' } );
				triggerBlobDownload( blob, 'mbs-settings-export-' + new Date().toISOString().slice( 0, 10 ) + '.json' );
				mbsExportMsg( $anchor, msgId, __( 'Settings exported successfully \u2014 your download will begin shortly.', 'my-book-showroom' ), 'success' );
			} else if ( response.success ) {
				if ( response.data && response.data.download_url ) {
					const link = document.createElement( 'a' );
					link.href     = response.data.download_url;
					link.download = response.data.filename || 'mbs-settings-export.json';
					document.body.appendChild( link );
					link.click();
					document.body.removeChild( link );
				}
				mbsExportMsg( $anchor, msgId, __( 'Settings exported successfully \u2014 your download will begin shortly.', 'my-book-showroom' ), 'success' );
			} else {
				mbsExportMsg( $anchor, msgId, sprintf( __( 'Settings export failed: %s', 'my-book-showroom' ), response.message || response.data || __( 'Unknown error', 'my-book-showroom' ) ), 'error' );
			}
		} ).fail( function() {
			mbsExportMsg( $anchor, msgId, __( 'Settings export request failed. Please try again.', 'my-book-showroom' ), 'error' );
		} ).always( function() {
			setExportBtnState( $btn, originalText, false );
		} );
	} );

	// -- Export Catalog + Covers as ZIP -------------------------------------
	//
	// Uses XMLHttpRequest with responseType = 'blob' so the binary ZIP data
	// is not corrupted by jQuery string coercion. On any error (PRO gate,
	// permissions, server error) the server sends a JSON error payload --
	// we read that Blob as text and parse it to surface a readable message.

	$( document ).on( 'click', '#mbs-export-covers-zip-btn', function( e ) {
		e.preventDefault();

		const $btn         = $( this );
		const $anchor      = $( '#mbs-export-zip-actions' );
		const msgId        = 'mbs-export-zip-message';
		const nonce        = $btn.data( 'nonce' );
		const originalText = $btn.text();

		if ( ! nonce ) {
			mbsExportMsg( $anchor, msgId, __( 'Missing security token. Please refresh the page.', 'my-book-showroom' ), 'error' );
			return;
		}

		setExportBtnState( $btn, originalText, true );
		mbsExportMsg( $anchor, msgId, '', '' ); // clear previous message

		const xhr = new XMLHttpRequest();
		xhr.open( 'POST', MBS_Settings.ajaxUrl, true );
		xhr.responseType = 'blob';
		xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );

		xhr.onload = function() {
			const contentType = xhr.getResponseHeader( 'Content-Type' ) || '';

			if ( xhr.status === 200 && contentType.indexOf( 'application/zip' ) !== -1 ) {
				// Success -- download the binary blob.
				triggerBlobDownload( xhr.response, 'mbs-catalog-covers-' + new Date().toISOString().slice( 0, 10 ) + '.zip' );
				mbsExportMsg( $anchor, msgId, __( 'ZIP exported successfully — your download will begin shortly.', 'my-book-showroom' ), 'success' );
				setExportBtnState( $btn, originalText, false );
			} else {
				// Error response -- read the Blob as text, try to parse JSON.
				const reader = new FileReader();
				reader.onload = function() {
					let message = __( 'Export failed. Please check your license and try again.', 'my-book-showroom' );
					try {
						const json = JSON.parse( reader.result );
						if ( json && json.data && json.data.message ) {
							message = sprintf( __( 'Export failed: %s', 'my-book-showroom' ), json.data.message );
						} else if ( json && json.message ) {
							message = sprintf( __( 'Export failed: %s', 'my-book-showroom' ), json.message );
						}
					} catch ( parseErr ) {
						// Not JSON -- keep the default message.
					}
					mbsExportMsg( $anchor, msgId, message, 'error' );
					setExportBtnState( $btn, originalText, false );
				};
				reader.readAsText( xhr.response );
			}
		};

		xhr.onerror = function() {
			mbsExportMsg( $anchor, msgId, __( 'Export request failed. Please try again.', 'my-book-showroom' ), 'error' );
			setExportBtnState( $btn, originalText, false );
		};

		xhr.send( 'action=mbs_export_covers_zip&nonce=' + encodeURIComponent( nonce ) );
	} );

} )( jQuery );
