/**
 * ThemeREX Auto Dealer - Admin JavaScript
 *
 * Handles conditional field visibility, validation, and auto-title
 * generation on the vehicle edit screen.
 *
 * @package ThemeREX\AutoDealer
 */

( function () {
	'use strict';

	/**
	 * The localized data object from wp_localize_script.
	 *
	 * @type {Object}
	 */
	var trxAdAdmin = window.trxAdAdmin || {};

	/**
	 * Tracks the last auto-generated title so we know whether the user
	 * has manually edited it.
	 *
	 * @type {string}
	 */
	var lastAutoTitle = '';

	/* ======================================================================
	   Utility helpers
	   ====================================================================== */

	/**
	 * Shortcut for querySelector.
	 *
	 * @param {string}      selector CSS selector.
	 * @param {Element=}    root     Context element (default: document).
	 * @return {Element|null}
	 */
	function qs( selector, root ) {
		return ( root || document ).querySelector( selector );
	}

	/**
	 * Shortcut for querySelectorAll as an array.
	 *
	 * @param {string}   selector CSS selector.
	 * @param {Element=} root     Context element (default: document).
	 * @return {Element[]}
	 */
	function qsa( selector, root ) {
		return Array.prototype.slice.call(
			( root || document ).querySelectorAll( selector )
		);
	}

	/**
	 * Show an element by adding .is-visible.
	 *
	 * @param {Element|null} el
	 */
	function show( el ) {
		if ( el ) {
			el.classList.add( 'is-visible' );
		}
	}

	/**
	 * Hide an element by removing .is-visible.
	 *
	 * @param {Element|null} el
	 */
	function hide( el ) {
		if ( el ) {
			el.classList.remove( 'is-visible' );
		}
	}

	/* ======================================================================
	   Vehicle Type Toggle
	   ====================================================================== */

	/**
	 * Show / hide type-specific field groups based on the selected
	 * vehicle type.
	 */
	function handleVehicleTypeChange() {
		var select = qs( '#trx_ad_vehicle_type, [name="trx_ad_vehicle_type"]' );

		if ( ! select ) {
			return;
		}

		var boatFields  = qs( '.trx-ad-boat-fields' );
		var truckFields = qs( '.trx-ad-truck-fields' );

		function update() {
			var value = select.value.toLowerCase();

			// Hide all type-specific groups first.
			hide( boatFields );
			hide( truckFields );

			if ( value === 'boat' ) {
				show( boatFields );
			} else if ( value === 'truck' || value === 'commercial' ) {
				show( truckFields );
			}
		}

		select.addEventListener( 'change', update );

		// Run on load to set initial state.
		update();
	}

	/* ======================================================================
	   Fuel Type Toggle (EV Fields)
	   ====================================================================== */

	/**
	 * Show / hide EV-specific fields based on the selected fuel type.
	 */
	function handleFuelTypeChange() {
		var select = qs( '#trx_ad_fuel_type, [name="trx_ad_fuel_type"]' );

		if ( ! select ) {
			return;
		}

		var evFields = qs( '.trx-ad-ev-fields' );

		function update() {
			var value = select.value.toLowerCase();

			if ( value === 'electric' || value === 'phev' ) {
				show( evFields );
			} else {
				hide( evFields );
			}
		}

		select.addEventListener( 'change', update );

		// Run on load.
		update();
	}

	/* ======================================================================
	   VIN Validation
	   ====================================================================== */

	/**
	 * Validate VIN input on blur.
	 * A valid VIN is exactly 17 alphanumeric characters (letters + digits),
	 * excluding I, O, Q (per ISO 3779).
	 */
	function handleVinValidation() {
		var vinInput = qs( '#trx_ad_vin, [name="trx_ad_vin"]' );

		if ( ! vinInput ) {
			return;
		}

		// Create or find the error element.
		var errorEl = vinInput.parentNode.querySelector( '.trx-ad-field-error' );

		if ( ! errorEl ) {
			errorEl = document.createElement( 'p' );
			errorEl.className = 'trx-ad-field-error';
			errorEl.textContent = trxAdAdmin.i18n
				? trxAdAdmin.i18n.vinError || 'VIN must be exactly 17 alphanumeric characters (no I, O, or Q).'
				: 'VIN must be exactly 17 alphanumeric characters (no I, O, or Q).';
			vinInput.parentNode.appendChild( errorEl );
		}

		vinInput.addEventListener( 'blur', function () {
			var value = vinInput.value.trim();

			// Allow empty (field may be optional).
			if ( value === '' ) {
				vinInput.classList.remove( 'has-error' );
				hide( errorEl );
				return;
			}

			// VIN: 17 chars, A-H, J-N, P, R-Z, 0-9 (no I, O, Q).
			var vinPattern = /^[A-HJ-NPR-Z0-9]{17}$/i;

			if ( ! vinPattern.test( value ) ) {
				vinInput.classList.add( 'has-error' );
				show( errorEl );
			} else {
				vinInput.classList.remove( 'has-error' );
				hide( errorEl );
				// Normalize to uppercase.
				vinInput.value = value.toUpperCase();
			}
		} );
	}

	/* ======================================================================
	   Price Validation
	   ====================================================================== */

	/**
	 * Validate price input on blur. Warn if negative.
	 */
	function handlePriceValidation() {
		var priceInputs = qsa(
			'#trx_ad_price, [name="trx_ad_price"], #trx_ad_sale_price, [name="trx_ad_sale_price"]'
		);

		priceInputs.forEach( function ( input ) {
			var warningEl = input.parentNode.querySelector( '.trx-ad-field-warning' );

			if ( ! warningEl ) {
				warningEl = document.createElement( 'p' );
				warningEl.className = 'trx-ad-field-warning';
				warningEl.textContent = trxAdAdmin.i18n
					? trxAdAdmin.i18n.priceWarning || 'Price should not be negative.'
					: 'Price should not be negative.';
				input.parentNode.appendChild( warningEl );
			}

			var errorEl = input.parentNode.querySelector( '.trx-ad-field-error' );

			if ( ! errorEl ) {
				errorEl = document.createElement( 'p' );
				errorEl.className = 'trx-ad-field-error';
				errorEl.textContent = trxAdAdmin.i18n
					? trxAdAdmin.i18n.priceError || 'Price must be a valid number.'
					: 'Price must be a valid number.';
				input.parentNode.appendChild( errorEl );
			}

			input.addEventListener( 'blur', function () {
				var value = input.value.trim();

				// Reset states.
				input.classList.remove( 'has-error', 'has-warning' );
				hide( errorEl );
				hide( warningEl );

				if ( value === '' ) {
					return;
				}

				var num = parseFloat( value );

				if ( isNaN( num ) ) {
					input.classList.add( 'has-error' );
					show( errorEl );
				} else if ( num < 0 ) {
					input.classList.add( 'has-warning' );
					show( warningEl );
				}
			} );
		} );
	}

	/* ======================================================================
	   Auto-Generate Post Title
	   ====================================================================== */

	/**
	 * When year, make, or model change, auto-suggest a title if the user
	 * has not manually edited it.
	 */
	function handleAutoTitle() {
		var titleInput = qs( '#title, #post-title-0, [name="post_title"]' );

		if ( ! titleInput ) {
			return;
		}

		// On the list-table view (`edit.php`), column headings render as
		// `<th id="trx_ad_year">` etc — same selector matches but `<th>`
		// has no `.value`, which crashed `buildAutoTitle`. Only accept
		// elements that are an actual form field.
		var isFormField = function ( el ) {
			return el && /^(INPUT|SELECT|TEXTAREA)$/.test( el.tagName );
		};
		var pickField = function ( selector ) {
			var el = qs( selector );
			return isFormField( el ) ? el : null;
		};
		var yearInput  = pickField( '#trx_ad_year, [name="trx_ad_year"]' );
		var makeInput  = pickField( '#trx_ad_make, [name="trx_ad_make"]' );
		var modelInput = pickField( '#trx_ad_model, [name="trx_ad_model"]' );

		// Collect whichever fields exist.
		var fields = [ yearInput, makeInput, modelInput ].filter( Boolean );

		if ( fields.length === 0 ) {
			return;
		}

		// Store the initial auto title pattern if the title matches on load.
		lastAutoTitle = buildAutoTitle( yearInput, makeInput, modelInput );

		function buildAutoTitle( yearEl, makeEl, modelEl ) {
			var parts = [];
			if ( yearEl && yearEl.value.trim() ) {
				parts.push( yearEl.value.trim() );
			}
			if ( makeEl ) {
				// Could be a select (taxonomy dropdown) or text input.
				var makeVal = getFieldValue( makeEl );
				if ( makeVal ) {
					parts.push( makeVal );
				}
			}
			if ( modelEl ) {
				var modelVal = getFieldValue( modelEl );
				if ( modelVal ) {
					parts.push( modelVal );
				}
			}
			return parts.join( ' ' );
		}

		/**
		 * Get the display value from a field (handles selects with option text).
		 *
		 * @param {Element} el
		 * @return {string}
		 */
		function getFieldValue( el ) {
			if ( el.tagName === 'SELECT' && el.selectedIndex >= 0 ) {
				var option = el.options[ el.selectedIndex ];
				// Skip placeholder/empty options.
				if ( option.value === '' || option.value === '0' || option.value === '-1' ) {
					return '';
				}
				return option.textContent.trim();
			}
			return el.value.trim();
		}

		function onFieldChange() {
			var currentTitle = titleInput.value.trim();
			var newAutoTitle = buildAutoTitle( yearInput, makeInput, modelInput );

			// Only set title if:
			// 1. Title is empty, OR
			// 2. Title matches the last auto-generated pattern.
			if ( currentTitle === '' || currentTitle === lastAutoTitle ) {
				titleInput.value = newAutoTitle;
				lastAutoTitle = newAutoTitle;

				// Trigger input event so WP's slug generator picks it up.
				var event = new Event( 'input', { bubbles: true } );
				titleInput.dispatchEvent( event );
			}
		}

		fields.forEach( function ( field ) {
			field.addEventListener( 'change', onFieldChange );
			field.addEventListener( 'input', onFieldChange );
		} );
	}

	/* ======================================================================
	   Initialization
	   ====================================================================== */

	/**
	 * Initialize all admin behaviors when the DOM is ready.
	 */
	function init() {
		handleVehicleTypeChange();
		handleFuelTypeChange();
		handleVinValidation();
		handlePriceValidation();
		handleAutoTitle();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();

/* ==========================================================================
   Settings-tab + list-table modules (migrated out of PHP-composed inline
   scripts, wp.org 2026-07 review round 2). Each module guards on its own
   DOM marker so this single bundle is safe on every admin screen. Data
   crosses the PHP->JS boundary only via wp_localize_script objects.
   ========================================================================== */

( function () {
	'use strict';

	/* Escape a string for use inside HTML built via innerHTML. */
	function escHtml( value ) {
		return String( value )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' )
			.replace( /'/g, '&#039;' );
	}

	/* ------------------------------------------------------------------
	   Settings — Custom Taxonomies tab (data: trxAdTaxTab)
	   ------------------------------------------------------------------ */
	function initTaxonomiesTab() {
		var tbody = document.getElementById( 'trx-ad-tax-body' );
		var addBtn = document.getElementById( 'trx-ad-add-tax' );
		var data = window.trxAdTaxTab;
		if ( ! tbody || ! addBtn || ! data ) {
			return;
		}
		var idx = tbody.querySelectorAll( 'tr' ).length;
		var slugPrefix = String( data.slugPrefix || '' );
		var i18n = data.i18n || {};

		addBtn.addEventListener( 'click', function () {
			var tr = document.createElement( 'tr' );
			var id = 'ut_' + Date.now() + '_' + idx;
			tr.innerHTML = buildRow( idx, id );
			tbody.appendChild( tr );
			idx++;
		} );

		tbody.addEventListener( 'click', function ( e ) {
			if ( e.target.classList.contains( 'trx-ad-remove-tax' ) || e.target.closest( '.trx-ad-remove-tax' ) ) {
				e.target.closest( 'tr' ).remove();
			}
		} );

		/* Auto-generate slug from label */
		tbody.addEventListener( 'input', function ( e ) {
			if ( e.target.classList.contains( 'trx-ad-tax-label' ) ) {
				var row = e.target.closest( 'tr' );
				var slugInput = row.querySelector( '.trx-ad-tax-slug' );
				var rewriteInput = row.querySelector( '.trx-ad-tax-rewrite' );
				if ( slugInput && ! slugInput.dataset.manual ) {
					var base = e.target.value.toLowerCase().replace( /[^a-z0-9]+/g, '_' ).replace( /^_|_$/g, '' );
					slugInput.value = slugPrefix + base.substring( 0, 32 - slugPrefix.length );
				}
				if ( rewriteInput && ! rewriteInput.dataset.manual ) {
					rewriteInput.value = e.target.value.toLowerCase().replace( /[^a-z0-9]+/g, '-' ).replace( /^-|-$/g, '' );
				}
			}
		} );

		/* Mark slug as manually edited */
		tbody.addEventListener( 'input', function ( e ) {
			if ( e.target.classList.contains( 'trx-ad-tax-slug' ) ) {
				e.target.dataset.manual = '1';
			}
			if ( e.target.classList.contains( 'trx-ad-tax-rewrite' ) ) {
				e.target.dataset.manual = '1';
			}
		} );

		function buildRow( i, id ) {
			var pfx = 'trx_ad_tax[' + i + ']';
			return '<td><p class="description">' + escHtml( i18n.saveFirst || '' ) + '</p></td>'
				+ '<td><input type="hidden" name="' + pfx + '[id]" value="' + escHtml( id ) + '">'
				+ '<input type="text" name="' + pfx + '[label]" value="" class="regular-text trx-ad-tax-label" placeholder="' + escHtml( i18n.labelPh || '' ) + '" required></td>'
				+ '<td><input type="text" name="' + pfx + '[singular]" value="" class="regular-text" placeholder="' + escHtml( i18n.singularPh || '' ) + '"></td>'
				+ '<td><input type="text" name="' + pfx + '[slug]" value="" class="regular-text trx-ad-tax-slug" placeholder="' + escHtml( slugPrefix ) + '..." readonly></td>'
				+ '<td><input type="text" name="' + pfx + '[rewrite_slug]" value="" class="regular-text trx-ad-tax-rewrite" placeholder="' + escHtml( i18n.rewritePh || '' ) + '"></td>'
				+ '<td style="text-align:center;"><input type="checkbox" name="' + pfx + '[hierarchical]" value="1"></td>'
				+ '<td style="text-align:center;"><input type="checkbox" name="' + pfx + '[show_in_filters]" value="1" checked></td>'
				+ '<td style="text-align:center;"><input type="checkbox" name="' + pfx + '[show_in_specs]" value="1" checked></td>'
				+ '<td><button type="button" class="button-link trx-ad-remove-tax" style="color:#b32d2e;" title="' + escHtml( i18n.remove || '' ) + '">'
				+ '<span class="dashicons dashicons-trash"></span></button></td>';
		}
	}

	/* ------------------------------------------------------------------
	   Settings — Custom Fields tab (data: trxAdFieldsTab)
	   ------------------------------------------------------------------ */
	function initFieldsTab() {
		var tbody = document.getElementById( 'trx-ad-fields-body' );
		var addBtn = document.getElementById( 'trx-ad-add-field' );
		var data = window.trxAdFieldsTab;
		if ( ! tbody || ! addBtn || ! data ) {
			return;
		}
		var idx = tbody.querySelectorAll( 'tr' ).length;
		var i18n = data.i18n || {};
		var typeOptions = ( data.fieldTypes || [] ).map( function ( t ) {
			return '<option value="' + escHtml( t ) + '">' + escHtml( t.charAt( 0 ).toUpperCase() + t.slice( 1 ) ) + '</option>';
		} ).join( '' );

		addBtn.addEventListener( 'click', function () {
			var tr = document.createElement( 'tr' );
			var id = 'cf_' + Date.now() + '_' + idx;
			tr.innerHTML = buildRow( idx, id );
			tbody.appendChild( tr );
			idx++;
		} );

		tbody.addEventListener( 'click', function ( e ) {
			/* closest() so a click on the inner dashicon span still matches the button (UAT #21). */
			var btn = e.target.closest( '.trx-ad-remove-field' );
			if ( btn ) {
				e.preventDefault();
				var row = btn.closest( 'tr' );
				if ( row ) {
					row.remove();
				}
			}
		} );

		function buildRow( i, id ) {
			var pfx = 'trx_ad_cf[' + i + ']';
			return '<td class="trx-ad-col-sort"><span class="dashicons dashicons-menu" style="cursor:grab;color:#999;"></span></td>'
				+ '<td><input type="hidden" name="' + pfx + '[id]" value="' + escHtml( id ) + '">'
				+ '<input type="text" name="' + pfx + '[label]" value="" class="regular-text" placeholder="' + escHtml( i18n.labelPh || '' ) + '" required></td>'
				+ '<td><input type="text" name="' + pfx + '[key]" value="" class="regular-text" placeholder="' + escHtml( i18n.keyPh || '' ) + '"></td>'
				+ '<td><select name="' + pfx + '[type]">' + typeOptions + '</select></td>'
				+ '<td><input type="text" name="' + pfx + '[options]" value="" class="regular-text" placeholder="' + escHtml( i18n.optionsPh || '' ) + '"></td>'
				+ '<td><input type="text" name="' + pfx + '[description]" value="" class="regular-text" placeholder="' + escHtml( i18n.descPh || '' ) + '"></td>'
				+ '<td><input type="text" name="' + pfx + '[group]" value="" class="small-text" placeholder="' + escHtml( i18n.groupPh || '' ) + '"></td>'
				+ '<td><button type="button" class="button-link trx-ad-remove-field" style="color:#b32d2e;" title="' + escHtml( i18n.remove || '' ) + '">'
				+ '<span class="dashicons dashicons-trash"></span></button></td>';
		}

		/* Simple drag-to-reorder */
		var dragEl = null;
		tbody.addEventListener( 'dragstart', function ( e ) {
			dragEl = e.target.closest( 'tr' );
			if ( dragEl ) {
				e.dataTransfer.effectAllowed = 'move';
			}
		} );
		tbody.addEventListener( 'dragover', function ( e ) {
			e.preventDefault();
			var target = e.target.closest( 'tr' );
			if ( target && target !== dragEl ) {
				var rect = target.getBoundingClientRect();
				var next = ( e.clientY - rect.top ) > ( rect.height / 2 );
				tbody.insertBefore( dragEl, next ? target.nextSibling : target );
			}
		} );
		tbody.addEventListener( 'dragend', function () {
			/* Re-index field names */
			var rows = tbody.querySelectorAll( 'tr' );
			rows.forEach( function ( row, ri ) {
				row.querySelectorAll( 'input, select' ).forEach( function ( inp ) {
					inp.name = inp.name.replace( /trx_ad_cf\[\d+\]/, 'trx_ad_cf[' + ri + ']' );
				} );
			} );
			dragEl = null;
		} );

		/* Make rows draggable */
		tbody.querySelectorAll( 'tr' ).forEach( function ( r ) {
			r.draggable = true;
		} );
		new MutationObserver( function () {
			tbody.querySelectorAll( 'tr' ).forEach( function ( r ) {
				r.draggable = true;
			} );
		} ).observe( tbody, { childList: true } );
	}

	/* ------------------------------------------------------------------
	   Settings — Forms tab form-builder (data: trxAdFormsTab)
	   ------------------------------------------------------------------ */
	function initFormsTab() {
		var tables = document.querySelectorAll( '.trx-ad-form-fields-table' );
		var data = window.trxAdFormsTab;
		if ( ! tables.length || ! data ) {
			return;
		}
		var fieldTypes = data.fieldTypes || [];

		// Add field.
		document.querySelectorAll( '.trx-ad-add-field' ).forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				var formId = this.dataset.formId;
				var tbody = document.querySelector( '.trx-ad-form-fields-table[data-form-id="' + formId + '"] tbody' );
				var idx = tbody.querySelectorAll( 'tr' ).length;
				var pfx = 'trx_ad_form[' + formId + '][fields][' + idx + ']';
				var typeOpts = '';
				fieldTypes.forEach( function ( t ) {
					typeOpts += '<option value="' + escHtml( t ) + '">' + escHtml( t.charAt( 0 ).toUpperCase() + t.slice( 1 ) ) + '</option>';
				} );
				var tr = document.createElement( 'tr' );
				tr.innerHTML =
					'<td><span class="dashicons dashicons-move" style="cursor:grab;color:#999;"></span></td>'
					+ '<td><input type="text" name="' + pfx + '[label]" value="" class="regular-text" required></td>'
					+ '<td><input type="text" name="' + pfx + '[id]" value="" class="small-text" style="width:70px;"></td>'
					+ '<td><select name="' + pfx + '[type]">' + typeOpts + '</select></td>'
					+ '<td style="text-align:center;"><input type="checkbox" name="' + pfx + '[required]" value="1"></td>'
					+ '<td><input type="text" name="' + pfx + '[placeholder]" value="" class="regular-text"></td>'
					+ '<td><select name="' + pfx + '[width]"><option value="100">100%</option><option value="50">50%</option><option value="33">33%</option><option value="25">25%</option></select></td>'
					+ '<td><button type="button" class="button-link trx-ad-remove-field" style="color:#b32d2e;"><span class="dashicons dashicons-trash"></span></button></td>';
				tbody.appendChild( tr );
			} );
		} );

		// Remove field.
		document.addEventListener( 'click', function ( e ) {
			if ( e.target.closest( '.trx-ad-remove-field' ) ) {
				e.target.closest( 'tr' ).remove();
			}
		} );

		// Drag to reorder (simple sortable via drag events).
		document.querySelectorAll( '.trx-ad-form-fields-table tbody' ).forEach( function ( tbody ) {
			var dragRow = null;
			tbody.addEventListener( 'dragstart', function ( e ) {
				dragRow = e.target.closest( 'tr' );
				if ( dragRow ) {
					dragRow.style.opacity = '0.4';
				}
			} );
			tbody.addEventListener( 'dragover', function ( e ) {
				e.preventDefault();
				var target = e.target.closest( 'tr' );
				if ( target && target !== dragRow && target.parentNode === tbody ) {
					var rect = target.getBoundingClientRect();
					var after = e.clientY > rect.top + rect.height / 2;
					tbody.insertBefore( dragRow, after ? target.nextSibling : target );
				}
			} );
			tbody.addEventListener( 'dragend', function () {
				if ( dragRow ) {
					dragRow.style.opacity = '';
				}
				dragRow = null;
				reindex( tbody );
			} );

			// Make rows draggable.
			tbody.querySelectorAll( 'tr' ).forEach( function ( tr ) {
				tr.draggable = true;
			} );
			var observer = new MutationObserver( function () {
				tbody.querySelectorAll( 'tr' ).forEach( function ( tr ) {
					tr.draggable = true;
				} );
			} );
			observer.observe( tbody, { childList: true } );
		} );

		function reindex( tbody ) {
			tbody.querySelectorAll( 'tr' ).forEach( function ( tr, i ) {
				tr.querySelectorAll( '[name]' ).forEach( function ( input ) {
					input.name = input.name.replace( /\[fields\]\[\d+\]/, '[fields][' + i + ']' );
				} );
			} );
		}
	}

	/* ------------------------------------------------------------------
	   Settings — Layouts tab pane toggle (no data)
	   ------------------------------------------------------------------ */
	function initLayoutsTab() {
		var layoutSel = document.getElementById( 'trx_ad_single_layout' );
		var panes = document.querySelectorAll( '[data-layout-pane]' );
		if ( ! layoutSel || ! panes.length ) {
			return;
		}
		function syncPanes() {
			panes.forEach( function ( p ) {
				p.style.display = ( p.getAttribute( 'data-layout-pane' ) === layoutSel.value ) ? '' : 'none';
			} );
		}
		layoutSel.addEventListener( 'change', syncPanes );
		syncPanes();
	}

	/* ------------------------------------------------------------------
	   Vehicle list table — quick-edit value copy (no data)
	   ------------------------------------------------------------------ */
	function initQuickEdit() {
		if ( typeof window.inlineEditPost === 'undefined' || ! document.querySelector( '.trx-ad-qe-price' ) ) {
			return;
		}
		var wpInlineEdit = window.inlineEditPost.edit;
		window.inlineEditPost.edit = function ( id ) {
			wpInlineEdit.apply( this, arguments );

			var postId = 0;
			if ( typeof id === 'object' ) {
				postId = parseInt( this.getId( id ), 10 );
			}

			if ( postId > 0 ) {
				var row = document.getElementById( 'post-' + postId );
				if ( ! row ) {
					return;
				}

				var priceCell = row.querySelector( '.column-trx_ad_price' );
				var statusCell = row.querySelector( '.column-trx_ad_status' );
				var editRow = document.getElementById( 'edit-' + postId );
				if ( ! editRow ) {
					return;
				}

				if ( priceCell ) {
					var priceText = priceCell.textContent.replace( /[^0-9.]/g, '' );
					var priceInput = editRow.querySelector( '.trx-ad-qe-price' );
					if ( priceInput ) {
						priceInput.value = priceText;
					}
				}

				if ( statusCell ) {
					var statusSpan = statusCell.querySelector( 'span' );
					var statusSelect = editRow.querySelector( '.trx-ad-qe-status' );
					if ( statusSpan && statusSelect ) {
						var statusMap = {
							'Available': 'available',
							'Sold': 'sold',
							'Reserved': 'reserved',
							'Coming Soon': 'coming_soon'
						};
						var statusText = statusSpan.textContent.trim();
						statusSelect.value = statusMap[ statusText ] || 'available';
					}
				}
			}
		};
	}

	function boot() {
		initTaxonomiesTab();
		initFieldsTab();
		initFormsTab();
		initLayoutsTab();
		initQuickEdit();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', boot );
	} else {
		boot();
	}
} )();
