(function () {
	'use strict';

	var PDI = 'images/pdi/';
	var ITEM_IMAGES = {
		'jaja-na-oko': PDI + 'jaja na oko.jpg',
		'jogurt': PDI + 'jogurt.jpeg',
		'omlet-slanina': PDI + 'omlet sa sunkom.jpg',
		'omlet-sunka': PDI + 'omlet sa sunkom.jpg',
		'pita-zeljanica': PDI + 'pita zeljanica.jpeg',
		'przenice': PDI + 'przenice 3kom.jpeg',
		'bela-corba': PDI + 'bela corba.jpeg',
		'krem-corba': PDI + 'krem corba.jpg',
		'supa-rezanci': PDI + 'supa sa rezancima.jpg',
		'supa-knedle': PDI + 'supa sa knedlama.jpg',
		'backa-snicla': PDI + 'becka snicla.jpg',
		'karadordeva-pileca': PDI + 'karadjordjeva pileca snicla.jpg',
		'karadordeva-snicla': PDI + 'karadjordjeva snicla.jpg',
		'cureci-medaljoni': PDI + 'cureci panirani medaljoni punjeni.jpg',
		'panirani-oslic': PDI + 'panirani oslic.jpg',
		'piletina-narandza': PDI + 'piletina u sosu sa narandzom i medom.jpeg',
		'pohovani-file': PDI + 'pohovani pileci file.jpg',
		'pohovani-batak': PDI + 'pohovani batak.jpg',
		'pohovane-palacinke-glavno': PDI + 'pohovane punjene palacinke.jpg',
		'pohovani-sir': PDI + 'pohovani sir.jpeg',
		'cufte': PDI + 'cufte u paradajzu.jpg',
		'lazanje': PDI + 'lazanje.jpg',
		'pasulj': PDI + 'pasulj sa kobasicom.jpg',
		'mlinci': PDI + 'mlinci sa piletinom.jpg',
		'batak-njoke': PDI + 'batak u umaku sa njokama.jpg',
		'pomfrit': PDI + 'pomfrit.jpeg',
		'mexiko-krompir': PDI + 'mexiko krompir.jpg',
		'paradajz-sos': PDI + 'paradajz.jpeg',
		'riza': PDI + 'riza.jpeg',
		'spanac': PDI + 'spanac.jpeg',
		'vege-burge': PDI + 'vege burge.jpg',
		'kupus-salata': PDI + 'kupus salata.jpg',
		'cvekla': PDI + 'cvekla.jpg',
		'krastavac-salata': PDI + 'krastavac salata.jpg',
		'kiseli-kupus': PDI + 'kiseli kupus.jpeg',
		'srpska-salata': PDI + 'srpska salata.jpg',
		'shopska': PDI + 'sopska salata.jpg',
		'zemicka': PDI + 'zemicka.jpg',
		'knedle-sljive': PDI + 'knedle sa sljivama.jpg',
		'pal-jabuka': PDI + 'palacinke.jpg',
		'pal-krem': PDI + 'palacinke.jpg',
		'pal-jagoda': PDI + 'palacinke.jpg',
		'pal-kajsija': PDI + 'palacinke.jpg',
		'pan-jabuka-cimet': PDI + 'panirane palacinke.jpg',
		'pan-visnja': PDI + 'panirane palacinke.jpg',
		'pan-jabuka': PDI + 'panirane palacinke.jpg',
		'poh-palacinke': PDI + 'pohovane punjene palacinke.jpg'
	};
	var DEFAULT_IMAGE = PDI + 'palacinke.jpg';

	var DELIVERY_FEE = 150;
	var ACTIVE_PANEL = 'order-cat-dorucak';
	var isSearchActive = false;

	var MENU = [
		{
			id: 'dorucak',
			title: 'Doručak',
			items: [
				{ id: 'jaja-na-oko', name: 'Jaja na oko', desc: '3 kom. Naglasite da li meko ili tvrdo pečena.', price: 400 },
				{ id: 'jogurt', name: 'Jogurt', desc: '', price: 80 },
				{ id: 'omlet-slanina', name: 'Omlet sa slaninom', desc: 'Tri jaja i slanina.', price: 400 },
				{ id: 'omlet-sunka', name: 'Omlet sa šunkom', desc: '3 jaja i šunka.', price: 400 },
				{ id: 'pita-zeljanica', name: 'Pita zeljanica', desc: '', price: 400 },
				{ id: 'przenice', name: 'Prženice', desc: '3 kom.', price: 400, popular: true }
			]
		},
		{
			id: 'supe',
			title: 'Supe i čorbe',
			items: [
				{ id: 'bela-corba', name: 'Bela čorba', desc: '500 ml', price: 400 },
				{ id: 'krem-corba', name: 'Krem čorba', desc: '500 ml', price: 500 },
				{ id: 'supa-rezanci', name: 'Supa sa rezancima', desc: '500 ml', price: 500 },
				{ id: 'supa-knedle', name: 'Supa sa knedlama', desc: '500 ml', price: 500, popular: true }
			]
		},
		{
			id: 'glavna',
			title: 'Glavna jela',
			items: [
				{ id: 'backa-snicla', name: 'Bečka šnicla', desc: '', price: 800 },
				{ id: 'karadordeva-pileca', name: 'Karađorđeva pileća šnicla', desc: '', price: 900 },
				{ id: 'karadordeva-snicla', name: 'Karađorđeva šnicla', desc: '', price: 900 },
				{
					id: 'cureci-medaljoni',
					name: 'Ćureći panirani medaljoni punjeni',
					desc: '10% popusta na odabrane artikle obračunava se pri plaćanju.',
					price: 630,
					oldPrice: 700,
					discount: true
				},
				{ id: 'panirani-oslic', name: 'Panirani oslić', desc: '', price: 800 },
				{ id: 'piletina-narandza', name: 'Piletina u sosu sa narandžom i medom', desc: '', price: 800 },
				{ id: 'pohovani-file', name: 'Pohovani pileći file', desc: 'Pohovano pileće belo meso, pileća bečka šnicla.', price: 800 },
				{ id: 'pohovani-batak', name: 'Pohovani batak sa karabatakom', desc: 'Paniran batak sa karabatakom — sirovo 350 g.', price: 800 },
				{ id: 'pohovane-palacinke-glavno', name: 'Pohovane punjene palačinke', desc: '2 komada pečenica, sir, pavlaka.', price: 800 },
				{ id: 'pohovani-sir', name: 'Pohovani sir', desc: '', price: 700 },
				{ id: 'cufte', name: 'Ćufte u paradajz sosu', desc: '3 komada sa paradajz sosom.', price: 800 },
				{ id: 'lazanje', name: 'Lazanje', desc: '', price: 900 },
				{ id: 'pasulj', name: 'Pasulj sa kobasicom', desc: '', price: 890 },
				{ id: 'mlinci', name: 'Mlinci sa piletinom', desc: '', price: 900 },
				{ id: 'batak-njoke', name: 'Batak u umaku sa njokama', desc: '', price: 890 }
			]
		},
		{
			id: 'prilozi',
			title: 'Prilozi',
			items: [
				{ id: 'pomfrit', name: 'Pomfrit', desc: '300 g', price: 300 },
				{ id: 'mexiko-krompir', name: 'Mexiko krompir kriške', desc: '300 g', price: 300 },
				{ id: 'paradajz-sos', name: 'Paradajz sos', desc: '200 g', price: 300 },
				{ id: 'pire', name: 'Pire krompir', desc: '300 g', price: 300 },
				{ id: 'riza', name: 'Riža', desc: '300 g', price: 300, popular: true },
				{ id: 'spanac', name: 'Spanać', desc: '200 g', price: 350, popular: true },
				{ id: 'vege-burge', name: 'Vege burge', desc: '', price: 210 }
			]
		},
		{
			id: 'salata',
			title: 'Salata',
			items: [
				{ id: 'kupus-salata', name: 'Kupus salata', desc: '200 g', price: 300 },
				{ id: 'cvekla', name: 'Cvekla', desc: '200 g', price: 300, popular: true },
				{ id: 'krastavac-salata', name: 'Krastavac salata', desc: '200 g', price: 300, popular: true },
				{ id: 'kiseli-kupus', name: 'Kiseli kupus', desc: '200 g', price: 300 },
				{ id: 'srpska-salata', name: 'Srpska salata', desc: '200 g', price: 350 },
				{ id: 'shopska', name: 'Šopska salata', desc: '300 g', price: 400 }
			]
		},
		{
			id: 'hleb',
			title: 'Hleb i zemičke',
			items: [
				{ id: 'zemicka', name: 'Zemička', desc: '', price: 60 }
			]
		},
		{
			id: 'deserti',
			title: 'Deserti',
			items: [
				{ id: 'knedle-sljive', name: 'Knedle sa šljivama', desc: '5 komada', price: 400 }
			]
		},
		{
			id: 'palacinke',
			title: 'Palačinke',
			items: [
				{ id: 'pal-jabuka', name: 'Palačinke sa nadevom od jabuke', desc: '2 kom u porciji.', price: 300 },
				{ id: 'pal-krem', name: 'Palačinke sa kremom', desc: '2 kom u porciji.', price: 350 },
				{ id: 'pal-jagoda', name: 'Palačinke sa nadevom od jagode', desc: '2 kom u porciji.', price: 300 },
				{ id: 'pal-kajsija', name: 'Palačinke sa džemom od kajsija', desc: '2 kom u porciji.', price: 300 },
				{ id: 'pan-jabuka-cimet', name: 'Panirane palačinke sa nadevom od jabuke i cimeta', desc: '2 kom u porciji.', price: 500 },
				{ id: 'pan-visnja', name: 'Panirane palačinke sa nadevom od višnje', desc: '2 kom u porciji.', price: 500 },
				{ id: 'pan-jabuka', name: 'Panirane palačinke sa nadevom od jabuke', desc: '2 kom u porciji.', price: 500 },
				{ id: 'poh-palacinke', name: 'Pohovane punjene palačinke', desc: '2 kom u porciji.', price: 800 }
			]
		}
	];

	var cart = {};

	function formatPrice(amount) {
		return amount.toLocaleString('sr-RS') + ' RSD';
	}

	function getItemImage(item) {
		return ITEM_IMAGES[item.id] || DEFAULT_IMAGE;
	}

	function findItem(itemId) {
		var i, j, cat, item;
		for (i = 0; i < MENU.length; i += 1) {
			cat = MENU[i];
			for (j = 0; j < cat.items.length; j += 1) {
				item = cat.items[j];
				if (item.id === itemId) {
					return item;
				}
			}
		}
		return null;
	}

	function cartCount() {
		return Object.keys(cart).reduce(function (sum, id) {
			return sum + cart[id];
		}, 0);
	}

	function cartSubtotal() {
		var total = 0;
		Object.keys(cart).forEach(function (id) {
			var item = findItem(id);
			if (item) {
				total += item.price * cart[id];
			}
		});
		return total;
	}

	function escapeHtml(str) {
		return String(str)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');
	}

	function renderItemCard(item, options) {
		options = options || {};
		var img = options.image || getItemImage(item);
		var badges = '';
		if (item.popular) {
			badges += '<span class="order-badge order-badge-popular">Popularno</span>';
		}
		if (item.discount) {
			badges += '<span class="order-badge order-badge-sale">−10%</span>';
		}
		var priceHtml = item.oldPrice
			? '<span class="order-price-old">' + formatPrice(item.oldPrice) + '</span><span class="order-price">' + formatPrice(item.price) + '</span>'
			: '<span class="order-price">' + formatPrice(item.price) + '</span>';
		var descHtml = item.desc ? '<p class="order-item-desc">' + escapeHtml(item.desc) + '</p>' : '';
		var qty = cart[item.id] || 0;
		var addBlock = qty > 0
			? '<div class="order-qty" data-id="' + item.id + '">' +
				'<button type="button" class="order-qty-btn" data-action="minus" aria-label="Smanji">−</button>' +
				'<span class="order-qty-val">' + qty + '</span>' +
				'<button type="button" class="order-qty-btn" data-action="plus" aria-label="Povećaj">+</button>' +
				'</div>'
			: '<button type="button" class="order-add-btn" data-id="' + item.id + '" aria-label="Dodaj u korpu">+</button>';
		return (
			'<article class="order-item" data-item-id="' + item.id + '">' +
				'<div class="order-item-img"><img src="' + img + '" alt="' + escapeHtml(item.name) + '" loading="lazy"></div>' +
				'<div class="order-item-info">' +
					(badges ? '<div class="order-item-badges">' + badges + '</div>' : '') +
					'<h4 class="order-item-name">' + escapeHtml(item.name) + '</h4>' +
					descHtml +
					'<div class="order-item-footer">' +
						'<div class="order-item-prices">' + priceHtml + '</div>' +
						addBlock +
					'</div>' +
				'</div>' +
			'</article>'
		);
	}

	function renderCategories() {
		var nav = document.getElementById('order-cat-nav');
		if (!nav) {
			return;
		}
		nav.innerHTML = MENU.map(function (cat) {
			return '<button type="button" class="order-cat-btn" data-target="order-cat-' + cat.id + '">' + escapeHtml(cat.title) + '</button>';
		}).join('');
	}

	function renderMenuSections() {
		var wrap = document.getElementById('order-menu-sections');
		if (!wrap) {
			return;
		}

		var categoriesHtml = MENU.map(function (cat) {
			var itemsHtml = cat.items.map(function (item) {
				return renderItemCard(item);
			}).join('');

			return (
				'<section class="order-category order-panel-hidden" id="order-cat-' + cat.id + '" data-panel="order-cat-' + cat.id + '">' +
					'<div class="order-category-head">' +
						'<h3 class="order-category-title">' + escapeHtml(cat.title) + '</h3>' +
						'<p class="order-category-count">' + cat.items.length + ' stavki</p>' +
					'</div>' +
					'<div class="order-items-list">' + itemsHtml + '</div>' +
				'</section>'
			);
		}).join('');

		wrap.innerHTML = categoriesHtml;

		applyPanelVisibility();
	}

	function applyPanelVisibility() {
		var wrap = document.getElementById('order-menu-sections');
		if (!wrap) {
			return;
		}

		if (isSearchActive) {
			wrap.querySelectorAll('.order-category').forEach(function (section) {
				var hasVisible = section.querySelector('.order-item:not(.order-item-hidden)');
				section.classList.toggle('order-panel-hidden', !hasVisible);
			});
			return;
		}

		wrap.querySelectorAll('.order-category').forEach(function (section) {
			var panelId = section.getAttribute('data-panel');
			section.classList.toggle('order-panel-hidden', panelId !== ACTIVE_PANEL);
		});

		document.querySelectorAll('.order-cat-btn').forEach(function (btn) {
			var isActive = btn.getAttribute('data-target') === ACTIVE_PANEL;
			btn.classList.toggle('active', isActive);
			if (isActive && isMobileCart()) {
				btn.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
			}
		});
	}

	function setActivePanel(panelId) {
		ACTIVE_PANEL = panelId;
		isSearchActive = false;
		var search = document.getElementById('order-search');
		if (search) {
			search.value = '';
		}
		var app = document.getElementById('order-menu-app');
		if (app) {
			app.querySelectorAll('.order-item').forEach(function (el) {
				el.classList.remove('order-item-hidden');
			});
		}
		applyPanelVisibility();
		var wrap = document.getElementById('order-menu-sections');
		if (wrap) {
			wrap.scrollIntoView({ behavior: 'smooth', block: 'start' });
		}
	}

	function renderCart() {
		var list = document.getElementById('order-cart-list');
		var empty = document.getElementById('order-cart-empty');
		var footer = document.getElementById('order-cart-footer');
		var count = cartCount();
		var subtotal = cartSubtotal();
		var total = subtotal + (count > 0 ? DELIVERY_FEE : 0);

		if (!list) {
			return;
		}

		if (count === 0) {
			list.innerHTML = '';
			if (empty) {
				empty.hidden = false;
			}
			if (footer) {
				footer.hidden = true;
			}
		} else {
			if (empty) {
				empty.hidden = true;
			}
			if (footer) {
				footer.hidden = false;
			}
			list.innerHTML = Object.keys(cart).map(function (id) {
				var item = findItem(id);
				if (!item) {
					return '';
				}
				var qty = cart[id];
				return (
					'<div class="order-cart-line" data-id="' + id + '">' +
						'<div class="order-cart-line-info">' +
							'<span class="order-cart-line-name">' + escapeHtml(item.name) + '</span>' +
							'<span class="order-cart-line-price">' + formatPrice(item.price * qty) + '</span>' +
						'</div>' +
						'<div class="order-qty order-qty-sm" data-id="' + id + '">' +
							'<button type="button" class="order-qty-btn" data-action="minus">−</button>' +
							'<span class="order-qty-val">' + qty + '</span>' +
							'<button type="button" class="order-qty-btn" data-action="plus">+</button>' +
						'</div>' +
					'</div>'
				);
			}).join('');
		}

		var subEl = document.getElementById('order-cart-subtotal');
		var delEl = document.getElementById('order-cart-delivery');
		var totEl = document.getElementById('order-cart-total');
		var mobCount = document.getElementById('order-mobile-count');
		var mobTotal = document.getElementById('order-mobile-total');

		if (subEl) {
			subEl.textContent = formatPrice(subtotal);
		}
		if (delEl) {
			delEl.textContent = count > 0 ? formatPrice(DELIVERY_FEE) : '—';
		}
		if (totEl) {
			totEl.textContent = formatPrice(total);
		}
		if (mobCount) {
			mobCount.textContent = count;
			mobCount.hidden = count === 0;
		}
		if (mobTotal) {
			mobTotal.textContent = formatPrice(total);
		}
	}

	function updateQty(itemId, delta) {
		var next = (cart[itemId] || 0) + delta;
		if (next <= 0) {
			delete cart[itemId];
		} else {
			cart[itemId] = next;
		}
		renderMenuSections();
		renderCart();
	}

	var cartLayoutParent = null;
	var cartLayoutMain = null;

	function isMobileCart() {
		return window.matchMedia('(max-width: 991px)').matches;
	}

	function initCartLayoutRefs() {
		cartLayoutParent = document.querySelector('#menu-section .order-layout');
		cartLayoutMain = cartLayoutParent && cartLayoutParent.querySelector('.order-main');
	}

	function closeCartSheet() {
		var cartPanel = document.getElementById('order-cart-panel');
		if (cartPanel) {
			cartPanel.classList.remove('order-cart-open');
		}
		document.body.classList.remove('order-cart-sheet-open');
	}

	function openCartSheet() {
		var cartPanel = document.getElementById('order-cart-panel');
		if (!cartPanel) {
			return;
		}
		setupCartPortal();
		cartPanel.classList.add('order-cart-open');
		document.body.classList.add('order-cart-sheet-open');
	}

	function setupCartPortal() {
		var cartPanel = document.getElementById('order-cart-panel');
		var mobileBar = document.getElementById('order-mobile-bar');
		var app = document.getElementById('order-menu-app');
		if (!cartPanel || !cartLayoutParent || !cartLayoutMain) {
			return;
		}
		if (isMobileCart()) {
			document.body.appendChild(cartPanel);
			if (mobileBar) {
				document.body.appendChild(mobileBar);
			}
		} else {
			cartLayoutMain.insertAdjacentElement('afterend', cartPanel);
			closeCartSheet();
			if (mobileBar && app) {
				app.appendChild(mobileBar);
			}
		}
	}

	function bindEvents() {
		var app = document.getElementById('order-menu-app');
		if (!app) {
			return;
		}

		app.addEventListener('click', function (e) {
			var addBtn = e.target.closest('.order-add-btn');
			if (addBtn) {
				updateQty(addBtn.getAttribute('data-id'), 1);
				return;
			}

			var qtyBtn = e.target.closest('.order-qty-btn');
			if (qtyBtn) {
				var wrap = qtyBtn.closest('[data-id]');
				if (!wrap) {
					return;
				}
				var id = wrap.getAttribute('data-id');
				updateQty(id, qtyBtn.getAttribute('data-action') === 'plus' ? 1 : -1);
				return;
			}

			var catBtn = e.target.closest('.order-cat-btn');
			if (catBtn) {
				var target = catBtn.getAttribute('data-target');
				if (target) {
					setActivePanel(target);
				}
			}
		});

		var search = document.getElementById('order-search');
		if (search) {
			search.addEventListener('input', function () {
				var q = search.value.trim().toLowerCase();
				isSearchActive = !!q;

				app.querySelectorAll('.order-item').forEach(function (el) {
					var name = (el.querySelector('.order-item-name') || {}).textContent || '';
					var desc = (el.querySelector('.order-item-desc') || {}).textContent || '';
					var cat = (el.querySelector('.order-item-cat') || {}).textContent || '';
					var match = !q || (name + ' ' + desc + ' ' + cat).toLowerCase().indexOf(q) !== -1;
					el.classList.toggle('order-item-hidden', !match);
				});

				if (isSearchActive) {
					document.querySelectorAll('.order-cat-btn').forEach(function (btn) {
						btn.classList.remove('active');
					});
				}

				applyPanelVisibility();
			});
		}

		var mobileBar = document.getElementById('order-mobile-bar');
		var cartPanel = document.getElementById('order-cart-panel');
		var backdrop = document.getElementById('order-cart-backdrop');

		if (mobileBar && cartPanel) {
			mobileBar.addEventListener('click', function () {
				if (cartPanel.classList.contains('order-cart-open')) {
					closeCartSheet();
				} else {
					openCartSheet();
				}
			});
		}

		var closeCart = document.getElementById('order-cart-close');
		if (closeCart) {
			closeCart.addEventListener('click', closeCartSheet);
		}

		if (backdrop) {
			backdrop.addEventListener('click', closeCartSheet);
		}

		window.addEventListener('resize', setupCartPortal);
	}

	function init() {
		renderCategories();
		renderMenuSections();
		renderCart();
		initCartLayoutRefs();
		setupCartPortal();
		bindEvents();
		applyPanelVisibility();
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
