/* global jQuery, woowsnFree */
(function ($) {
	'use strict';

	// ── Registration field builder ─────────────────────────────────
	var fieldIndex = $('#woowsn-fields-body tr').length;

	$('#woowsn-add-field').on('click', function () {
		var template = $('#woowsn-field-template tbody').html();
		if (!template) return;

		var row = template
			.replace(/__FIELDS__/g, 'fields')
			.replace(/__IDX__/g, fieldIndex);

		$('#woowsn-fields-body').append(row);
		fieldIndex++;
	});

	$(document).on('click', '.woowsn-remove-field', function () {
		$(this).closest('tr').remove();
	});

	// Auto-generate field key from label for new rows.
	$(document).on('input', '.woowsn-field-key-input', function () {
		var key = $(this).val()
			.toLowerCase()
			.replace(/[^a-z0-9]+/g, '_')
			.replace(/^_+|_+$/g, '');

		if (!/^woowsn_/.test(key)) {
			key = 'woowsn_' + key;
		}

		$(this).siblings('.woowsn-field-key-hidden').val(key);
	});

}(jQuery));
