/* LEYENDA ESTADO DE LOS PLATOS
a = solicitado
b = preparacion
c = preparado
d = entregado
z = anulado
*/

var PRODUCTION_STATE = {
	currentView: 'pedidos',
	currentListTab: 1,
	channels: { mesa: [], mostrador: [], delivery: [] },
	counts: { mesa: 0, mostrador: 0, delivery: 0 },
	lastRefreshAt: null,
	hasLoadedOnce: false,
	refreshRequestId: 0,
	relativeClock: null,
	safetyPollingClock: null,
	refreshInFlight: false,
	pendingRefreshOptions: null,
	useCombinedEndpoint: true
};

function productionUrl(path) {
	return $('#url').val() + path;
}

function fetchJson(path, data) {
	var payload = $.extend({}, data || {}, { _rt: Date.now() });
	return $.ajax({
		type: 'POST',
		dataType: 'json',
		url: productionUrl(path),
		data: payload,
		cache: false,
		headers: {
			'Cache-Control': 'no-cache',
			'Pragma': 'no-cache'
		}
	});
}

function fetchJsonPromise(path, data) {
	return new Promise(function (resolve, reject) {
		fetchJson(path, data).done(function (response) {
			resolve(Array.isArray(response) ? response : []);
		}).fail(reject);
	});
}

function fetchJsonObjectPromise(path, data) {
	return new Promise(function (resolve, reject) {
		fetchJson(path, data).done(function (response) {
			resolve(response && typeof response === 'object' ? response : {});
		}).fail(reject);
	});
}

function escapeHtml(value) {
	return String(value == null ? '' : value)
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#39;');
}

function escapeJsString(value) {
	return String(value == null ? '' : value)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'");
}

function toNumber(value) {
	var parsed = parseFloat(value);
	return isNaN(parsed) ? 0 : parsed;
}

function formatQty(value) {
	var quantity = toNumber(value);
	return Number.isInteger(quantity) ? String(quantity) : quantity.toFixed(2).replace(/\.?0+$/, '');
}

function getAllItems() {
	return [].concat(PRODUCTION_STATE.channels.mesa, PRODUCTION_STATE.channels.mostrador, PRODUCTION_STATE.channels.delivery);
}

function getChannelLabel(key) {
	if (key === 'mesa') { return 'Mesa'; }
	if (key === 'mostrador') { return 'Para llevar'; }
	return 'Delivery';
}

function getChannelMeta(channelKey) {
	if (channelKey === 'mesa') {
		return {
			label: 'Mesa',
			className: 'mesa',
			iconClass: 'fa fa-utensils',
			flowLabel: 'Servicio',
			flowClass: 'service',
			flowIconClass: 'fa fa-bell-o',
			orderActionIconClass: 'fa fa-check-circle',
			orderActionLabel: 'Atender pedido'
		};
	}

	if (channelKey === 'mostrador') {
		return {
			label: 'Para llevar',
			className: 'mostrador',
			iconClass: 'fa fa-shopping-bag',
			flowLabel: 'Empaque',
			flowClass: 'pack',
			flowIconClass: 'fa fa-archive',
			orderActionIconClass: 'fa fa-shopping-bag',
			orderActionLabel: 'Entregar pedido'
		};
	}

	return {
		label: 'Delivery',
		className: 'delivery',
		iconClass: 'fa fa-motorcycle',
		flowLabel: 'Despacho',
		flowClass: 'dispatch',
		flowIconClass: 'fa fa-paper-plane',
		orderActionIconClass: 'fa fa-paper-plane',
		orderActionLabel: 'Despachar pedido'
	};
}

function getChannelKeyByType(tipoAtencion) {
	if (parseInt(tipoAtencion, 10) === 1) { return 'mesa'; }
	if (parseInt(tipoAtencion, 10) === 2) { return 'mostrador'; }
	return 'delivery';
}

function getStatusMeta(item) {
	if (parseInt(item.id_tipo, 10) === 2) {
		return { label: 'En espera', badgeClass: 'waiting', action: 'atendido', actionLabel: 'Despachar', actionClass: 'success', iconClass: 'fa fa-paper-plane' };
	}

	if (item.estado === 'b') {
		return { label: 'En preparacion', badgeClass: 'preparing', action: 'atendido', actionLabel: 'Listo', actionClass: 'success', iconClass: 'fa fa-check' };
	}

	return { label: 'En espera', badgeClass: 'waiting', action: 'preparacion', actionLabel: 'Iniciar', actionClass: 'primary', iconClass: 'fa fa-play' };
}

function getPriorityMeta(fechaPedido) {
	var minutes = Math.max(0, moment().diff(moment(fechaPedido), 'minutes'));
	if (minutes >= 15) { return { key: 'urgent', label: 'Urgente', minutes: minutes }; }
	if (minutes >= 8) { return { key: 'attention', label: 'Atencion', minutes: minutes }; }
	return { key: 'normal', label: 'Normal', minutes: minutes };
}

function getOperatorName(item) {
	var fullName = $.trim((item.nombres || '') + ' ' + (item.ape_paterno || ''));
	return fullName || 'Sin asignar';
}

