(function ($) {
	'use strict';

	var cfg = window.rcRecipe || {};
	var lineIndex = 0;
	var laborIndex = 0;

	function init() {
		var $builder = $('.rc-recipe-builder');
		if (!$builder.length) {
			return;
		}

		lineIndex = $builder.find('.rc-line-row').length;
		laborIndex = $builder.find('.rc-labour-card').length;

		$builder.on('click', '.rc-add-line', addLine);
		$builder.on('click', '.rc-add-labor', addLabor);
		$builder.on('click', '.rc-remove-line', removeRow);
		$builder.on('click', '.rc-remove-labor', removeRow);
		$builder.on('input change', 'input, select, textarea', debounceRecalc);

		$builder.on('input', '.rc-ingredient-input', onIngredientInput);
		$builder.on('keydown', '.rc-ingredient-input', onIngredientKeydown);
		$(document).on('click', function (e) {
			if (!$(e.target).closest('.rc-ingredient-cell').length) {
				$('.rc-ingredient-suggestions').remove();
			}
		});

		$(document).on('click', '.rc-ingredient-suggestions li', onSuggestionPick);

		initSortable();
		recalc();

		// --- Photo / Media Manager ---
		var photoFrame;

		$builder.on('click', '#rc-set-photo', function (e) {
			e.preventDefault();

			if (photoFrame) {
				photoFrame.open();
				return;
			}

			photoFrame = wp.media({
				title: 'Choose or upload a menu item photo',
				library: { type: 'image' },
				multiple: false,
				button: { text: 'Use this photo' }
			});

			photoFrame.on('select', function () {
				var attachment = photoFrame.state().get('selection').first().toJSON();
				$('#rc-image-url').val(attachment.url);
				$('#rc-image-preview').html(
					'<img src="' + attachment.url + '" style="max-width:200px;max-height:200px;border:1px solid #ccc;padding:4px;" />'
				);
				$('#rc-remove-photo').show();
			});

			photoFrame.open();
		});

		$builder.on('click', '#rc-remove-photo', function () {
			$('#rc-image-url').val('');
			$('#rc-image-preview').empty();
			$(this).hide();
		});

		$builder.on('change', '#rc-print-image', function () {
			var checked = $(this).is(':checked') ? 1 : 0;
			var recipeId = parseInt($('input[name="recipe_id"]').val(), 10);
			if (!recipeId) return;
			$.post(cfg.ajaxUrl, {
				action: 'rc_toggle_print_image',
				nonce: cfg.nonce,
				recipe_id: recipeId,
				print_image: checked
			});
		});
	}

	function debounceRecalc() {
		clearTimeout(window._rcRecalcTimer);
		window._rcRecalcTimer = setTimeout(recalc, 200);
	}

	function initSortable() {
		if (!$.fn.sortable) return;
		$('.rc-lines tbody').sortable({
			handle: '.rc-drag-handle',
			axis: 'y',
			opacity: 0.7,
			placeholder: 'ui-sortable-placeholder',
			update: reindexLines
		});
	}

	function reindexLines() {
		$('.rc-line-row').each(function (i) {
			$(this).find('input, select').each(function () {
				var name = $(this).attr('name');
				if (name) {
					$(this).attr('name', name.replace(/lines\[\d+\]/, 'lines[' + i + ']'));
				}
			});
		});
		recalc();
	}

	function addLine(e) {
		e.preventDefault();
		var tpl = $('#rc-line-template').html().replace(/\{\{INDEX\}\}/g, String(lineIndex++));
		var $newRow = $(tpl);
		$('.rc-lines tbody').append($newRow);
		$newRow.find('.rc-ingredient-input').trigger('focus');
		recalc();
	}

	function addLabor(e) {
		e.preventDefault();
		var tpl = $('#rc-labor-template').html().replace(/\{\{INDEX\}\}/g, String(laborIndex++));
		var $newCard = $(tpl);
		$('.rc-labour-list').append($newCard);
		$newCard.find('input[type="text"]').trigger('focus');
		recalc();
	}

	function removeRow(e) {
		e.preventDefault();
		$(e.currentTarget).closest('.rc-labour-card, tr').remove();
		recalc();
	}

	function onIngredientInput(e) {
		var $input = $(e.currentTarget);
		var term = $input.val().trim();
		var $cell = $input.closest('.rc-ingredient-cell');
		$cell.find('.rc-ingredient-id').val('');

		$('.rc-ingredient-suggestions').remove();
		if (term.length < 2) {
			return;
		}

		$.getJSON(cfg.ajaxUrl, {
			action: 'rc_search_ingredients',
			nonce: cfg.nonce,
			term: term
		}).done(function (items) {
			if (!items || !items.length) {
				return;
			}
			var $ul = $('<ul class="rc-ingredient-suggestions" role="listbox"></ul>');
			items.forEach(function (item) {
				$ul.append(
					$('<li role="option"></li>')
						.attr('data-id', item.id)
						.attr('data-name', item.name)
						.attr('data-unit', item.unit_hint)
						.text(item.name + (item.food_type ? ' (' + item.food_type + ')' : ''))
				);
			});
			$cell.append($ul);
		});
	}

	function onIngredientKeydown(e) {
		var $list = $(e.currentTarget).closest('.rc-ingredient-cell').find('.rc-ingredient-suggestions');
		if (!$list.length) {
			return;
		}
		var $items = $list.find('li');
		var $sel = $items.filter('.is-selected');
		if (e.key === 'ArrowDown') {
			e.preventDefault();
			if (!$sel.length) {
				$items.first().addClass('is-selected');
			} else {
				$sel.removeClass('is-selected').next().addClass('is-selected');
			}
		} else if (e.key === 'ArrowUp') {
			e.preventDefault();
			if ($sel.length) {
				$sel.removeClass('is-selected').prev().addClass('is-selected');
			}
		} else if (e.key === 'Enter' && $sel.length) {
			e.preventDefault();
			$sel.trigger('click');
		}
	}

	function onSuggestionPick(e) {
		var $li = $(e.currentTarget);
		var $row = $li.closest('tr');
		$row.find('.rc-ingredient-input').val($li.data('name'));
		$row.find('.rc-ingredient-id').val($li.data('id'));
		$row.find('.rc-line-unit').val($li.data('unit') || 'g');
		$li.closest('.rc-ingredient-suggestions').remove();
		recalc();
	}

	window.rcRecipeRecalc = recalc;

	function recalc() {
		var $form = $('.rc-recipe-builder form');
		if (!$form.length) {
			return;
		}

		$.post(cfg.ajaxUrl, $form.serialize() + '&action=rc_calculate_recipe&nonce=' + encodeURIComponent(cfg.nonce))
			.done(function (resp) {
				if (!resp || !resp.success) {
					return;
				}
				var d = resp.data;
				$('#rc-cost-per-portion').text(formatMoney(d.cost_per_portion));
				$('#rc-food-cost-pct').text(d.menu_price > 0 ? d.food_cost_pct + '%' : '—');
				$('#rc-gross-profit').text(d.menu_price > 0 ? formatMoney(d.gross_profit) : '—');
				$('#rc-gross-margin-pct').text(d.menu_price > 0 ? d.gross_margin_pct + '%' : '—');
				$('#rc-labor-cost').text(formatMoney(d.labor_per_portion));

				if (d.nutrition) {
					$('#rc-portion-weight').text(Math.round(d.portion_weight) + ' g');
					$('#rc-nutrition-calories').text(d.nutrition.calories);
					$('#rc-nutrition-protein').text(d.nutrition.protein_grams + ' g');
					$('#rc-nutrition-fat').text(d.nutrition.fat_grams + ' g');
					$('#rc-nutrition-carbs').text(d.nutrition.carb_grams + ' g');
				}

				(d.line_details || []).forEach(function (line, i) {
					var $row = $('.rc-line-row').eq(i);
					$row.find('.rc-line-imperial').text(line.imperial || '—');
					$row.find('.rc-line-cost').text(formatMoney(line.line_cost));
				});
			});
	}

	function fmtNum(n) {
		var v = parseFloat(n);
		if (isNaN(v)) return '0';
		return String(v);
	}

	function formatMoney(n) {
		var v = parseFloat(n || 0);
		return '$' + (isNaN(v) ? '0.00' : v.toFixed(2));
	}

	// Intercept form submit to check duplicate recipe name
	$('.rc-recipe-builder form').on('submit', function(e) {
		var $form  = $(this);
		var $error = $('#rc-recipe-save-error');
		var name   = $('#rc-recipe-name').val().trim();
		var id     = parseInt($('input[name="recipe_id"]').val(), 10) || 0;

		if (!name) {
			$error.text('Please enter a recipe name.').show();
			e.preventDefault();
			return false;
		}

		$error.hide();
		var $btn = $form.find('button[type="submit"]');
		$btn.prop('disabled', true);

		$.post(cfg.ajaxUrl, {
			action: 'rc_check_recipe_name',
			nonce:  cfg.nonce,
			name:   name,
			id:     id
		}).done(function(resp) {
			if (resp && resp.success && resp.data.duplicate) {
				$error.text('Recipe Names must be unique.').show();
				$btn.prop('disabled', false);
			} else {
				$error.hide();
				$form[0].submit();
			}
		}).fail(function() {
			$error.text('Could not verify recipe name. Try again.').show();
			$btn.prop('disabled', false);
		});

		e.preventDefault();
		return false;
	});

	$(init);
})(jQuery);
