/**
 * Surfaces Newsroom OS tag-guard errors in the Gutenberg block editor and
 * offers two recovery actions: replace with the suggested existing tag,
 * or force-create the new tag anyway via X-Newsai-Tag-Force.
 */
( function () {
	if ( typeof wp === 'undefined' || ! wp.apiFetch || ! wp.data ) {
		return;
	}

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

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

	function getPostTags() {
		try {
			var current = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'tags' );
			return Array.isArray( current ) ? current.slice() : [];
		} catch ( e ) {
			return [];
		}
	}

	function setPostTags( ids ) {
		try {
			wp.data.dispatch( 'core/editor' ).editPost( { tags: ids } );
		} catch ( e ) {
			/* no-op */
		}
	}

	function appendTagId( id ) {
		if ( ! id ) {
			return;
		}
		var ids = getPostTags();
		if ( ids.indexOf( id ) === -1 ) {
			ids.push( id );
			setPostTags( ids );
		}
	}

	function notify( status, message, options ) {
		try {
			var dispatchNotices = wp.data.dispatch( 'core/notices' );
			if ( dispatchNotices && typeof dispatchNotices.createNotice === 'function' ) {
				dispatchNotices.createNotice( status, message, options || {} );
			}
		} catch ( e ) {
			/* no-op */
		}
	}

	function useSuggested( id, name ) {
		appendTagId( id );
		notify( 'success', t( 'Tag added: ', 'Προστέθηκε ετικέτα: ' ) + name, {
			type: 'snackbar',
			isDismissible: true,
		} );
	}

	function forceCreate( original ) {
		wp.apiFetch( {
			path: '/wp/v2/tags',
			method: 'POST',
			data: { name: original },
			headers: { 'X-Newsai-Tag-Force': '1' },
		} ).then( function ( term ) {
			if ( term && term.id ) {
				appendTagId( term.id );
				notify(
					'success',
					t( 'Tag created: ', 'Δημιουργήθηκε ετικέτα: ' ) + ( term.name || original ),
					{ type: 'snackbar', isDismissible: true }
				);
			}
		} ).catch( function ( err ) {
			notify(
				'error',
				t( 'Could not create tag: ', 'Αδύνατη η δημιουργία ετικέτας: ' ) +
					( err && err.message ? err.message : original ),
				{ type: 'snackbar', isDismissible: true }
			);
		} );
	}

	wp.apiFetch.use( function ( options, next ) {
		return next( options ).catch( function ( error ) {
			var msg = error && error.message;
			var code = error && error.code;
			if ( ! msg || typeof msg !== 'string' ) {
				return Promise.reject( error );
			}
			var isOurs =
				code === 'newsai_tag_duplicate_suspect' ||
				msg.indexOf( 'Possible duplicate tag' ) !== -1 ||
				msg.indexOf( 'Πιθανό διπλό Tag' ) !== -1;
			if ( ! isOurs ) {
				return Promise.reject( error );
			}

			var data = ( error && error.data ) || {};
			var suggestedId = parseInt( data.suggested_id, 10 ) || 0;
			var suggestedName = ( data.suggested_name || '' ) + '';
			var original = ( data.original || '' ) + '';

			var actions = [];
			if ( suggestedId && suggestedName ) {
				actions.push( {
					label: t( 'Use: ', 'Χρήση: ' ) + suggestedName,
					onClick: function () { useSuggested( suggestedId, suggestedName ); },
				} );
			}
			if ( original ) {
				actions.push( {
					label: t( 'Keep: ', 'Διατήρηση: ' ) + original,
					onClick: function () { forceCreate( original ); },
				} );
			}

			notify( 'warning', msg, {
				isDismissible: true,
				actions: actions,
			} );

			return Promise.reject( error );
		} );
	} );
} )();