function getOperatorMeta(item) {
	if (parseInt(item.tipo_atencion, 10) === 1) {
		return { label: 'Mozo', iconClass: 'fa fa-user-o' };
	}

	return { label: 'Caja', iconClass: 'fa fa-credit-card' };
}

function getSalonLabel(item) {
	var salon = item.desc_salon || '';
	return salon === 'MOSTRADOR' ? 'PARA LLEVAR' : salon;
}

function getContextTitle(item) {
	if (parseInt(item.tipo_atencion, 10) === 1) {
		return 'Mesa ' + escapeHtml(item.nro_mesa);
	}
	return 'Pedido ' + escapeHtml(item.nro_mesa);
}

function renderComment(comment) {
	if (!comment) { return ''; }
	return '<div class="production-comment"><i class="fa fa-comment"></i><span>' + escapeHtml(comment) + '</span></div>';
}

function normalizeLabelForCompare(value) {
	var text = $.trim((value || '').toString()).toLowerCase();
	if (!text) { return ''; }
	if (typeof text.normalize === 'function') {
		text = text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
	}
	text = $.trim(text.replace(/[^a-z0-9]+/g, ' '));
	if (!text) { return ''; }
	if (text.length > 3 && text.slice(-2) === 'es') {
		text = text.slice(0, -2);
	} else if (text.length > 3 && text.slice(-1) === 's') {
		text = text.slice(0, -1);
	}
	return text;
}

function isCategoryRedundantWithProduct(productName, categoryName) {
	var productNormalized = normalizeLabelForCompare(productName);
	var categoryNormalized = normalizeLabelForCompare(categoryName);
	if (!productNormalized || !categoryNormalized) { return false; }
	return productNormalized === categoryNormalized;
}

function getPrimaryPresentationLabel(item) {
	var presentation = $.trim((item && item.pres_prod) || '');
	if (presentation) { return presentation; }
	var product = $.trim((item && item.nombre_prod) || '');
	return product || 'Producto';
}

function getSecondaryProductLabel(item) {
	var product = $.trim((item && item.nombre_prod) || '');
	if (!product) { return ''; }
	var primary = getPrimaryPresentationLabel(item);
	if (isCategoryRedundantWithProduct(primary, product)) {
		return '';
	}
	return product;
}

function renderItemMetaChips(item) {
	var productLabel = getSecondaryProductLabel(item);
	if (!productLabel) {
		return '';
	}
	return '<div class="production-line__meta"><span class="production-chip production-chip--neutral production-chip--product-name">' + escapeHtml(productLabel) + '</span></div>';
}

function renderItemAction(item) {
	var statusMeta = getStatusMeta(item);
	var buttonClass = 'production-action-btn production-action-btn--' + statusMeta.actionClass;
	return '<button type="button" class="' + buttonClass + '" onclick="' + statusMeta.action + '(' + parseInt(item.id_pedido, 10) + ',' + parseInt(item.id_pres, 10) + ',\'' + escapeJsString(item.fecha_pedido) + '\');"><i class="' + escapeHtml(statusMeta.iconClass) + ' production-action-btn__icon"></i><span>' + escapeHtml(statusMeta.actionLabel) + '</span></button>';
}

function renderLoadingState(message) {
	return '<div class="production-loading"><div class="spinner-border" role="status"><span class="sr-only">Cargando</span></div><div>' + escapeHtml(message || 'Cargando pedidos...') + '</div></div>';
}

function renderEmptyState(title, detail) {
	return '<div class="production-empty"><i class="ti-check-box"></i><div class="font-weight-bold">' + escapeHtml(title) + '</div><div>' + escapeHtml(detail || 'No hay pendientes por mostrar.') + '</div></div>';
}

function renderOperatorSupport(item) {
	var operatorMeta = getOperatorMeta(item);
	return '<span class="production-ticket-card__support"><i class="' + escapeHtml(operatorMeta.iconClass) + '"></i><span>' + escapeHtml(operatorMeta.label + ': ' + getOperatorName(item)) + '</span></span>';
}

function renderLineOperatorNote(item) {
	var operatorMeta = getOperatorMeta(item);
	return '<span class="production-line__operator-note"><i class="' + escapeHtml(operatorMeta.iconClass) + '"></i><span>' + escapeHtml(operatorMeta.label + ': ' + getOperatorName(item)) + '</span></span>';
}

function getDistinctOperatorNames(items) {
	var seen = {};
	var names = [];

	$.each(items || [], function (_, item) {
		var name = $.trim(getOperatorName(item));
		if (!name || seen[name]) {
			return;
		}
		seen[name] = true;
		names.push(name);
	});

	return names;
}

function renderGroupOperatorSummary(items) {
	var names = getDistinctOperatorNames(items);
	if (!names.length) {
		return '';
	}

	if (names.length === 1) {
		return renderOperatorSupport((items || [])[0] || {});
	}

	var summaryLabel = names.length <= 2
		? 'Responsables: ' + names.join(', ')
		: 'Responsables: ' + names.length + ' personas';

	return '<span class="production-ticket-card__support"><i class="fa fa-users"></i><span>' + escapeHtml(summaryLabel) + '</span></span>';
}

