/**
 * Custom Fields repeater and flexible content row UI.
 */
(function ($) {
	'use strict';

	function renumberRows($wrap, selector) {
		$wrap.find(selector).each(function (i) {
			var $row = $(this);
			$row.attr('data-row', String(i));
			$row.find('.cf-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 + ']')
					);
				}
			});
		});
	}

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

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

		$(document).on('click', '.cf-flexible__add', function (e) {
			e.preventDefault();
			var $flex = $(this).closest('.cf-flexible');
			var layout = $flex.find('.cf-flexible__layout-select').val();
			if (!layout) {
				return;
			}
			var template = $flex.find('.cf-flexible-row-template[data-layout="' + layout + '"]').html();
			if (!template) {
				return;
			}
			var $rows = $flex.find('.cf-flexible__rows');
			var index = $rows.find('.cf-flexible__row').length;
			$rows.append(template.replace(/__ROW__/g, String(index)));
			renumberRows($rows, '.cf-flexible__row');
		});

		$(document).on('click', '.cf-flexible__remove', function (e) {
			e.preventDefault();
			var $rows = $(this).closest('.cf-flexible').find('.cf-flexible__rows');
			$(this).closest('.cf-flexible__row').remove();
			renumberRows($rows, '.cf-flexible__row');
		});

		$('.cf-repeater__rows').each(function () {
			renumberRows($(this), '.cf-repeater__row');
		});
	});
})(jQuery);
