/**
 * SiteOrigin RSM Hero — preset apply and JSON import/export.
 */
( function ( $ ) {
	'use strict';

	var data = window.rsmsparkCwHeroAdmin || {};
	var presets = Array.isArray( data.presets ) ? data.presets : [];
	var i18n = data.i18n || {};
	var exportPlugin = data.exportPlugin || 'rsmspark-content-widgets-hero';

	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 fieldSelector( section, key ) {
		return (
			"[name*='[" +
			section +
			"][" +
			key +
			"]'], [name*='-" +
			section +
			"-" +
			key +
			"'], [name*='_" +
			section +
			"_" +
			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 setFieldValue( $form, section, key, value ) {
		var $field = findField( $form, section, key );
		if ( ! $field.length ) {
			return;
		}

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

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

		if ( $field.is( 'select' ) ) {
			$field.val( String( value ) ).trigger( 'change' );
			return;
		}

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

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

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

		showSoExportJsonPreview( $form, '.rsmspark-cw-hero-export-json', text );
	}

	function showSoExportJsonPreview( $form, exportButtonSelector, 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, exportButtonSelector ) {
		setExportFieldValue( $form, section, key, text );
		showExportJsonPanel( text );

		if ( isAppearanceWidgetsScreen() ) {
			return;
		}

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

	function readFieldValue( $form, section, key ) {
		var $field = findField( $form, section, key );
		if ( ! $field.length ) {
			return '';
		}

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

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

		return $field.val();
	}

	function readMediaSrc( $form, section, key ) {
		var $field = findField( $form, section, key );
		if ( ! $field.length ) {
			return '';
		}

		var $wrap = $field.closest(
			'.siteorigin-widget-field-media, .so-field-media, .so-field-wrapper'
		);
		var src =
			$wrap.find( '.screenshot img, .thumbnail img, img' ).first().attr( 'src' ) ||
			'';

		return src;
	}

	function heroHasMediaValue( key, value ) {
		if ( key === 'background_image' ) {
			if ( typeof value === 'number' ) {
				return value > 0;
			}
			return String( value || '' ).trim() !== '' && String( value ) !== '0';
		}
		return String( value || '' ).trim() !== '';
	}

	function heroLayerHasImage( layer ) {
		if ( ! layer || typeof layer !== 'object' ) {
			return false;
		}
		if ( parseInt( layer.image, 10 ) > 0 ) {
			return true;
		}
		return String( layer.image_src || '' ).trim() !== '';
	}

	function readBackgroundLayers( $form ) {
		var layerMap = {};
		var layerFieldPattern = /background_layers[\[\]_-]+(\d+)[\[\]_-]+([a-z_]+)/i;

		$form.find( 'input, select, textarea' ).each( function () {
			var name = this.name || '';
			if ( name.indexOf( 'background_layers' ) === -1 ) {
				return;
			}

			var match = name.match( layerFieldPattern );
			if ( ! match ) {
				return;
			}

			var index = match[ 1 ];
			var key = match[ 2 ];
			var $el = $( this );
			var type = ( $el.attr( 'type' ) || '' ).toLowerCase();
			var value;

			if ( type === 'checkbox' ) {
				value = $el.is( ':checked' );
			} else {
				value = $el.val();
			}

			if ( ! layerMap[ index ] ) {
				layerMap[ index ] = {};
			}
			layerMap[ index ][ key ] = value;
		} );

		var indices = Object.keys( layerMap ).sort( function ( a, b ) {
			return parseInt( a, 10 ) - parseInt( b, 10 );
		} );

		return indices.map( function ( index ) {
			var layer = layerMap[ index ];
			if ( layer.image && ! layer.image_src ) {
				layer.image_src = readLayerMediaSrc( $form, index );
			}
			return layer;
		} );
	}

	function readLayerMediaSrc( $form, layerIndex ) {
		var pattern =
			'background_layers' +
			'[\\[\\]_-]+' +
			layerIndex +
			'[\\[\\]_-]+image';
		var src = '';
		var re = new RegExp( pattern, 'i' );

		$form.find( 'input, select, textarea' ).each( function () {
			var name = this.name || '';
			if ( ! re.test( name ) ) {
				return;
			}
			var $wrap = $( this ).closest(
				'.siteorigin-widget-field-media, .so-field-media, .so-field-wrapper'
			);
			src =
				$wrap.find( '.screenshot img, .thumbnail img, img' ).first().attr( 'src' ) ||
				'';
			return false;
		} );

		return src;
	}

	function flattenInstance( $form ) {
		var contentKeys = [
			'headline',
			'subheadline',
			'background_image',
			'cta_text',
			'cta_url',
			'layout',
			'split_ratio',
			'image_side',
			'vertical_align',
			'mobile_order',
			'focal_preset',
			'focal_x',
			'focal_y',
		];
		var appearanceKeys = [
			'overlay_opacity',
			'min_height',
			'background_video_url',
			'parallax',
		];
		var flat = {};
		var i;

		for ( i = 0; i < contentKeys.length; i++ ) {
			flat[ contentKeys[ i ] ] = readFieldValue(
				$form,
				'content',
				contentKeys[ i ]
			);
		}

		for ( i = 0; i < appearanceKeys.length; i++ ) {
			flat[ appearanceKeys[ i ] ] = readFieldValue(
				$form,
				'appearance',
				appearanceKeys[ i ]
			);
		}

		flat.background_image_src = readMediaSrc(
			$form,
			'content',
			'background_image'
		);

		var layers = readBackgroundLayers( $form );
		if ( layers.length ) {
			flat.background_layers = layers;
		}

		return flat;
	}

	function mergePresetConfig( config, current ) {
		var next = $.extend( {}, current, config || {} );
		var mediaKeys = [
			'background_image',
			'background_image_src',
			'background_video_url',
		];
		var i;
		var key;

		for ( i = 0; i < mediaKeys.length; i++ ) {
			key = mediaKeys[ i ];
			if (
				! heroHasMediaValue( key, config ? config[ key ] : '' ) &&
				Object.prototype.hasOwnProperty.call( current, key )
			) {
				next[ key ] = current[ key ];
			}
		}

		if (
			( ! config ||
				! Array.isArray( config.background_layers ) ||
				! config.background_layers.length ) &&
			Array.isArray( current.background_layers ) &&
			current.background_layers.length
		) {
			next.background_layers = current.background_layers.slice();
		} else if (
			config &&
			Array.isArray( config.background_layers ) &&
			config.background_layers.length
		) {
			next.background_layers = config.background_layers.map(
				function ( layer, index ) {
					var merged = $.extend( {}, layer );
					var currentLayer =
						current.background_layers &&
						current.background_layers[ index ]
							? current.background_layers[ index ]
							: null;

					if (
						currentLayer &&
						! heroLayerHasImage( merged ) &&
						String( merged.video_url || '' ).trim() === '' &&
						heroLayerHasImage( currentLayer )
					) {
						merged.image = currentLayer.image || 0;
						merged.image_src = currentLayer.image_src || '';
					}
					return merged;
				}
			);
		}

		return next;
	}

	function applyFlatConfig( $form, config ) {
		var contentKeys = [
			'headline',
			'subheadline',
			'background_image',
			'cta_text',
			'cta_url',
			'layout',
			'split_ratio',
			'image_side',
			'vertical_align',
			'mobile_order',
			'focal_preset',
			'focal_x',
			'focal_y',
		];
		var appearanceKeys = [
			'overlay_opacity',
			'min_height',
			'background_video_url',
			'parallax',
		];
		var i;

		for ( i = 0; i < contentKeys.length; i++ ) {
			if (
				Object.prototype.hasOwnProperty.call( config, contentKeys[ i ] )
			) {
				setFieldValue(
					$form,
					'content',
					contentKeys[ i ],
					config[ contentKeys[ i ] ]
				);
			}
		}

		for ( i = 0; i < appearanceKeys.length; i++ ) {
			if (
				Object.prototype.hasOwnProperty.call(
					config,
					appearanceKeys[ i ]
				)
			) {
				setFieldValue(
					$form,
					'appearance',
					appearanceKeys[ i ],
					config[ appearanceKeys[ i ] ]
				);
			}
		}

		if (
			Array.isArray( config.background_layers ) &&
			config.background_layers.length
		) {
			window.alert(
				t(
					'layersManual',
					'This preset includes background layers. Configure them under Appearance → Background layers after applying.'
				)
			);
		}
	}

	function pickHeroExportConfig( config ) {
		var keys = [
			'headline',
			'subheadline',
			'background_image',
			'background_image_src',
			'background_video_url',
			'overlay_opacity',
			'min_height',
			'parallax',
			'cta_text',
			'cta_url',
			'layout',
			'split_ratio',
			'image_side',
			'vertical_align',
			'mobile_order',
			'focal_preset',
			'focal_x',
			'focal_y',
			'background_layers',
		];
		var picked = {};
		var i;

		for ( i = 0; i < keys.length; i++ ) {
			if (
				Object.prototype.hasOwnProperty.call( config, keys[ i ] )
			) {
				picked[ keys[ i ] ] = config[ keys[ i ] ];
			}
		}

		return picked;
	}

	function parseHeroImportPayload( raw ) {
		var payload = raw;

		if ( typeof raw === 'string' ) {
			try {
				payload = JSON.parse( raw );
			} catch ( error ) {
				return null;
			}
		}

		if ( ! payload || typeof payload !== 'object' ) {
			return null;
		}

		if (
			payload.plugin === exportPlugin &&
			payload.config &&
			typeof payload.config === 'object'
		) {
			return payload;
		}

		if (
			payload.plugin === 'rsmspark-content-widgets' &&
			payload.block === 'hero' &&
			payload.attributes &&
			typeof payload.attributes === 'object'
		) {
			return {
				plugin: exportPlugin,
				version: payload.version || '',
				exported_at: payload.exported_at || '',
				label: payload.label || '',
				config: pickHeroExportConfig( payload.attributes ),
			};
		}

		return null;
	}

	function findPreset( slug ) {
		return presets.find( function ( item ) {
			return item.slug === slug;
		} );
	}

	function isHeroForm( $form ) {
		return (
			$form.length &&
			( findField( $form, 'presets', 'style_preset' ).length ||
				$form.find( '.rsmspark-cw-hero-apply-preset' ).length )
		);
	}

	$( document ).on( 'click', '.rsmspark-cw-hero-apply-preset', function ( event ) {
		event.preventDefault();
		var $form = widgetForm( $( this ) );
		if ( ! isHeroForm( $form ) ) {
			return;
		}

		var slug = String(
			readFieldValue( $form, 'presets', 'style_preset' ) || ''
		);
		var preset = findPreset( slug );
		if ( ! preset ) {
			window.alert(
				t( 'selectPreset', 'Choose a layout preset first.' )
			);
			return;
		}
		if (
			! window.confirm(
				t(
					'confirm',
					'Apply this hero preset? Layout and appearance values will be overwritten.'
				)
			)
		) {
			return;
		}

		applyFlatConfig(
			$form,
			mergePresetConfig(
				preset.config || {},
				flattenInstance( $form )
			)
		);
	} );

	$( document ).on( 'click', '.rsmspark-cw-hero-export-json', function ( event ) {
		event.preventDefault();
		event.stopPropagation();
		var $form = widgetForm( $( this ) );
		if ( ! isHeroForm( $form ) ) {
			return;
		}

		var payload = {
			plugin: exportPlugin,
			version: data.version || '',
			exported_at: new Date().toISOString(),
			label: String(
				readFieldValue( $form, 'content', 'headline' ) || 'Hero'
			),
			config: flattenInstance( $form ),
		};
		var text = JSON.stringify( payload, null, 2 );

		refreshSoExportDisplay(
			$form,
			'presets',
			'export_json',
			text,
			'.rsmspark-cw-hero-export-json'
		);

		if ( navigator.clipboard && navigator.clipboard.writeText ) {
			navigator.clipboard.writeText( text ).catch( function () {} );
		}
	} );

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

		var raw = String(
			readFieldValue( $form, 'presets', 'import_json' ) || ''
		);
		var payload = parseHeroImportPayload( raw );

		if ( ! payload ) {
			window.alert(
				t(
					'importError',
					'Paste valid RSM Hero JSON export data (hero preset or block export).'
				)
			);
			return;
		}

		if (
			! window.confirm(
				t(
					'confirm',
					'Apply this hero preset? Layout and appearance values will be overwritten.'
				)
			)
		) {
			return;
		}

		applyFlatConfig(
			$form,
			mergePresetConfig( payload.config || {}, flattenInstance( $form ) )
		);
	} );
}( jQuery ) );