function renderChannelFlowBadge(channelKey) {
	var channelMeta = getChannelMeta(channelKey);
	return '<span class="production-flow-badge production-flow-badge--' + channelMeta.flowClass + '"><i class="' + escapeHtml(channelMeta.flowIconClass) + '"></i><span>' + escapeHtml(channelMeta.flowLabel) + '</span></span>';
}

function renderChannelBadge(channelKey) {
	var channelMeta = getChannelMeta(channelKey);
	return '<span class="production-channel-badge production-channel-badge--' + channelMeta.className + '"><i class="' + escapeHtml(channelMeta.iconClass) + '"></i><span>' + escapeHtml(channelMeta.label) + '</span></span>';
}

function renderListRow(item, channelKey) {
	var channelMeta = getChannelMeta(channelKey);
	var priorityMeta = getPriorityMeta(item.fecha_pedido);
	var statusMeta = getStatusMeta(item);
	var contextDetail = channelKey === 'mesa' ? getSalonLabel(item) : getChannelLabel(channelKey);

	return '' +
		'<article class="production-ticket-card production-ticket-card--' + priorityMeta.key + ' production-ticket-card--channel-' + channelMeta.className + '">' +
			'<div class="production-ticket-card__body">' +
				'<div class="production-ticket-card__top">' +
					'<div class="production-ticket-card__eyebrow">' +
						renderChannelBadge(channelKey) +
						renderChannelFlowBadge(channelKey) +
						'<span class="production-priority-badge production-priority-badge--' + priorityMeta.key + '">' + escapeHtml(priorityMeta.label) + '</span>' +
					'</div>' +
					'<div class="production-ticket-card__time">' + escapeHtml(moment(item.fecha_pedido).fromNow()) + '</div>' +
				'</div>' +
				'<div class="production-product-cell">' +
					'<p class="production-ticket-card__title"><span class="production-qty">' + formatQty(item.cantidad) + ' uni</span> ' + escapeHtml(getPrimaryPresentationLabel(item)) + '</p>' +
					renderItemMetaChips(item) +
					renderComment(item.comentario) +
				'</div>' +
				'<div class="production-ticket-card__footer">' +
					'<div class="production-ticket-card__context">' +
						'<strong>' + getContextTitle(item) + '</strong>' +
						'<span>' + escapeHtml(contextDetail) + '</span>' +
						renderOperatorSupport(item) +
					'</div>' +
					'<div class="production-ticket-card__actions">' +
						'<div class="production-ticket-card__status"><span class="production-status-badge production-status-badge--' + statusMeta.badgeClass + '">' + escapeHtml(statusMeta.label) + '</span></div>' +
						renderItemAction(item) +
					'</div>' +
				'</div>' +
			'</div>' +
		'</article>';
}

function renderListTableBody(selector, items, channelKey) {
	var html = '';
	if (!items.length) {
		html = renderEmptyState('Sin pendientes', 'Este canal no tiene items pendientes.');
	} else {
		$.each(items, function (_, item) {
			html += renderListRow(item, channelKey);
		});
	}
	$(selector).html(html);
}

function groupItemsByOrder(items) {
	var grouped = {};

	$.each(items, function (_, item) {
		var key = String(item.id_pedido);
		if (!grouped[key]) {
			grouped[key] = {
				id_pedido: item.id_pedido,
				id_areap: item.id_areap,
				tipo_atencion: item.tipo_atencion,
				nro_mesa: item.nro_mesa,
				desc_salon: getSalonLabel(item),
				items: []
			};
		}
		grouped[key].items.push(item);
	});

	return Object.keys(grouped).map(function (key) {
		return grouped[key];
	}).sort(function (left, right) {
		return moment(left.items[0].fecha_pedido).valueOf() - moment(right.items[0].fecha_pedido).valueOf();
	});
}

function groupItemsByProduct(items) {
	var grouped = {};

	$.each(items, function (_, item) {
		var key = String(item.nombre_prod) + '|' + String(item.pres_prod);
		if (!grouped[key]) {
			grouped[key] = {
				nombre_prod: item.nombre_prod,
				pres_prod: item.pres_prod,
				pro_cat: item.Producto && item.Producto.pro_cat ? item.Producto.pro_cat : '',
				items: []
			};
		}
		grouped[key].items.push(item);
	});

	return Object.keys(grouped).map(function (key) {
		return grouped[key];
	}).sort(function (left, right) {
		return moment(left.items[0].fecha_pedido).valueOf() - moment(right.items[0].fecha_pedido).valueOf();
	});
}

function getGroupPriority(items) {
	var priority = { key: 'normal', label: 'Normal', minutes: 0 };
	$.each(items, function (_, item) {
		var itemPriority = getPriorityMeta(item.fecha_pedido);
		if (itemPriority.minutes > priority.minutes) {
			priority = itemPriority;
		}
	});
	return priority;
}

