/**
 * Options Page Builder — repeater row UI on live options pages.
 */
(function ($) {
	'use strict';

	function renumberRows($rows) {
		$rows.find('.wpps-opb-repeater__row').each(function (i) {
			var $row = $(this);
			$row.attr('data-row', String(i));
			$row.find('.wpps-opb-repeater__row-num').text(String(i + 1));
			$row.find('[name]').each(function () {
				var name = $(this).attr('name');
				if (name) {
					$(this).attr(
						'name',
						name.replace(/\[\d+\]/, '[' + i + ']').replace(/\[__ROW__\]/, '[' + i + ']')
					);
				}
				var id = $(this).attr('id');
				if (id) {
					$(this).attr('id', id.replace(/-\d+-/, '-' + i + '-').replace(/-__ROW__-/, '-' + i + '-'));
				}
			});
			$row.find('[data-target]').each(function () {
				var target = $(this).attr('data-target');
				if (target) {
					$(this).attr('data-target', target.replace(/-\d+-/, '-' + i + '-').replace(/-__ROW__-/, '-' + i + '-'));
				}
			});
		});
	}

	$(function () {
		$('.wpps-opb-repeater__rows').each(function () {
			renumberRows($(this));
		});

		$(document).on('click', '.wpps-opb-repeater__add', function (e) {
			e.preventDefault();
			var $repeater = $(this).closest('.wpps-opb-repeater');
			var max = parseInt($repeater.data('max'), 10) || 0;
			var $rows = $repeater.find('.wpps-opb-repeater__rows');
			if (max > 0 && $rows.find('.wpps-opb-repeater__row').length >= max) {
				return;
			}
			var template = $repeater.find('.wpps-opb-repeater-row-template').html();
			if (!template) {
				return;
			}
			var index = $rows.find('.wpps-opb-repeater__row').length;
			$rows.append(template.replace(/__ROW__/g, String(index)));
			renumberRows($rows);
		});

		$(document).on('click', '.wpps-opb-repeater__remove', function (e) {
			e.preventDefault();
			var $repeater = $(this).closest('.wpps-opb-repeater');
			var min = parseInt($repeater.data('min'), 10) || 0;
			var $rows = $repeater.find('.wpps-opb-repeater__rows');
			if ($rows.find('.wpps-opb-repeater__row').length <= min) {
				return;
			}
			$(this).closest('.wpps-opb-repeater__row').remove();
			renumberRows($rows);
		});
	});
})(jQuery);
