/**
 * File Path: assets/js/mbs-admin-taxonomy-author.js
 *
 * Edit Tag screen — Author taxonomy DOM reorder.
 *
 * WordPress always appends custom edit_form_fields after the Description row.
 * This script moves:
 *  1. The "View Author" button row  — immediately after the Slug row.
 *  2. The "Name structure" section  — immediately after the View Author row.
 *
 * Loaded only on edit-tags.php / term.php for the mbs_author taxonomy.
 * No jQuery dependency — pure vanilla JS.
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */
/* global document */
( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		var table = document.querySelector( '.form-table tbody' );
		if ( ! table ) {
			return;
		}

		// Find the Slug row — all re-insertions anchor from here.
		var slugInput = document.getElementById( 'slug' );
		if ( ! slugInput ) {
			return;
		}
		var slugRow = slugInput.closest( 'tr' );
		if ( ! slugRow || ! slugRow.parentNode ) {
			return;
		}

		var anchor = slugRow;

		// ── Step 1: Move "View Author" button row to immediately after Slug ──
		var viewRow = table.querySelector( 'tr.mbs-settings-view-row' );
		if ( viewRow ) {
			slugRow.parentNode.insertBefore( viewRow, slugRow.nextSibling );
			anchor = viewRow;
		}

		// ── Step 2: Move "Name structure" section after the View row ──
		var rows = Array.prototype.slice.call( table.querySelectorAll( 'tr' ) );
		var headingRow = null;

		for ( var i = 0; i < rows.length; i++ ) {
			var h3 = rows[ i ].querySelector( 'h3' );
			if ( h3 && h3.textContent.indexOf( 'Name structure' ) !== -1 ) {
				headingRow = rows[ i ];
				break;
			}
		}

		if ( ! headingRow ) {
			return; // Fields not present (add-new form has no pre-populated values).
		}

		// Collect: heading row + the 7 name-field rows.
		var nameKeys = [
			'mbs_name_titles_before',
			'mbs_name_before_key',
			'mbs_name_prefix_to_key',
			'mbs_name_key',
			'mbs_name_after_key',
			'mbs_name_letters',
			'mbs_name_inverted',
		];

		var rowsToMove = [ headingRow ];
		nameKeys.forEach( function ( id ) {
			var el = document.getElementById( id );
			if ( el ) {
				var row = el.closest( 'tr' );
				if ( row ) {
					rowsToMove.push( row );
				}
			}
		} );

		// Re-insert collected rows immediately after the anchor (View row or Slug row).
		rowsToMove.forEach( function ( row ) {
			if ( row && anchor.parentNode ) {
				anchor.parentNode.insertBefore( row, anchor.nextSibling );
				anchor = row;
			}
		} );
	} );
} )();