function getGroupTotals(items) {
	var totalQuantity = 0;
	var waiting = 0;
	var preparing = 0;

	$.each(items, function (_, item) {
		var statusMeta = getStatusMeta(item);
		totalQuantity += toNumber(item.cantidad);
		if (statusMeta.badgeClass === 'preparing') {
			preparing += 1;
		} else {
			waiting += 1;
		}
	});

	return { totalQuantity: totalQuantity, waiting: waiting, preparing: preparing };
}

function renderOrderGroup(group) {
	var totals = getGroupTotals(group.items);
	var priorityMeta = getGroupPriority(group.items);
	var channelKey = getChannelKeyByType(group.tipo_atencion);
	var channelMeta = getChannelMeta(channelKey);
	var groupClass = ' production-card--channel-' + channelMeta.className;
	if (priorityMeta.key !== 'normal') { groupClass += ' production-card--' + priorityMeta.key; }
	var linesHtml = '';

	$.each(group.items, function (_, item) {
		var statusMeta = getStatusMeta(item);
		var itemPriority = getPriorityMeta(item.fecha_pedido);

		linesHtml += '' +
			'<div class="production-line production-line--channel-' + channelMeta.className + '">' +
				'<div class="production-line__main">' +
					'<p class="production-line__title"><span class="production-qty">' + formatQty(item.cantidad) + ' uni</span> ' + escapeHtml(getPrimaryPresentationLabel(item)) + '</p>' +
					renderItemMetaChips(item) +
					renderComment(item.comentario) +
				'</div>' +
				'<div class="production-line__context"><strong>' + getContextTitle(item) + '</strong><span>' + escapeHtml(getSalonLabel(item)) + '</span></div>' +
				'<div class="production-timebox"><strong>' + escapeHtml(moment(item.fecha_pedido).fromNow()) + '</strong>' + renderLineOperatorNote(item) + '<div class="production-status-stack m-t-10"><span class="production-status-badge production-status-badge--' + statusMeta.badgeClass + '">' + escapeHtml(statusMeta.label) + '</span><span class="production-priority-badge production-priority-badge--' + itemPriority.key + '">' + escapeHtml(itemPriority.label) + '</span></div></div>' +
				'<div class="text-right">' + renderItemAction(item) + '</div>' +
			'</div>';
	});

	return '' +
		'<article class="production-card production-card--order-group' + groupClass + '">' +
			'<div class="production-card__header">' +
				'<div class="production-card__header-left">' +
					'<div class="production-card__eyebrow">' + renderChannelBadge(channelKey) + renderChannelFlowBadge(channelKey) + '<span class="production-priority-badge production-priority-badge--' + priorityMeta.key + '">' + escapeHtml(priorityMeta.label) + '</span></div>' +
					'<h3 class="production-card__title">' + getContextTitle(group) + '</h3>' +
					'<p class="production-card__subtitle">' + escapeHtml(group.desc_salon || 'Sin salon') + '</p>' +
					'<div class="production-card__support-row">' + renderGroupOperatorSummary(group.items) + '</div>' +
				'</div>' +
				'<div class="production-card__stats">' +
					'<div class="production-card__stat"><small>Total</small><strong>' + formatQty(totals.totalQuantity) + ' uni</strong></div>' +
					'<div class="production-card__stat"><small>Mayor espera</small><strong>' + escapeHtml(moment(group.items[0].fecha_pedido).fromNow()) + '</strong></div>' +
					'<div class="production-card__stat"><small>Estados</small><strong>' + totals.waiting + ' espera / ' + totals.preparing + ' prep.</strong></div>' +
				'</div>' +
				'<div><button type="button" class="production-action-btn production-order-action production-order-action--' + channelMeta.className + '" onclick="atendidopormesa(' + parseInt(group.id_pedido, 10) + ',' + parseInt(group.id_areap, 10) + ');"><i class="' + escapeHtml(channelMeta.orderActionIconClass) + ' production-action-btn__icon"></i><span>' + escapeHtml(channelMeta.orderActionLabel) + '</span></button></div>' +
			'</div>' +
			'<div class="production-card__body"><div class="production-card__body-grid">' + linesHtml + '</div></div>' +
		'</article>';
}

