(function ($) {
	'use strict';

	var cfg = window.rcIngredientModal || {};
	var $modal = null;
	var $targetRow = null;
	var $currentLink = null;

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

	function init() {
		$modal = $('#rc-ingredient-modal');
		if (!$modal.length) {
			return;
		}

		$(document).on('click', '.rc-open-ingredient-modal', openCreateModal);
		$(document).on('click', '.rc-edit-ingredient', openEditModal);
		$modal.on('click', '#rc-prev-ingredient', navIngredient);
		$modal.on('click', '#rc-next-ingredient', navIngredient);
		$modal.on('click', '.rc-modal-close, .rc-modal-cancel, .rc-modal-backdrop', closeModal);
		$modal.on('submit', '#rc-ingredient-modal-form', saveIngredient);
		$modal.on('change', '#rc-new-ingredient-unit', updateWeightLabel);
		$modal.on('click', '#rc-calc-cost', calcCost);
		$modal.on('click', '#rc-add-food-type', showFoodTypeInput);
		$modal.on('click', '#rc-save-food-type', saveFoodType);
		$modal.on('click', '#rc-cancel-food-type', hideFoodTypeInput);
		$modal.on('click', '#rc-add-supplier', showSupplierInput);
		$modal.on('click', '#rc-save-supplier', saveSupplier);
		$modal.on('click', '#rc-cancel-supplier', hideSupplierInput);
		$modal.on('click', '#rc-add-area', showAreaInput);
		$modal.on('click', '#rc-save-area', saveArea);
		$modal.on('click', '#rc-cancel-area', hideAreaInput);
		$modal.on('click', '#rc-copy-ingredient', copyIngredient);
		$modal.on('click', '#rc-edit-recipe-button, #rc-edit-recipe-button-top', editSubRecipe);
		$modal.on('click', '#rc-delete-ingredient', deleteIngredient);

		$(document).on('keydown', function (e) {
			if (e.key === 'Escape' && !$modal.prop('hidden')) {
				closeModal(e);
			}
		});
	}

	function openCreateModal(e) {
		e.preventDefault();
		$targetRow = $(e.currentTarget).closest('tr.rc-line-row');
		if (!$targetRow.length) {
			$targetRow = null;
		}

		var prefill = $(e.currentTarget).data('prefill-name') || '';
		if (!prefill && $targetRow && $targetRow.length) {
			prefill = $targetRow.find('.rc-ingredient-input').val() || '';
		}
		
		$('#rc-ingredient-modal-form')[0].reset();
		$('#rc-new-ingredient-id').val('');
		$('#rc-new-ingredient-name').val(prefill);
		$('#rc-copy-ingredient').hide();
		$('#rc-edit-recipe-button').hide();
		$('#rc-edit-recipe-button-top').hide();
		$('#rc-sub-recipe-notice').hide();
		$('#rc-save-ingredient-btn').show();
		$('#rc-calc-cost').show();
		$('#rc-ingredient-modal-form').find('input, select, textarea').prop('disabled', false);
		updateWeightLabel();
		$modal.prop('hidden', false);
		$('#rc-new-ingredient-name').trigger('focus');
	}

	function openEditModal(e) {
		e.preventDefault();
		var $link = $(e.currentTarget);
		$currentLink = $link;
		var id = $link.data('id');
		if (!id) return;

		$targetRow = null;
		
		var $nameInput = $('#rc-new-ingredient-name');
		$nameInput.prop('disabled', true);
		var wasSubRecipe = false;

		$.getJSON(cfg.ajaxUrl, {
			action: 'rc_get_ingredient',
			nonce: cfg.nonce,
			id: id
		}).done(function (resp) {
			if (!resp || !resp.success) {
				$('#rc-ingredient-modal-error').text('Could not fetch ingredient data.').prop('hidden', false);
				return;
			}
			var item = resp.data;
			var isSubRecipe = item.is_recipe && parseInt(item.is_recipe) === 1;
			wasSubRecipe = isSubRecipe;

			$('#rc-ingredient-modal-form')[0].reset();
			$('#rc-sub-recipe-notice').hide();
			$('#rc-edit-recipe-button').hide();
			$('#rc-edit-recipe-button-top').hide();
			$('#rc-ingredient-modal-error').prop('hidden', true).text('');

			if (isSubRecipe) {
				$('#rc-sub-recipe-notice').show();
				var recipeId = item.recipe_id || 0;
				$('#rc-edit-recipe-button').show().data('recipe-id', recipeId);
				$('#rc-edit-recipe-button-top').show().data('recipe-id', recipeId);
				$('#rc-copy-ingredient').hide();
				$('#rc-delete-ingredient').hide();
				$('#rc-save-ingredient-btn').hide();
				$('#rc-calc-cost').hide();
				$('#rc-ingredient-modal-form').find('input, select, textarea').prop('disabled', true);
				$('#rc-edit-recipe-button').prop('disabled', false);
			} else {
				$('#rc-copy-ingredient').show();
				$('#rc-delete-ingredient').show();
				$('#rc-save-ingredient-btn').show();
				$('#rc-calc-cost').show();
			}
			
			$('#rc-new-ingredient-id').val(item.id);
			$('#rc-new-ingredient-name').val(item.name);
			$('#rc-new-ingredient-type').val(item.food_type);
			$('#rc-new-ingredient-area').val(item.area || '');
			$('#rc-new-ingredient-min-level').val(fmtNum(item.min_level));

			var unit = 'g';
			var hint = (item.size_label || '').toLowerCase();
			if (hint.includes('ml')) unit = 'ml';
			else if (hint.includes('ea')) unit = 'ea';
			$('#rc-new-ingredient-unit').val(unit);

			$('#rc-new-ingredient-weight').val(fmtNum(item.weight_grams));
			$('#rc-new-ingredient-package-size').val(fmtNum(item.package_size));
			$('#rc-new-ingredient-package-cost').val(fmtNum(item.package_cost));
			$('#rc-new-ingredient-cost').val(fmtNum(item.food_cost));
			$('#rc-new-ingredient-size').val(item.size_label);

			var $sup = $('#rc-new-ingredient-supplier');
			if (item.supplier && $sup.find('option[value="' + item.supplier.replace(/"/g, '\\"') + '"]').length === 0) {
				$sup.append($('<option></option>').attr('value', item.supplier).text(item.supplier));
			}
			$sup.val(item.supplier);

			$('#rc-nutri-calories').val(fmtNum(item.calories));
			$('#rc-nutri-fat').val(fmtNum(item.fat_grams));
			$('#rc-nutri-satfat').val(fmtNum(item.saturated_fat_grams));
			$('#rc-nutri-transfat').val(fmtNum(item.trans_fat_grams));
			$('#rc-nutri-carbs').val(fmtNum(item.carb_grams));
			$('#rc-nutri-fiber').val(fmtNum(item.fiber_grams));
			$('#rc-nutri-sugar').val(fmtNum(item.sugar_grams));
			$('#rc-nutri-chol').val(fmtNum(item.cholesterol_mg));
			$('#rc-nutri-protein').val(fmtNum(item.protein_grams));
			$('#rc-nutri-sodium').val(fmtNum(item.sodium_mg));
			$('#rc-nutri-vita').val(fmtNum(item.vit_a));
			$('#rc-nutri-vitc').val(fmtNum(item.vit_c_mg));
			$('#rc-nutri-potassium').val(fmtNum(item.potassium_mg));
			$('#rc-nutri-calcium').val(fmtNum(item.calcium_mg));
			$('#rc-nutri-iron').val(fmtNum(item.iron_mg));

			$('#rc-new-ingredient-ingredients-text').val(item.ingredients_text || '');

			var prevId = parseInt($link.data('prev-id')) || 0;
			var nextId = parseInt($link.data('next-id')) || 0;
			$('#rc-prev-ingredient').toggle(prevId > 0).data('nav-id', prevId);
			$('#rc-next-ingredient').toggle(nextId > 0).data('nav-id', nextId);
			var $pn = $('.rc-prev-next').show();
			$pn.removeClass('rc-prev-only rc-next-only');
			if (!(prevId > 0) && nextId > 0) {
				$pn.addClass('rc-next-only');
			} else if (prevId > 0 && !(nextId > 0)) {
				$pn.addClass('rc-prev-only');
			}

			updateWeightLabel();
			$modal.prop('hidden', false);
		}).fail(function () {
			$('#rc-ingredient-modal-error').text('Request failed to fetch ingredient.').prop('hidden', false);
		}).always(function () {
			$nameInput.prop('disabled', wasSubRecipe);
		});
	}

	function editSubRecipe(e) {
		e.preventDefault();
		var recipeId = $(this).data('recipe-id');
		if (recipeId) {
			window.location.href = 'admin.php?page=restaurant-costing-recipe-edit&id=' + recipeId;
		}
	}

	function navIngredient(e) {
		e.preventDefault();
		var navId = $(this).data('nav-id');
		if (!navId) return;
		var $newLink = $('.rc-edit-ingredient[data-id="' + navId + '"]');
		if ($newLink.length) {
			$newLink.trigger('click');
		}
	}

	function closeModal(e) {
		if (e) {
			e.preventDefault();
		}
		$modal.prop('hidden', true);
		$targetRow = null;
		$('#rc-copy-ingredient').hide();
		$('#rc-delete-ingredient').hide();
		$('.rc-prev-next').hide().removeClass('rc-prev-only rc-next-only');
		$('#rc-edit-recipe-button').hide();
		$('#rc-edit-recipe-button-top').hide();
		$('#rc-sub-recipe-notice').hide();
		$('#rc-save-ingredient-btn').show();
		$('#rc-calc-cost').show();
		$('#rc-ingredient-modal-form').find('input, select, textarea').prop('disabled', false);
	}

	function updateWeightLabel() {
		var unit = $('#rc-new-ingredient-unit').val();
		$('.rc-weight-unit-label').text(unit === 'ea' ? 'g' : unit);
	}

	function calcCost(e) {
		e.preventDefault();
		var $error = $('#rc-ingredient-modal-error');

		var weight = parseFloat($('#rc-new-ingredient-weight').val());
		var pkgSize = parseFloat($('#rc-new-ingredient-package-size').val());
		var pkgCost = parseFloat($('#rc-new-ingredient-package-cost').val());

		var missing = [];
		if (isNaN(weight) || weight <= 0) missing.push('Weight');
		if (isNaN(pkgSize) || pkgSize <= 0) missing.push('Package size');
		if (isNaN(pkgCost) || pkgCost < 0) missing.push('Package cost');

		if (missing.length > 0) {
			$error.text('Missing data: ' + missing.join(', ') + '.').prop('hidden', false);
			return;
		}

		var foodCost = (pkgCost / pkgSize) * weight;
		$('#rc-new-ingredient-cost').val(fmtNum(foodCost));
		$error.prop('hidden', true).text('');
	}

	function floatOrNull(val) {
		var n = parseFloat(val);
		return isNaN(n) ? '' : n;
	}

	function saveIngredient(e) {
		e.preventDefault();
		var $error = $('#rc-ingredient-modal-error');
		$error.prop('hidden', true).text('');

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

		$.post(cfg.ajaxUrl, {
			action: 'rc_save_ingredient',
			nonce: cfg.nonce,
			id: $('#rc-new-ingredient-id').val(),
			name: $('#rc-new-ingredient-name').val(),
			food_type: $('#rc-new-ingredient-type').val(),
			unit: $('#rc-new-ingredient-unit').val(),
			weight_grams: $('#rc-new-ingredient-weight').val(),
			food_cost: $('#rc-new-ingredient-cost').val(),
			min_level: $('#rc-new-ingredient-min-level').val(),
			size_label: $('#rc-new-ingredient-size').val(),
			supplier: $('#rc-new-ingredient-supplier').val(),
			area: $('#rc-new-ingredient-area').val(),
			package_size: $('#rc-new-ingredient-package-size').val(),
			package_cost: $('#rc-new-ingredient-package-cost').val(),
			calories: floatOrNull($('#rc-nutri-calories').val()),
			fat_grams: floatOrNull($('#rc-nutri-fat').val()),
			saturated_fat_grams: floatOrNull($('#rc-nutri-satfat').val()),
			trans_fat_grams: floatOrNull($('#rc-nutri-transfat').val()),
			carb_grams: floatOrNull($('#rc-nutri-carbs').val()),
			fiber_grams: floatOrNull($('#rc-nutri-fiber').val()),
			sugar_grams: floatOrNull($('#rc-nutri-sugar').val()),
			cholesterol_mg: floatOrNull($('#rc-nutri-chol').val()),
			protein_grams: floatOrNull($('#rc-nutri-protein').val()),
			sodium_mg: floatOrNull($('#rc-nutri-sodium').val()),
			vit_a: floatOrNull($('#rc-nutri-vita').val()),
			vit_c_mg: floatOrNull($('#rc-nutri-vitc').val()),
			potassium_mg: floatOrNull($('#rc-nutri-potassium').val()),
			calcium_mg: floatOrNull($('#rc-nutri-calcium').val()),
			iron_mg: floatOrNull($('#rc-nutri-iron').val()),
		})
			.done(function (resp) {
				if (!resp || !resp.success) {
					$error.text((resp && resp.data && resp.data.message) || 'Could not save.').prop('hidden', false);
					return;
				}
				
				window.location.reload();
			})
			.fail(function (xhr) {
				console.error('AJAX Error:', xhr);
				$error.text('Request failed. Please check if you are logged in and have permission.').prop('hidden', false);
			})
			.always(function () {
				$btn.prop('disabled', false);
			});
	}

	function copyIngredient(e) {
		e.preventDefault();
		var $error = $('#rc-ingredient-modal-error');
		$error.prop('hidden', true).text('');

		var $btn = $('#rc-copy-ingredient');
		$btn.prop('disabled', true);

		$.post(cfg.ajaxUrl, {
			action: 'rc_save_ingredient',
			nonce: cfg.nonce,
			id: $('#rc-new-ingredient-id').val(),
			name: $('#rc-new-ingredient-name').val(),
			food_type: $('#rc-new-ingredient-type').val(),
			unit: $('#rc-new-ingredient-unit').val(),
			weight_grams: $('#rc-new-ingredient-weight').val(),
			food_cost: $('#rc-new-ingredient-cost').val(),
			min_level: $('#rc-new-ingredient-min-level').val(),
			size_label: $('#rc-new-ingredient-size').val(),
			supplier: $('#rc-new-ingredient-supplier').val(),
			area: $('#rc-new-ingredient-area').val(),
			package_size: $('#rc-new-ingredient-package-size').val(),
			package_cost: $('#rc-new-ingredient-package-cost').val(),
			calories: floatOrNull($('#rc-nutri-calories').val()),
			fat_grams: floatOrNull($('#rc-nutri-fat').val()),
			saturated_fat_grams: floatOrNull($('#rc-nutri-satfat').val()),
			trans_fat_grams: floatOrNull($('#rc-nutri-transfat').val()),
			carb_grams: floatOrNull($('#rc-nutri-carbs').val()),
			fiber_grams: floatOrNull($('#rc-nutri-fiber').val()),
			sugar_grams: floatOrNull($('#rc-nutri-sugar').val()),
			cholesterol_mg: floatOrNull($('#rc-nutri-chol').val()),
			protein_grams: floatOrNull($('#rc-nutri-protein').val()),
			sodium_mg: floatOrNull($('#rc-nutri-sodium').val()),
			vit_a: floatOrNull($('#rc-nutri-vita').val()),
			vit_c_mg: floatOrNull($('#rc-nutri-vitc').val()),
			potassium_mg: floatOrNull($('#rc-nutri-potassium').val()),
			calcium_mg: floatOrNull($('#rc-nutri-calcium').val()),
			iron_mg: floatOrNull($('#rc-nutri-iron').val()),
		})
			.done(function (resp) {
				if (!resp || !resp.success) {
					$error.text((resp && resp.data && resp.data.message) || 'Could not save original ingredient.').prop('hidden', false);
					return;
				}

				// Clear id and name to turn it into a new copy
				$('#rc-new-ingredient-id').val('');
				$('#rc-new-ingredient-name').val('').trigger('focus');
				$('#rc-copy-ingredient').hide();
				$error.text('Original saved. Fill in a new name and click Save to create the copy.').prop('hidden', false);
			})
			.fail(function (xhr) {
				$error.text('Request failed. Please check if you are logged in and have permission.').prop('hidden', false);
			})
			.always(function () {
				$btn.prop('disabled', false);
			});
	}

	function deleteIngredient(e) {
		e.preventDefault();
		var id = $('#rc-new-ingredient-id').val();
		if (!id) return;

		rcConfirm('Delete this ingredient permanently? This cannot be undone.', function (confirmed) {
			if (!confirmed) return;

			var $error = $('#rc-ingredient-modal-error');
			$error.prop('hidden', true).text('');

			var $btn = $('#rc-delete-ingredient');
			$btn.prop('disabled', true);

			$.post(cfg.ajaxUrl, {
				action: 'rc_delete_ingredient',
				nonce: cfg.nonce,
				id: id
			})
				.done(function (resp) {
					if (!resp || !resp.success) {
						$error.text((resp && resp.data && resp.data.message) || 'Could not delete.').prop('hidden', false);
						return;
					}
					window.location.reload();
				})
				.fail(function () {
					$error.text('Request failed.').prop('hidden', false);
				})
				.always(function () {
					$btn.prop('disabled', false);
				});
		});
	}

	function showFoodTypeInput() {
		$('#rc-add-food-type').hide();
		$('#rc-new-food-type-row').show();
		$('#rc-new-food-type-input').val('').trigger('focus');
	}

	function hideFoodTypeInput() {
		$('#rc-add-food-type').show();
		$('#rc-new-food-type-row').hide();
		$('#rc-new-food-type-input').val('');
	}

	function saveFoodType() {
		var name = $.trim($('#rc-new-food-type-input').val());
		if (!name) {
			return;
		}

		$.post(cfg.ajaxUrl, {
			action: 'rc_add_food_type',
			nonce: cfg.nonce,
			name: name
		}).done(function (resp) {
			if (resp && resp.success) {
				var $select = $('#rc-new-ingredient-type');
				$select.append($('<option></option>').attr('value', name).text(name));
				$select.val(name);
				hideFoodTypeInput();
			}
		});
	}

	function showSupplierInput() {
		$('#rc-add-supplier').hide();
		$('#rc-new-supplier-row').show();
		$('#rc-new-supplier-input').val('').trigger('focus');
	}

	function hideSupplierInput() {
		$('#rc-add-supplier').show();
		$('#rc-new-supplier-row').hide();
		$('#rc-new-supplier-input').val('');
	}

	function saveSupplier() {
		var name = $.trim($('#rc-new-supplier-input').val());
		if (!name) {
			return;
		}

		$.post(cfg.ajaxUrl, {
			action: 'rc_add_supplier',
			nonce: cfg.nonce,
			name: name
		}).done(function (resp) {
			if (resp && resp.success) {
				var $select = $('#rc-new-ingredient-supplier');
				$select.append($('<option></option>').attr('value', name).text(name));
				$select.val(name);
				hideSupplierInput();
			}
		});
	}

	function showAreaInput() {
		$('#rc-add-area').hide();
		$('#rc-new-area-row').show();
		$('#rc-new-area-input').val('').trigger('focus');
	}

	function hideAreaInput() {
		$('#rc-add-area').show();
		$('#rc-new-area-row').hide();
		$('#rc-new-area-input').val('');
	}

	function saveArea() {
		var name = $.trim($('#rc-new-area-input').val());
		if (!name) {
			return;
		}

		$.post(cfg.ajaxUrl, {
			action: 'rc_add_area',
			nonce: cfg.nonce,
			name: name
		}).done(function (resp) {
			if (resp && resp.success) {
				var $select = $('#rc-new-ingredient-area');
				$select.append($('<option></option>').attr('value', name).text(name));
				$select.val(name);
				hideAreaInput();
			}
		});
	}

	$(init);
})(jQuery);
