/**
 * SiteOrigin RSM Features — JSON import/export via admin AJAX.
 */
( function ( $ ) {
	'use strict';

	var data = window.rsmsparkCwFeaturesAdmin || {};
	var i18n = data.i18n || {};
	var exportButtonSelector = '.rsmspark-cw-features-export-json';

	function t( key, fallback ) {
		return i18n[ key ] || fallback;
	}

	function widgetForm( $trigger ) {
		var $form = $trigger.closest( '.siteorigin-widget-form' );
		if ( $form.length ) {
			return $form;
		}
		return $trigger
			.closest( '.so-content-tabs, .so-panels-dialog' )
			.find( '.siteorigin-widget-form' )
			.first();
	}

	function findFieldByPath( $form, path ) {
		var pattern = path
			.map( function ( part ) {
				return '[' + part + ']';
			} )
			.join( '' );
		var $fields = $form.find( "[name*='" + pattern + "']" );
		if ( $fields.length ) {
			return $fields.first();
		}
		return $();
	}

	function readFieldValue( $field ) {
		if ( ! $field.length ) {
			return '';
		}

		var type = ( $field.attr( 'type' ) || '' ).toLowerCase();

		if ( type === 'checkbox' ) {
			return $field.is( ':checked' );
		}

		if ( $field.is( 'select[multiple]' ) ) {
			return $field.val() || [];
		}

		return $field.val();
	}

	function setFieldValue( $field, value ) {
		if ( ! $field.length ) {
			return;
		}

		var type = ( $field.attr( 'type' ) || '' ).toLowerCase();

		if ( type === 'checkbox' ) {
			$field.prop( 'checked', !! value ).trigger( 'change' );
			return;
		}

		if ( $field.is( 'select[multiple]' ) ) {
			$field.val( Array.isArray( value ) ? value : [] ).trigger( 'change' );
			return;
		}

		$field.val( value == null ? '' : value ).trigger( 'change' );
	}

	function parseBracketPath( name ) {
		var parts = [];
		var re = /\[([^\]]*)\]/g;
		var match;

		while ( ( match = re.exec( name ) ) ) {
			parts.push( match[ 1 ] );
		}

		if ( parts.length <= 1 ) {
			return null;
		}

		return parts.slice( 1 );
	}

	function setByPath( target, path, value ) {
		var cursor = target;
		var i;

		for ( i = 0; i < path.length - 1; i++ ) {
			var key = path[ i ];
			if ( cursor[ key ] == null || typeof cursor[ key ] !== 'object' ) {
				cursor[ key ] = /^[0-9]+$/.test( String( path[ i + 1 ] ) )
					? []
					: {};
			}
			cursor = cursor[ key ];
		}

		cursor[ path[ path.length - 1 ] ] = value;
	}

	function parseFormToInstance( $form ) {
		var instance = {};

		$form.find( 'input, select, textarea' ).each( function () {
			var name = this.name || '';
			var path = parseBracketPath( name );

			if ( ! path || ! path.length ) {
				return;
			}

			var value = readFieldValue( $( this ) );
			var last = path[ path.length - 1 ];

			if ( last === 'export_json' || last === 'import_json' ) {
				return;
			}

			setByPath( instance, path, value );
		} );

		return instance;
	}

	function applyPathToForm( $form, path, value ) {
		if ( path.length === 0 ) {
			return;
		}

		var $field = findFieldByPath( $form, path );
		if ( ! $field.length ) {
			return;
		}

		setFieldValue( $field, value );
	}

	function walkInstance( $form, value, path ) {
		var key;

		if ( Array.isArray( value ) ) {
			value.forEach( function ( item, index ) {
				walkInstance( $form, item, path.concat( [ String( index ) ] ) );
			} );
			return;
		}

		if ( value && typeof value === 'object' ) {
			for ( key in value ) {
				if ( Object.prototype.hasOwnProperty.call( value, key ) ) {
					walkInstance( $form, value[ key ], path.concat( [ key ] ) );
				}
			}
			return;
		}

		applyPathToForm( $form, path, value );
	}

	function applyInstanceToForm( $form, instance ) {
		var key;

		for ( key in instance ) {
			if ( ! Object.prototype.hasOwnProperty.call( instance, key ) ) {
				continue;
			}
			if ( key === 'import_export' ) {
				continue;
			}
			walkInstance( $form, instance[ key ], [ key ] );
		}
	}

	function findField( $form, section, key ) {
		var $fields = $form.find( fieldSelector( section, key ) );
		if ( $fields.length ) {
			return $fields.first();
		}
		return $form.find( '[name*="' + section + '"][name*="' + key + '"]' ).first();
	}

	function readFieldInSection( $form, section, key ) {
		return readFieldValue( findField( $form, section, key ) );
	}

	function setExportFieldInSection( $form, section, key, value ) {
		var text = value == null ? '' : String( value );
		var $field = findField( $form, section, key );

		if ( $field.length ) {
			$field.val( text );
		}

		showSoExportJsonPreview( $form, text );
	}

	function showSoExportJsonPreview( $form, text ) {
		var $button = $form.find( exportButtonSelector ).first();
		if ( ! $button.length ) {
			return;
		}

		var exportText = String( text || '' );
		$form.data( 'rsmCwLastExportJson', exportText );

		var $fieldWrap = $button.closest(
			'.siteorigin-widget-field, .so-field-wrapper, .so-field-textarea, .so-field'
		);

		if ( ! $fieldWrap.length ) {
			$fieldWrap = $button.parent();
		}

		var $mount = $fieldWrap.children( '.rsmspark-cw-so-export-json-mount' ).first();

		if ( ! $mount.length ) {
			$mount = $( '<div class="rsmspark-cw-so-export-json-mount"></div>' );
			$button.closest( 'p' ).after( $mount );
		}

		$mount.empty();

		if ( ! exportText.trim() ) {
			return;
		}

		$mount.append(
			$( '<p class="description rsmspark-cw-so-export-json-label">' ).text(
				t(
					'exportLabel',
					'Generated export (also copied to your clipboard):'
				)
			),
			$(
				'<pre class="rsmspark-cw-so-export-json-preview" tabindex="0" role="textbox" aria-readonly="true"></pre>'
			).text( exportText )
		);

		var pre = $mount.find( '.rsmspark-cw-so-export-json-preview' )[ 0 ];
		if ( pre && pre.scrollIntoView ) {
			pre.scrollIntoView( { block: 'nearest', behavior: 'smooth' } );
		}
	}

	function isAppearanceWidgetsScreen() {
		return ( window.location.pathname || '' ).indexOf( 'widgets.php' ) !== -1;
	}

	function showExportJsonPanel( text ) {
		if (
			window.RsmCwExportJsonUi &&
			typeof window.RsmCwExportJsonUi.show === 'function'
		) {
			window.RsmCwExportJsonUi.show( text, {
				title: t( 'exportPanelTitle', 'JSON export ready' ),
				widgetArea: isAppearanceWidgetsScreen(),
			} );
		}
	}

	function refreshSoExportDisplay( $form, section, key, text ) {
		setExportFieldInSection( $form, section, key, text );
		showExportJsonPanel( text );

		if ( isAppearanceWidgetsScreen() ) {
			return;
		}

		[ 0, 50, 250 ].forEach( function ( delay ) {
			window.setTimeout( function () {
				showSoExportJsonPreview( $form, text );
				var $field = findField( $form, section, key );
				if ( $field.length ) {
					$field.val( String( text || '' ) );
				}
			}, delay );
		} );
	}

	function fieldSelector( section, key ) {
		return (
			"[name*='[" +
			section +
			"][" +
			key +
			"]'], [name*='-" +
			section +
			"-" +
			key +
			"'], [name*='_" +
			section +
			"_" +
			key +
			"']"
		);
	}

	function isFeaturesForm( $form ) {
		return $form.length && $form.find( exportButtonSelector ).length;
	}

	function postFeaturesJson( payload ) {
		return $.post( data.ajaxUrl || '', payload );
	}

	$( document ).on( 'click', exportButtonSelector, function ( event ) {
		event.preventDefault();
		event.stopPropagation();
		var $form = widgetForm( $( this ) );
		if ( ! isFeaturesForm( $form ) ) {
			return;
		}

		var instance = parseFormToInstance( $form );
		var label = String(
			instance.general && instance.general.title ? instance.general.title : ''
		);

		postFeaturesJson( {
			action: 'rsmspark_cw_features_widget_json',
			nonce: data.nonce || '',
			mode: 'export',
			label: label,
			instance: JSON.stringify( instance ),
		} )
			.done( function ( response ) {
				if ( ! response || ! response.success || ! response.data ) {
					window.alert(
						t(
							'requestError',
							'Could not process features JSON. Try again.'
						)
					);
					return;
				}

				var text = JSON.stringify( response.data, null, 2 );
				refreshSoExportDisplay( $form, 'import_export', 'export_json', text );

				if ( navigator.clipboard && navigator.clipboard.writeText ) {
					navigator.clipboard.writeText( text ).catch( function () {} );
				}
			} )
			.fail( function () {
				window.alert(
					t(
						'requestError',
						'Could not process features JSON. Try again.'
					)
				);
			} );
	} );

	$( document ).on( 'click', '.rsmspark-cw-features-import-json', function ( event ) {
		event.preventDefault();
		var $form = widgetForm( $( this ) );
		if ( ! isFeaturesForm( $form ) ) {
			return;
		}

		var raw = String(
			readFieldInSection( $form, 'import_export', 'import_json' ) || ''
		);

		if ( ! raw.trim() ) {
			window.alert(
				t(
					'importError',
					'Paste valid RSM Features JSON export data (widget or block export).'
				)
			);
			return;
		}

		if (
			! window.confirm(
				t(
					'confirm',
					'Apply this features import? Current settings will be overwritten.'
				)
			)
		) {
			return;
		}

		var instance = parseFormToInstance( $form );

		postFeaturesJson( {
			action: 'rsmspark_cw_features_widget_json',
			nonce: data.nonce || '',
			mode: 'import',
			payload: raw,
			instance: JSON.stringify( instance ),
		} )
			.done( function ( response ) {
				if ( ! response || ! response.success || ! response.data ) {
					window.alert(
						t(
							'importError',
							'Paste valid RSM Features JSON export data (widget or block export).'
						)
					);
					return;
				}

				applyInstanceToForm( $form, response.data.instance || {} );

				window.alert(
					t(
						'importApplied',
						'Features import applied. Review Feature chips and Popout rows if counts changed.'
					)
				);
			} )
			.fail( function () {
				window.alert(
					t(
						'requestError',
						'Could not process features JSON. Try again.'
					)
				);
			} );
	} );
}( jQuery ) );