function renderProductGroup(group) {
	var totals = getGroupTotals(group.items);
	var priorityMeta = getGroupPriority(group.items);
	var groupClass = priorityMeta.key === 'normal' ? '' : ' production-card--' + priorityMeta.key;
	var productHint = getSecondaryProductLabel({ pres_prod: group.pres_prod, nombre_prod: group.nombre_prod });
	var eyebrowProductChip = productHint
		? '<span class="production-chip production-chip--neutral production-chip--product-name">' + escapeHtml(productHint) + '</span>'
		: '';
	var linesHtml = '';

	$.each(group.items, function (_, item) {
		var statusMeta = getStatusMeta(item);
		var itemPriority = getPriorityMeta(item.fecha_pedido);
		var channelKey = getChannelKeyByType(item.tipo_atencion);
		var channelMeta = getChannelMeta(channelKey);

		linesHtml += '' +
			'<div class="production-line production-line--channel-' + channelMeta.className + '">' +
				'<div class="production-line__main">' +
					'<p class="production-line__title"><span class="production-qty">' + formatQty(item.cantidad) + ' uni</span> ' + escapeHtml(getPrimaryPresentationLabel(item)) + '</p>' +
					renderItemMetaChips(item) +
					renderComment(item.comentario) +
				'</div>' +
				'<div class="production-line__context"><strong>' + getContextTitle(item) + '</strong><span>' + escapeHtml(getSalonLabel(item)) + '</span><div class="production-line__support m-t-10">' + renderChannelBadge(channelKey) + renderChannelFlowBadge(channelKey) + '</div></div>' +
				'<div class="production-timebox"><strong>' + escapeHtml(moment(item.fecha_pedido).fromNow()) + '</strong>' + renderLineOperatorNote(item) + '<div class="production-status-stack m-t-10"><span class="production-status-badge production-status-badge--' + statusMeta.badgeClass + '">' + escapeHtml(statusMeta.label) + '</span><span class="production-priority-badge production-priority-badge--' + itemPriority.key + '">' + escapeHtml(itemPriority.label) + '</span></div></div>' +
				'<div class="text-right">' + renderItemAction(item) + '</div>' +
			'</div>';
	});

	return '' +
		'<article class="production-card production-card--product-group' + groupClass + '">' +
			'<div class="production-card__header">' +
				'<div class="production-card__header-left">' +
					'<div class="production-card__eyebrow">' + eyebrowProductChip + '<span class="production-priority-badge production-priority-badge--' + priorityMeta.key + '">' + escapeHtml(priorityMeta.label) + '</span></div>' +
					'<h3 class="production-card__title">' + escapeHtml(getPrimaryPresentationLabel({ pres_prod: group.pres_prod, nombre_prod: group.nombre_prod })) + '</h3>' +
					'<p class="production-card__subtitle">' + escapeHtml(productHint ? 'Producto: ' + productHint : 'Agrupado desde todos los canales activos.') + '</p>' +
				'</div>' +
				'<div class="production-card__stats">' +
					'<div class="production-card__stat"><small>Total</small><strong>' + formatQty(totals.totalQuantity) + ' uni</strong></div>' +
					'<div class="production-card__stat"><small>Items</small><strong>' + group.items.length + ' registros</strong></div>' +
					'<div class="production-card__stat"><small>Mayor espera</small><strong>' + escapeHtml(moment(group.items[0].fecha_pedido).fromNow()) + '</strong></div>' +
				'</div>' +
			'</div>' +
			'<div class="production-card__body"><div class="production-card__body-grid">' + linesHtml + '</div></div>' +
		'</article>';
}

function setTextOrBlank(selector, value) {
	$(selector).text(value > 0 ? value : '');
}

function updateSummary() {
	var allItems = getAllItems();
	var waiting = 0;
	var urgent = 0;
	var orders = {};
	var products = {};
	var oldestMinutes = 0;

	$.each(allItems, function (_, item) {
		var statusMeta = getStatusMeta(item);
		var priorityMeta = getPriorityMeta(item.fecha_pedido);
		orders[String(item.id_pedido)] = true;
		products[String(item.nombre_prod) + '|' + String(item.pres_prod)] = true;
		if (statusMeta.badgeClass === 'waiting') { waiting += 1; }
		if (priorityMeta.key === 'urgent') { urgent += 1; }
		if (priorityMeta.minutes > oldestMinutes) { oldestMinutes = priorityMeta.minutes; }
	});

	$('#metric_total_items').text(allItems.length);
	$('#metric_total_orders').text(Object.keys(orders).length);
	$('#metric_waiting').text(waiting);
	$('#metric_urgent').text(urgent);
	$('#metric_oldest_wait').text(oldestMinutes > 0 ? 'Mayor espera: ' + oldestMinutes + ' min' : 'Sin demoras criticas');

	$('#metric_channel_mesa').text(PRODUCTION_STATE.counts.mesa);
	$('#metric_channel_most').text(PRODUCTION_STATE.counts.mostrador);
	$('#metric_channel_del').text(PRODUCTION_STATE.counts.delivery);

	setTextOrBlank('#cant_pedidos_mesa', PRODUCTION_STATE.counts.mesa);
	setTextOrBlank('#cant_pedidos_most', PRODUCTION_STATE.counts.mostrador);
	setTextOrBlank('#cant_pedidos_del', PRODUCTION_STATE.counts.delivery);
	setTextOrBlank('#mode_count_lista', allItems.length);
	setTextOrBlank('#mode_count_pedidos', Object.keys(orders).length);
	setTextOrBlank('#mode_count_platos', Object.keys(products).length);
}

function updateViewHeader() {
	if (PRODUCTION_STATE.currentView === 'lista') {
		$('#production_view_title').text('Orden de llegada');
		$('#production_view_subtitle').text('Toca un canal y avanza ticket por ticket sin perder de vista la urgencia.');
		return;
	}

	if (PRODUCTION_STATE.currentView === 'platos') {
		$('#production_view_title').text('Por producto');
		$('#production_view_subtitle').text('Ideal para estaciones de cocina que trabajan por lote o por tipo de preparacion.');
		return;
	}

	$('#production_view_title').text('Por pedido');
	$('#production_view_subtitle').text('Vista principal para completar ordenes y despachar cada ticket con un solo vistazo.');
}

