/**
 * Classic editor tag-guard: intercept the Tags metabox "Add" before tag-box.js
 * pushes the chip into the hidden tax_input list. Surfaces a duplicate suggestion
 * with two actions: replace with existing tag, or keep the new one (force bypass
 * on post save via a hidden newsai_tag_force flag in the post form).
 */
( function ( $ ) {
	if ( ! $ || typeof window === 'undefined' ) {
		return;
	}

	var IS_EL =
		( window.newsaiTagGuard && window.newsaiTagGuard.lang &&
		  String( window.newsaiTagGuard.lang ).toLowerCase().indexOf( 'el' ) === 0 ) ||
		( document.documentElement && document.documentElement.lang &&
		  document.documentElement.lang.toLowerCase().indexOf( 'el' ) === 0 );

	function t( en, el ) {
		return IS_EL ? el : en;
	}

	function ensureForceField( $form ) {
		if ( ! $form || ! $form.length ) {
			return;
		}
		if ( ! $form.find( 'input[name="newsai_tag_force"]' ).length ) {
			$form.append( '<input type="hidden" name="newsai_tag_force" value="1" />' );
		}
	}

	function getOrCreateNoticeArea( $tagsdiv ) {
		var $area = $tagsdiv.find( '.newsai-tag-guard-notice' );
		if ( ! $area.length ) {
			$area = $(
				'<div class="newsai-tag-guard-notice" style="margin:8px 0;padding:10px 12px;border-left:4px solid #d63638;background:#fcf0f1;color:#5b1d20;border-radius:2px;"></div>'
			);
			var $jax = $tagsdiv.find( '.jaxtag' );
			if ( $jax.length ) {
				$jax.before( $area );
			} else {
				$tagsdiv.prepend( $area );
			}
		}
		return $area;
	}

	function clearNotice( $tagsdiv ) {
		$tagsdiv.find( '.newsai-tag-guard-notice' ).remove();
	}

	function showSuggestion( $tagsdiv, data, onResolve ) {
		var $area = getOrCreateNoticeArea( $tagsdiv );
		$area.empty();

		$area.append(
			$( '<p style="margin:0 0 8px 0;font-weight:600;"></p>' ).text(
				'Newsroom OS: ' + data.message
			)
		);

		var $btns = $( '<p style="margin:0;display:flex;gap:6px;flex-wrap:wrap;"></p>' );

		if ( data.suggested_id && data.suggested_name ) {
			$( '<button type="button" class="button button-primary"></button>' )
				.text( t( 'Use: ', 'Χρήση: ' ) + data.suggested_name )
				.on( 'click', function () {
					clearNotice( $tagsdiv );
					onResolve( 'use', data );
				} )
				.appendTo( $btns );
		}

		if ( data.original ) {
			$( '<button type="button" class="button"></button>' )
				.text( t( 'Keep: ', 'Διατήρηση: ' ) + data.original )
				.on( 'click', function () {
					clearNotice( $tagsdiv );
					onResolve( 'keep', data );
				} )
				.appendTo( $btns );
		}

		$( '<button type="button" class="button-link" style="margin-left:auto;color:#646970;"></button>' )
			.text( t( 'Cancel', 'Άκυρο' ) )
			.on( 'click', function () {
				clearNotice( $tagsdiv );
				onResolve( 'cancel', data );
			} )
			.appendTo( $btns );

		$area.append( $btns );
	}

	function checkTermAsync( name, taxonomy ) {
		var cfg = window.newsaiTagGuard || {};
		return $.ajax( {
			url: cfg.ajaxurl || window.ajaxurl,
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'newsai_tag_guard_check',
				nonce: cfg.nonce || '',
				term: name,
				taxonomy: taxonomy || 'post_tag',
			},
		} );
	}

	function performAddOnce( $tagsdiv, taxonomy ) {
		var tb = window.tagBox;
		if ( tb && typeof tb.flushTags === 'function' ) {
			tb._newsaiBypass = true;
			try {
				tb.flushTags( $tagsdiv );
			} finally {
				tb._newsaiBypass = false;
			}
		}
	}

	function patchTagBox() {
		var tb = window.tagBox;
		if ( ! tb || typeof tb.flushTags !== 'function' || tb._newsaiPatched ) {
			return;
		}
		var origFlush = tb.flushTags;
		tb._newsaiPatched = true;

		tb.flushTags = function ( el, a, f ) {
			if ( tb._newsaiBypass ) {
				return origFlush.call( tb, el, a, f );
			}

			var $tagsdiv = $( el );
			var taxonomy = $tagsdiv.find( '.the-tags' ).attr( 'name' ) || '';
			taxonomy = taxonomy.replace( /^tax_input\[/, '' ).replace( /\]$/, '' );
			if ( taxonomy !== 'post_tag' ) {
				return origFlush.call( tb, el, a, f );
			}

			var $newTagInput = $tagsdiv.find( 'input.newtag' );
			var raw = ( $newTagInput.val() || '' ).trim();
			if ( ! raw ) {
				return origFlush.call( tb, el, a, f );
			}
			if ( raw.indexOf( ',' ) !== -1 ) {
				return origFlush.call( tb, el, a, f );
			}

			checkTermAsync( raw, taxonomy )
				.done( function ( resp ) {
					if ( ! resp || ! resp.success || ! resp.data || ! resp.data.block ) {
						performAddOnce( $tagsdiv, taxonomy );
						return;
					}
					showSuggestion( $tagsdiv, resp.data, function ( action ) {
						if ( action === 'use' && resp.data.suggested_name ) {
							$newTagInput.val( resp.data.suggested_name );
							performAddOnce( $tagsdiv, taxonomy );
							return;
						}
						if ( action === 'keep' ) {
							ensureForceField( $tagsdiv.closest( 'form' ) );
							performAddOnce( $tagsdiv, taxonomy );
							return;
						}
						$newTagInput.focus();
					} );
				} )
				.fail( function ( xhr ) {
					if ( xhr && ( xhr.status === 403 || xhr.status === 401 ) ) {
						var $area = getOrCreateNoticeArea( $tagsdiv );
						$area.empty().append(
							$( '<p style="margin:0;font-weight:600;"></p>' ).text(
								'Newsroom OS: ' +
									t(
										'Could not verify this tag (permission denied).',
										'Δεν ήταν δυνατός ο έλεγχος της ετικέτας (άρνηση δικαιώματος).'
									)
							)
						);
						return;
					}
					performAddOnce( $tagsdiv, taxonomy );
				} );
		};
	}

	$( function () {
		patchTagBox();
		var tries = 0;
		var iv = setInterval( function () {
			tries++;
			if ( window.tagBox && typeof window.tagBox.flushTags === 'function' ) {
				patchTagBox();
				clearInterval( iv );
			} else if ( tries > 50 ) {
				clearInterval( iv );
			}
		}, 100 );
	} );
} )( window.jQuery );
