(function () {
	'use strict';

	/* Isti sadržaj kao partials/nav.html — koristi se kad fetch ne radi (file://, mreža, 404). */
	var NAV_HTML_EMBEDDED =
		'<div class="header-sticky">' +
		'<nav class="navbar navbar-expand-lg site-navbar" aria-label="Glavna navigacija">' +
		'<div class="container">' +
		'<div class="site-nav-left">' +
		'<button type="button" class="site-nav-toggle" aria-expanded="false" aria-controls="siteNavDrawer" aria-label="Otvori ili zatvori meni">' +
		'<span class="site-nav-toggle-bars" aria-hidden="true"><span></span><span></span><span></span></span>' +
		'</button>' +
		'<span class="site-nav-left-label" aria-hidden="true">Menu</span>' +
		'</div>' +
		'<a class="navbar-brand site-nav-brand" href="index.html" aria-label="Početna">' +
		'<img src="images/kucasluhalogo.png" alt="Kuća sluha">' +
		'</a>' +
		'<div class="site-nav-right">' +
		'<a href="tel:+381113441059" class="site-nav-phone" data-phone-fixed="+381113441059" data-phone-mobile="+381649935455" aria-label="Pozovite: izaberite broj telefona"><i class="fa-solid fa-phone" aria-hidden="true"></i></a>' +
		'<a class="btn-default site-nav-desktop-cta" href="index.html#appointmentForm" aria-label="Zakažite termin — idite na kontakt formu">Zakažite termin</a>' +
		'</div>' +
		'<div class="navbar-collapse main-menu site-nav-drawer" id="siteNavDrawer">' +
		'<button type="button" class="site-nav-close" aria-label="Zatvori meni"></button>' +
		'<a class="site-drawer-brand" href="index.html" aria-label="Početna">' +
		'<img src="images/kucasluhalogo.png" alt="Kuća sluha">' +
		'</a>' +
		'<div class="nav-menu-wrapper">' +
		'<ul class="navbar-nav mr-auto site-drawer-menu" id="site-menu" role="menubar">' +
		'<li class="nav-item nav-item-title" role="none"><a class="nav-link nav-link-title nav-link-title-primary" href="index.html" data-nav-key="index" role="menuitem">Početna</a></li>' +
		'<li class="nav-item nav-item-title" role="none"><a class="nav-link nav-link-title nav-link-title-primary" href="index.html#vrste-aparata" data-nav-key="vrste-aparata" role="menuitem">Slušni aparati</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="index.html#tekst" role="menuitem">Vrste slušnih aparata</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="nevidljivi-slusni-aparati.html" role="menuitem">Nevidljivi slušni aparati</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="slusni-aparati.html" role="menuitem">Slušni aparati cene</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="g8.html#onama" data-nav-key="g8" role="menuitem">G8 platforma</a></li>' +
		'<li class="nav-item nav-item-title" role="none"><a class="nav-link nav-link-title" href="javascript:void(0)" role="menuitem">Sluh</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="kako-funkcionise-sluh.html" role="menuitem">Kako funkcioniše sluh</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="gubitak-sluha.html" role="menuitem">Gubitak sluha</a></li>' +
		'<li class="nav-item nav-item-sub" role="none"><a class="nav-link nav-link-sub" href="merenje-sluha.html" role="menuitem">Merenje sluha</a></li>' +
		'<li class="nav-item nav-item-title" role="none"><a class="nav-link nav-link-title" href="index.html" data-nav-key="kontakt" role="menuitem">Kontakt</a></li>' +
		'</ul></div>' +
		'<a class="btn-default site-nav-cta" href="index.html" aria-label="Zakažite pregled sluha — idite na formu">Zakaži pregled</a>' +
		'</div></div></nav>' +
		'<div class="site-nav-backdrop" id="siteNavBackdrop" hidden aria-hidden="true"></div>' +
		'<a class="btn-default site-nav-mobile-fab" href="index.html#appointmentForm" aria-label="Zakažite termin — idite na kontakt formu">Zakažite termin</a></div>';

	var mount = document.getElementById('nav-mount');
	if (!mount) return;

	var header = mount.closest('header.site-header');
	var partialUrl = new URL('partials/nav.html', window.location.href).href;
	var navResizeBound = false;

	function currentPageFile() {
		var fromHtml = document.documentElement.getAttribute('data-current-page');
		if (fromHtml === 'index') return 'index.html';
		if (fromHtml) return fromHtml + '.html';
		var p = (window.location.pathname || '').split('/').pop() || '';
		if (!p || p.toLowerCase() === 'index.html') return 'index.html';
		return p;
	}

	function markActive() {
		var menu = document.getElementById('site-menu');
		if (!menu) return;
		var file = currentPageFile().replace(/^\.\//, '').split('#')[0].toLowerCase();

		menu.querySelectorAll('.nav-link').forEach(function (a) {
			a.classList.remove('active');
			a.removeAttribute('aria-current');
		});

		var setCurrent = true;
		menu.querySelectorAll('.nav-link[href]').forEach(function (a) {
			var href = (a.getAttribute('href') || '').trim();
			if (href.indexOf('#') === 0) return;
			var part = href.split('/').pop();
			if (!part) return;
			var f = part.split('#')[0].toLowerCase();
			if (f === file) {
				a.classList.add('active');
				if (setCurrent) {
					a.setAttribute('aria-current', 'page');
					setCurrent = false;
				}
			}
		});
	}

	function syncHeaderHeight() {
		var hs = document.querySelector('header.main-header .header-sticky');
		var mh = document.querySelector('header.main-header');
		if (hs && mh && window.jQuery) {
			window.jQuery(mh).css('height', window.jQuery(hs).outerHeight());
		}
	}

	function closeNav() {
		if (!header) return;
		header.classList.remove('nav-open');
		var btn = header.querySelector('.site-nav-toggle');
		if (btn) {
			btn.setAttribute('aria-expanded', 'false');
		}
		var bd = document.getElementById('siteNavBackdrop');
		if (bd) {
			bd.classList.remove('is-visible');
			bd.setAttribute('hidden', '');
			bd.setAttribute('aria-hidden', 'true');
		}
		document.body.style.overflow = '';
		header.querySelectorAll('li.submenu.is-open').forEach(function (li) {
			li.classList.remove('is-open');
			var t = li.querySelector('.submenu-toggle');
			if (t) t.setAttribute('aria-expanded', 'false');
		});
	}

	function openNav() {
		if (!header) return;
		header.classList.add('nav-open');
		var btn = header.querySelector('.site-nav-toggle');
		if (btn) {
			btn.setAttribute('aria-expanded', 'true');
		}
		var bd = document.getElementById('siteNavBackdrop');
		if (bd) {
			bd.removeAttribute('hidden');
			bd.classList.add('is-visible');
			bd.setAttribute('aria-hidden', 'false');
		}
		document.body.style.overflow = 'hidden';
	}

	function toggleNav() {
		if (!header) return;
		if (header.classList.contains('nav-open')) closeNav();
		else openNav();
	}

	function initMobileSubmenus(root) {
		root.querySelectorAll('li.submenu').forEach(function (li) {
			var toggle = li.querySelector('.submenu-toggle');
			var panel = li.querySelector('.submenu-panel');
			var headingLink = li.querySelector('.submenu-heading .nav-link');
			if (!toggle || !panel) return;
			toggle.setAttribute('tabindex', '0');
			function setOpen(open) {
				li.classList.toggle('is-open', open);
				toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
			}
			toggle.addEventListener('click', function (e) {
				e.preventDefault();
				e.stopPropagation();
				setOpen(!li.classList.contains('is-open'));
			});
			toggle.addEventListener('keydown', function (e) {
				if (e.key === 'Enter' || e.key === ' ') {
					e.preventDefault();
					setOpen(!li.classList.contains('is-open'));
				}
			});
			if (headingLink) {
				headingLink.addEventListener('click', function (e) {
					if (!window.matchMedia('(max-width: 991px)').matches) return;
					e.preventDefault();
					e.stopPropagation();
					setOpen(!li.classList.contains('is-open'));
				});
			}
		});
	}

	function bindPhoneChoice(root) {
		var phoneTrigger = root.querySelector('.site-nav-phone');
		if (!phoneTrigger) return;

		var fixedNumber = phoneTrigger.getAttribute('data-phone-fixed') || '+381113441059';
		var mobileNumber = phoneTrigger.getAttribute('data-phone-mobile') || '+381649935455';
		var dropdown = null;
		var isOpen = false;
		var escHandler = null;
		var outsideClickHandler = null;
		var repositionHandler = null;

		function formatDisplayNumber(value) {
			var normalized = String(value || '').replace(/\s+/g, '');
			if (normalized === '+381113441059') return '011 344 10 59';
			if (normalized === '+381649935455') return '064 993 54 55';
			return value;
		}

		function setDropdownPosition() {
			if (!dropdown) return;
			var rect = phoneTrigger.getBoundingClientRect();
			var panelWidth = 304;
			var margin = 12;
			var top = rect.bottom + 10;
			var left = rect.right - panelWidth;

			if (left < margin) left = margin;
			if (left + panelWidth > window.innerWidth - margin) {
				left = window.innerWidth - panelWidth - margin;
			}

			dropdown.style.top = top + 'px';
			dropdown.style.left = left + 'px';
		}

		function closeDropdown() {
			if (!dropdown || !isOpen) return;

			isOpen = false;
			phoneTrigger.setAttribute('aria-expanded', 'false');
			dropdown.classList.remove('is-open');

			window.setTimeout(function () {
				if (!dropdown) return;
				dropdown.remove();
				dropdown = null;
			}, 190);

			if (outsideClickHandler) {
				document.removeEventListener('click', outsideClickHandler, true);
				outsideClickHandler = null;
			}
			if (escHandler) {
				document.removeEventListener('keydown', escHandler, true);
				escHandler = null;
			}
			if (repositionHandler) {
				window.removeEventListener('resize', repositionHandler);
				window.removeEventListener('scroll', repositionHandler, true);
				repositionHandler = null;
			}
		}

		function openDropdown() {
			if (isOpen) return;
			isOpen = true;
			phoneTrigger.setAttribute('aria-expanded', 'true');

			dropdown = document.createElement('div');
			dropdown.className = 'phone-choice-dropdown';
			dropdown.setAttribute('role', 'dialog');
			dropdown.setAttribute('aria-label', 'Kontakt telefoni');
			dropdown.innerHTML =
				'<a class="phone-choice-row phone-choice-row--fixed" href="tel:' + fixedNumber + '">' +
				'<span class="phone-choice-row__icon" aria-hidden="true"><i class="fa-solid fa-phone"></i></span>' +
				'<span class="phone-choice-row__text">' +
				'<span class="phone-choice-row__label">Fiksni</span>' +
				'<span class="phone-choice-row__number">' + formatDisplayNumber(fixedNumber) + '</span>' +
				'</span>' +
				'</a>' +
				'<a class="phone-choice-row phone-choice-row--mobile" href="tel:' + mobileNumber + '">' +
				'<span class="phone-choice-row__icon" aria-hidden="true"><i class="fa-solid fa-mobile-screen-button"></i></span>' +
				'<span class="phone-choice-row__text">' +
				'<span class="phone-choice-row__label">Mobilni</span>' +
				'<span class="phone-choice-row__number">' + formatDisplayNumber(mobileNumber) + '</span>' +
				'</span>' +
				'</a>';

			document.body.appendChild(dropdown);
			setDropdownPosition();
			window.requestAnimationFrame(function () {
				if (dropdown) dropdown.classList.add('is-open');
			});

			outsideClickHandler = function (evt) {
				if (!dropdown) return;
				var clickedPhoneTrigger = evt.target.closest('.site-nav-phone');
				if (clickedPhoneTrigger === phoneTrigger) return;
				if (!dropdown.contains(evt.target)) closeDropdown();
			};

			escHandler = function (evt) {
				if (evt.key === 'Escape') {
					closeDropdown();
					phoneTrigger.focus();
				}
			};

			repositionHandler = function () {
				if (!dropdown) return;
				setDropdownPosition();
			};

			document.addEventListener('click', outsideClickHandler, true);
			document.addEventListener('keydown', escHandler, true);
			window.addEventListener('resize', repositionHandler);
			window.addEventListener('scroll', repositionHandler, true);

			dropdown.querySelectorAll('.phone-choice-row').forEach(function (link) {
				link.addEventListener('click', function () {
					closeDropdown();
				});
			});
		}

		phoneTrigger.addEventListener('click', function (e) {
			e.preventDefault();
			e.stopPropagation();
			if (isOpen) {
				closeDropdown();
			} else {
				openDropdown();
			}
		});

		phoneTrigger.setAttribute('aria-haspopup', 'dialog');
		phoneTrigger.setAttribute('aria-expanded', 'false');
	}

	function bindNavInteractions(root) {
		var toggle = root.querySelector('.site-nav-toggle');
		var closeBtn = root.querySelector('.site-nav-close');
		var backdrop = root.querySelector('#siteNavBackdrop');
		var drawer = root.querySelector('#siteNavDrawer');
		if (toggle) {
			toggle.addEventListener('click', toggleNav);
		}
		if (closeBtn) {
			closeBtn.addEventListener('click', closeNav);
		}
		if (backdrop) {
			backdrop.addEventListener('click', closeNav);
		}

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

		function trySmoothScrollFromLink(a) {
			if (!a) return false;
			var hrefRaw = (a.getAttribute('href') || '').trim();
			if (!hrefRaw || hrefRaw === '#') return false;

			// Support "#id" and "index.html#id" when we are on index.html
			var hashIndex = hrefRaw.indexOf('#');
			if (hashIndex < 0) return false;

			var hash = hrefRaw.slice(hashIndex);
			if (!hash || hash === '#') return false;

			var beforeHash = hrefRaw.slice(0, hashIndex);
			var page = currentPageFile().split('#')[0].toLowerCase();
			var before = (beforeHash || '').split('/').pop().toLowerCase();
			if (before && before !== page) return false;

			var target = document.querySelector(hash);
			if (!target) return false;

			var hs = document.querySelector('.site-header .header-sticky');
			var offset = hs ? hs.offsetHeight : 80;
			var top = target.getBoundingClientRect().top + window.pageYOffset - offset - 8;
			window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
			return true;
		}

		// Also support clicking the <li> area (not just the <a>) and enable smooth scroll for "index.html#..."
		if (drawer) {
			drawer.addEventListener('click', function (e) {
				var a = e.target.closest('a[href]');
				if (!a) {
					var li = e.target.closest('li.nav-item');
					if (li) a = li.querySelector('a[href]');
				}
				if (!a) return;
				if (a.closest('.submenu-heading')) return;

				if (trySmoothScrollFromLink(a)) {
					e.preventDefault();
					if (isMobileNav()) closeNav();
					return;
				}

				// Close only when the click actually targets a page/section link.
				var hrefRaw = (a.getAttribute('href') || '').trim().toLowerCase();
				var isRealNavTarget = hrefRaw && hrefRaw !== '#' && hrefRaw.indexOf('javascript:') !== 0;
				if (isMobileNav() && isRealNavTarget) closeNav();
			});
		}

		document.addEventListener('keydown', function (e) {
			if (e.key === 'Escape' && header && header.classList.contains('nav-open')) {
				closeNav();
				if (toggle) toggle.focus();
			}
		});
		initMobileSubmenus(root);
		bindPhoneChoice(root);
	}

	function pinMobileFab(root) {
		var fab = root.querySelector('.site-nav-mobile-fab');
		if (!fab) return;

		// Keep a single pinned FAB instance in the document body so scroll/sticky
		// header state changes can never push it back into navbar layout flow.
		var existingPinned = document.querySelector('body > .site-nav-mobile-fab');
		if (existingPinned && existingPinned !== fab) {
			existingPinned.remove();
		}

		if (fab.parentElement !== document.body) {
			document.body.appendChild(fab);
		}
	}

	function delegateSmoothScroll() {
		document.addEventListener('click', function (e) {
			var a = e.target.closest('a[href^="#"]');
			if (!a) return;
			var href = a.getAttribute('href');
			if (!href || href === '#') return;
			var target = document.querySelector(href);
			if (!target) return;
			e.preventDefault();
			var hs = document.querySelector('.site-header .header-sticky');
			var offset = hs ? hs.offsetHeight : 80;
			var top = target.getBoundingClientRect().top + window.pageYOffset - offset - 8;
			window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
			if (header && header.classList.contains('nav-open')) closeNav();
		});
	}

	function applyNavHtml(html) {
		if (!html || !String(html).trim()) {
			html = NAV_HTML_EMBEDDED;
		}
		mount.innerHTML = html;
		pinMobileFab(mount);
		markActive();
		bindNavInteractions(mount);
		syncHeaderHeight();
		if (!navResizeBound) {
			navResizeBound = true;
			window.addEventListener('resize', syncHeaderHeight);
		}
	}

	function loadNavViaFetch() {
		var ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
		var to = ctrl
			? setTimeout(function () {
					try {
						ctrl.abort();
					} catch (e) {}
			  }, 4000)
			: 0;

		var opts = { credentials: 'same-origin' };
		if (ctrl) opts.signal = ctrl.signal;

		fetch(partialUrl, opts)
			.then(function (r) {
				if (to) clearTimeout(to);
				if (!r.ok) throw new Error('Nav partial failed');
				return r.text();
			})
			.then(function (html) {
				if (!html || !String(html).trim()) throw new Error('Empty nav');
				applyNavHtml(html);
			})
			.catch(function () {
				if (to) clearTimeout(to);
				applyNavHtml(NAV_HTML_EMBEDDED);
			});
	}

	/* file:// i neki pregledači ne dozvoljavaju fetch ka lokalnom partialu — odmah ugrađeni meni */
	if (window.location.protocol === 'file:') {
		applyNavHtml(NAV_HTML_EMBEDDED);
	} else if (typeof fetch !== 'function') {
		applyNavHtml(NAV_HTML_EMBEDDED);
	} else {
		loadNavViaFetch();
	}

	delegateSmoothScroll();
})();