function applyViewState() {
	$('.production-mode-btn').removeClass('active');
	$('.production-mode-btn[data-mode="' + PRODUCTION_STATE.currentView + '"]').addClass('active');

	if (PRODUCTION_STATE.currentView === 'lista') {
		$('.display-lista').removeClass('production-mode-hidden');
		$('.display-agrupacion-pedidos').addClass('production-mode-hidden');
		$('.display-agrupacion-platos').addClass('production-mode-hidden');
		$('#tipo_atencion').val(String(PRODUCTION_STATE.currentListTab));
		$('#tipo_atencion_opcional').val(String(PRODUCTION_STATE.currentListTab));
		$('.production-list-tab[data-tab="' + PRODUCTION_STATE.currentListTab + '"]').tab('show');
	} else if (PRODUCTION_STATE.currentView === 'platos') {
		$('.display-lista').addClass('production-mode-hidden');
		$('.display-agrupacion-pedidos').addClass('production-mode-hidden');
		$('.display-agrupacion-platos').removeClass('production-mode-hidden');
		$('#tipo_atencion').val('4');
	} else {
		$('.display-lista').addClass('production-mode-hidden');
		$('.display-agrupacion-pedidos').removeClass('production-mode-hidden');
		$('.display-agrupacion-platos').addClass('production-mode-hidden');
		$('#tipo_atencion').val('5');
	}

	updateViewHeader();
}

function renderGroupedOrders() {
	var groups = groupItemsByOrder(getAllItems());
	var html = '';
	if (!groups.length) {
		$('#agrupacion_pedidos_list').html(renderEmptyState('Sin pedidos pendientes', 'No hay tickets activos para esta area.'));
		return;
	}
	$.each(groups, function (_, group) { html += renderOrderGroup(group); });
	$('#agrupacion_pedidos_list').html(html);
}

function renderGroupedProducts() {
	var groups = groupItemsByProduct(getAllItems());
	var html = '';
	if (!groups.length) {
		$('#agrupacion_platos_list').html(renderEmptyState('Sin productos pendientes', 'No hay platos ni bebidas en cola por ahora.'));
		return;
	}
	$.each(groups, function (_, group) { html += renderProductGroup(group); });
	$('#agrupacion_platos_list').html(html);
}

function renderListView() {
	renderListTableBody('#list_pedidos_mesa', PRODUCTION_STATE.channels.mesa, 'mesa');
	renderListTableBody('#list_pedidos_most', PRODUCTION_STATE.channels.mostrador, 'mostrador');
	renderListTableBody('#list_pedidos_del', PRODUCTION_STATE.channels.delivery, 'delivery');
}

function renderCurrentView() {
	applyViewState();
	if (PRODUCTION_STATE.currentView === 'lista') { renderListView(); return; }
	if (PRODUCTION_STATE.currentView === 'platos') { renderGroupedProducts(); return; }
	renderGroupedOrders();
}

function updateLastRefreshLabel() {
	if (!PRODUCTION_STATE.lastRefreshAt) {
		$('#production_last_refresh').text('instantes');
		return;
	}
	$('#production_last_refresh').text(moment(PRODUCTION_STATE.lastRefreshAt).fromNow());
}

function playNotificationSoundIfNeeded(previousCounts, nextCounts) {
	var shouldPlay = nextCounts.mesa > previousCounts.mesa || nextCounts.mostrador > previousCounts.mostrador || nextCounts.delivery > previousCounts.delivery;
	if (!PRODUCTION_STATE.hasLoadedOnce || !shouldPlay) { return; }

	try {
		new buzz.sound('public/sound/ding_ding', { formats: ['ogg', 'mp3', 'aac'] }).play();
	} catch (error) {
		console.error('No se pudo reproducir el sonido de notificacion.', error);
	}
}

function mergeRefreshOptions(currentOptions, nextOptions) {
	var current = $.extend({ showLoading: false }, currentOptions || {});
	var incoming = $.extend({ showLoading: false }, nextOptions || {});

	return {
		showLoading: Boolean(current.showLoading || incoming.showLoading)
	};
}

function fetchLegacyChannelsPromise() {
	return Promise.all([
		fetchJsonPromise('produccion/mesas_list'),
		fetchJsonPromise('produccion/mostrador_list'),
		fetchJsonPromise('produccion/delivery_list')
	]);
}

