/**
 * Kramar — Weight-Based Shipping rules table admin JS.
 *
 * Handles:
 *  - "Add Rule" clones the hidden template row into the live tbody.
 *  - "Delete" removes a rule row.
 *  - On WC settings form submit, serialises all rows to JSON and writes it
 *    into the hidden #kramar-wbs-rules-json field before the form posts.
 *
 * No jQuery. No inline scripts. Plain ES5 for broad compatibility.
 */
( function () {
	'use strict';

	var tbody     = null;
	var jsonInput = null;
	var addBtn    = null;
	var template  = null;

	function init() {
		tbody     = document.getElementById( 'kramar-wbs-rules-body' );
		jsonInput = document.getElementById( 'kramar-wbs-rules-json' );
		addBtn    = document.getElementById( 'kramar-wbs-add-rule' );

		var templateTable = document.getElementById( 'kramar-wbs-row-template' );
		if ( templateTable ) {
			template = templateTable.querySelector( 'tr' );
		}

		if ( ! tbody || ! jsonInput || ! addBtn || ! template ) {
			return;
		}

		// "Add Rule" button.
		addBtn.addEventListener( 'click', function () {
			addRow();
		} );

		// Delegate delete clicks inside the tbody.
		tbody.addEventListener( 'click', function ( e ) {
			var btn = e.target;
			if ( btn && btn.classList.contains( 'kramar-wbs-delete-row' ) ) {
				var row = btn.closest( 'tr' );
				if ( row ) {
					row.parentNode.removeChild( row );
				}
			}
		} );

		// Serialize before the WC settings form submits.
		var form = jsonInput.closest( 'form' );
		if ( form ) {
			form.addEventListener( 'submit', function () {
				jsonInput.value = serializeRows();
			} );
		}
	}

	/**
	 * Clone the template row and append it to the live tbody.
	 */
	function addRow() {
		var newRow = template.cloneNode( true );

		// Reset all field values in the cloned row.
		var inputs = newRow.querySelectorAll( 'input[type="text"], input[type="number"]' );
		for ( var i = 0; i < inputs.length; i++ ) {
			inputs[ i ].value = inputs[ i ].defaultValue;
		}

		var checkboxes = newRow.querySelectorAll( 'input[type="checkbox"]' );
		for ( var j = 0; j < checkboxes.length; j++ ) {
			checkboxes[ j ].checked = true; // new rules default to enabled
		}

		var selects = newRow.querySelectorAll( 'select' );
		for ( var k = 0; k < selects.length; k++ ) {
			selects[ k ].selectedIndex = 0;
		}

		tbody.appendChild( newRow );
	}

	/**
	 * Collect all rule rows and return them as a JSON string.
	 *
	 * @returns {string} JSON array of rule objects.
	 */
	function serializeRows() {
		var rows  = tbody.querySelectorAll( 'tr.kramar-wbs-rule-row' );
		var rules = [];

		for ( var i = 0; i < rows.length; i++ ) {
			var row    = rows[ i ];
			var rule   = {};
			var fields = row.querySelectorAll( '.kramar-wbs-field' );

			for ( var j = 0; j < fields.length; j++ ) {
				var field = fields[ j ];
				var key   = field.getAttribute( 'data-field' );
				if ( ! key ) {
					continue;
				}

				if ( field.type === 'checkbox' ) {
					rule[ key ] = field.checked;
				} else {
					rule[ key ] = field.value;
				}
			}

			rules.push( rule );
		}

		return JSON.stringify( rules );
	}

	// Boot after DOM ready.
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
}() );