function fetchChannelsSnapshotPromise() {
	if (!PRODUCTION_STATE.useCombinedEndpoint) {
		return fetchLegacyChannelsPromise();
	}

	return fetchJsonObjectPromise('produccion/panel_data').then(function (snapshot) {
		var mesa = Array.isArray(snapshot.mesa) ? snapshot.mesa : null;
		var mostrador = Array.isArray(snapshot.mostrador) ? snapshot.mostrador : null;
		var delivery = Array.isArray(snapshot.delivery) ? snapshot.delivery : null;

		if (mesa && mostrador && delivery) {
			return [mesa, mostrador, delivery];
		}

		PRODUCTION_STATE.useCombinedEndpoint = false;
		return fetchLegacyChannelsPromise();
	}).catch(function () {
		PRODUCTION_STATE.useCombinedEndpoint = false;
		return fetchLegacyChannelsPromise();
	});
}

function refreshChannelData(options) {
	var settings = $.extend({ showLoading: true }, options || {});
	if (PRODUCTION_STATE.refreshInFlight) {
		PRODUCTION_STATE.pendingRefreshOptions = mergeRefreshOptions(PRODUCTION_STATE.pendingRefreshOptions, settings);
		return Promise.resolve();
	}

	PRODUCTION_STATE.refreshInFlight = true;
	var requestId = ++PRODUCTION_STATE.refreshRequestId;
	var previousCounts = $.extend({}, PRODUCTION_STATE.counts);

	if (settings.showLoading) {
		if (PRODUCTION_STATE.currentView === 'lista') {
			$('#list_pedidos_mesa').html(renderLoadingState('Cargando pedidos de mesa...'));
			$('#list_pedidos_most').html(renderLoadingState('Cargando pedidos para llevar...'));
			$('#list_pedidos_del').html(renderLoadingState('Cargando pedidos delivery...'));
		} else if (PRODUCTION_STATE.currentView === 'platos') {
			$('#agrupacion_platos_list').html(renderLoadingState('Agrupando productos...'));
		} else {
			$('#agrupacion_pedidos_list').html(renderLoadingState('Agrupando pedidos...'));
		}
	}

	return fetchChannelsSnapshotPromise().then(function (responses) {
		if (requestId !== PRODUCTION_STATE.refreshRequestId) { return; }

		PRODUCTION_STATE.channels.mesa = responses[0];
		PRODUCTION_STATE.channels.mostrador = responses[1];
		PRODUCTION_STATE.channels.delivery = responses[2];
		PRODUCTION_STATE.counts = {
			mesa: responses[0].length,
			mostrador: responses[1].length,
			delivery: responses[2].length
		};

		playNotificationSoundIfNeeded(previousCounts, PRODUCTION_STATE.counts);
		PRODUCTION_STATE.lastRefreshAt = moment();
		PRODUCTION_STATE.hasLoadedOnce = true;
		updateSummary();
		renderCurrentView();
		updateLastRefreshLabel();
	}).catch(function (error) {
		console.error('Error al actualizar produccion.', error);
		if (PRODUCTION_STATE.currentView === 'lista') {
			var listError = renderEmptyState('No se pudo actualizar', 'Verifica la conexion o intenta nuevamente.');
			$('#list_pedidos_mesa').html(listError);
			$('#list_pedidos_most').html(listError);
			$('#list_pedidos_del').html(listError);
			return;
		}

		var targetSelector = PRODUCTION_STATE.currentView === 'platos' ? '#agrupacion_platos_list' : '#agrupacion_pedidos_list';
		$(targetSelector).html(renderEmptyState('No se pudo actualizar', 'Verifica la conexion o intenta nuevamente.'));
	}).then(function () {
		PRODUCTION_STATE.refreshInFlight = false;
		if (!PRODUCTION_STATE.pendingRefreshOptions) {
			return;
		}

		var pendingOptions = PRODUCTION_STATE.pendingRefreshOptions;
		PRODUCTION_STATE.pendingRefreshOptions = null;
		refreshChannelData(pendingOptions);
	});
}

function refreshCurrentView(options) {
	return refreshChannelData(options);
}

function hideLegacyTopbarButtons() {
	$('.topbar button[onclick="listarPedidos();"], .topbar button[onclick="agruparPlatos();"], .topbar button[onclick="agruparPedidos();"]').closest('li').hide();
}

function bindListTabs() {
	$('.production-list-tab').on('shown.bs.tab', function () {
		var tab = parseInt($(this).data('tab'), 10);
		PRODUCTION_STATE.currentListTab = tab;
		if (PRODUCTION_STATE.currentView === 'lista') {
			$('#tipo_atencion').val(String(tab));
			$('#tipo_atencion_opcional').val(String(tab));
		}
	});
}

function bindPusherUpdates() {
	if (typeof Pusher === 'undefined') {
		return;
	}

	var channelName = $('#pusher_channel').val();
	if (!channelName) {
		console.warn('Canal Pusher no disponible para produccion.');
		return;
	}

	var pusher = new Pusher('01c14cdca26db19318e0', { cluster: 'us2', forceTLS: true });
	var channel = pusher.subscribe(channelName);
	var refreshTimeout = null;

	function scheduleRealtimeRefresh() {
		if (refreshTimeout) {
			clearTimeout(refreshTimeout);
		}
		refreshTimeout = setTimeout(function () {
			refreshCurrentView({ showLoading: false });
		}, 350);
	}

	channel.bind('notification-mostrador', scheduleRealtimeRefresh);
	channel.bind('notification-delivery', scheduleRealtimeRefresh);
	channel.bind('new-notification', scheduleRealtimeRefresh);
	channel.bind('notification-ventaRapida', scheduleRealtimeRefresh);
	channel.bind('stock-update', scheduleRealtimeRefresh);
	channel.bind('production-refresh', scheduleRealtimeRefresh);

	pusher.connection.bind('connected', function () {
		refreshCurrentView({ showLoading: false });
	});

	pusher.connection.bind('disconnected', function () {
		console.warn('Pusher desconectado en produccion; se mantiene sincronizacion por fallback automatico.');
	});

	pusher.connection.bind('error', function (error) {
		console.error('Error en conexion realtime de produccion.', error);
	});
}

function startSafetyPolling() {
	if (PRODUCTION_STATE.safetyPollingClock) {
		clearInterval(PRODUCTION_STATE.safetyPollingClock);
	}

	PRODUCTION_STATE.safetyPollingClock = setInterval(function () {
		refreshCurrentView({ showLoading: false });
	}, 3500);

	$(window).off('.productionSync').on('online.productionSync focus.productionSync pageshow.productionSync', function () {
		refreshCurrentView({ showLoading: false });
	});

	document.addEventListener('visibilitychange', function () {
		if (!document.hidden) {
			refreshCurrentView({ showLoading: false });
		}
	});
}

function startRelativeClock() {
	if (PRODUCTION_STATE.relativeClock) { clearInterval(PRODUCTION_STATE.relativeClock); }
	PRODUCTION_STATE.relativeClock = setInterval(updateLastRefreshLabel, 30000);
}

$(function () {
	moment.locale('es');
	$('#area-p').addClass('active');
	$('.container-fluid').addClass('p-10');
	hideLegacyTopbarButtons();
	bindListTabs();
	bindPusherUpdates();
	startSafetyPolling();
	startRelativeClock();
	refreshCurrentView({ showLoading: true });
});

var listarPedidos = function () {
	PRODUCTION_STATE.currentView = 'lista';
	applyViewState();
	refreshCurrentView({ showLoading: false });
};

var agruparPlatos = function () {
	PRODUCTION_STATE.currentView = 'platos';
	applyViewState();
	refreshCurrentView({ showLoading: false });
};

var agruparPedidos = function () {
	PRODUCTION_STATE.currentView = 'pedidos';
	applyViewState();
	refreshCurrentView({ showLoading: false });
};

var nropedidosMesa = function () { return refreshCurrentView({ showLoading: false }); };
var pedidosMesa = function () { return renderListTableBody('#list_pedidos_mesa', PRODUCTION_STATE.channels.mesa, 'mesa'); };
var nropedidosMostrador = function () { return refreshCurrentView({ showLoading: false }); };
var pedidosMostrador = function () { return renderListTableBody('#list_pedidos_most', PRODUCTION_STATE.channels.mostrador, 'mostrador'); };
var nropedidosDelivery = function () { return refreshCurrentView({ showLoading: false }); };
var pedidosDelivery = function () { return renderListTableBody('#list_pedidos_del', PRODUCTION_STATE.channels.delivery, 'delivery'); };
var agrupacion_platos_list = function () { return renderGroupedProducts(); };
var agrupacion_pedidos_list = function () { return renderGroupedOrders(); };

function runProductionAction(path, payload) {
	return $.ajax({
		dataType: 'JSON',
		type: 'POST',
		url: productionUrl(path),
		data: payload
	}).done(function () {
		refreshCurrentView({ showLoading: false });
	}).fail(function (jqXHR, textStatus, errorThrown) {
		console.error('Error en accion de produccion.', errorThrown || textStatus);
	});
}

var preparacion = function (cod_ped, cod_prod, fecha_p) {
	return runProductionAction('produccion/preparacion', {
		cod_ped: cod_ped,
		cod_prod: cod_prod,
		fecha_p: fecha_p
	});
};

var atendido = function (cod_ped, cod_prod, fecha_p) {
	return runProductionAction('produccion/atendido', {
		cod_ped: cod_ped,
		cod_prod: cod_prod,
		fecha_p: fecha_p
	});
};

var atendidopormesa = function (cod_ped, id_areap) {
	var submitAction = function () {
		runProductionAction('produccion/atendidopormesa', {
			cod_ped: cod_ped,
			id_areap: id_areap
		});
	};

	if (typeof Swal === 'undefined' || typeof Swal.fire !== 'function') {
		if (window.confirm('Se marcara todo el pedido como atendido.')) {
			submitAction();
		}
		return;
	}

	Swal.fire({
		title: 'Confirmar atencion',
		text: 'Se marcara todo el pedido como atendido.',
		icon: 'question',
		showCancelButton: true,
		confirmButtonText: 'Si, continuar',
		cancelButtonText: 'Cancelar'
	}).then(function (result) {
		var confirmed = typeof result.isConfirmed !== 'undefined' ? result.isConfirmed : result.value;
		if (!confirmed) { return; }
		submitAction();
	});
};
