(function ($) {
    "use strict";
	
	var $window = $(window); 
	var $body = $('body'); 
	
	/* Preloader Effect */
	$window.on('load', function(){
		$(".preloader").fadeOut(600);
	});
	
	/* Sticky Header */	
	if($('.active-sticky-header').length){
		$window.on('resize', function(){
			setHeaderHeight();
		});

		function setHeaderHeight(){
	 		$("header.main-header").css("height", $('header .header-sticky').outerHeight());
		}	
	
		$(window).on("scroll", function() {
			var fromTop = $(window).scrollTop();
			setHeaderHeight();
			var $sticky = $("header .header-sticky");
			if ($("header.site-header").length) {
				$sticky.toggleClass("active", true).removeClass("hide");
				return;
			}
			var headerHeight = $sticky.outerHeight();
			$sticky.toggleClass("hide", (fromTop > headerHeight + 100));
			$sticky.toggleClass("active", (fromTop > 600));
		});

	}	
	
	/* Slick Menu JS (legacy #menu only — site uses partials/nav.html + navbar.js) */
	if ($('#menu').length) {
		$('#menu').slicknav({
			label : '',
			prependTo : '.responsive-menu'
		});
	}

	if($("a[href='#top']").length){
		$("a[href='#top']").click(function() {
			$("html, body").animate({ scrollTop: 0 }, "slow");
			return false;
		});
	}
	
	/* Image Coparision JS */
	if ($('.transformation_image').length) {
		$(".transformation_image").twentytwenty({
			no_overlay: true,
		});
	}

	/* Hero Slider Layout JS */
	if ($('.hero-slider-layout .swiper').length) {
		const hero_slider_layout = new Swiper('.hero-slider-layout .swiper', {
			slidesPerView : 1,
			speed: 1000,
			spaceBetween: 0,
			loop: true,
			autoplay: {
				delay: 4000,
			},
			pagination: {
				el: '.hero-pagination',
				clickable: true,
			},
		});
	}
	
	/* testimonial Slider JS */
	if ($('.testimonial-slider').length) {
		const testimonial_slider = new Swiper('.testimonial-slider .swiper', {
			slidesPerView : 1,
			speed: 1000,
			spaceBetween: 30,
			loop: true,
			autoplay: {
				delay: 5000,
			},
			pagination: {
				el: '.swiper-pagination',
				clickable: true,
			},
			navigation: {
				nextEl: '.testimonial-button-next',
				prevEl: '.testimonial-button-prev',
			},
			breakpoints: {
				768:{
				  	slidesPerView: 1,
				},
				991:{
				  	slidesPerView: 1,
				}
			}
		});
	}

	/* Service Single Image Carousel JS */
	if ($('.service-single-slider').length) {
		const service_single_slider = new Swiper('.service-single-slider .swiper', {
			slidesPerView : 1,
			speed: 1000,
			spaceBetween: 10,
			loop: true,
			autoplay: {
				delay: 5000,
			},
			pagination: {
				el: '.swiper-pagination',
				clickable: true,
			},
			navigation: {
				nextEl: '.service-single-button-next',
				prevEl: '.service-single-button-prev',
			},
		});
	}

	/* Doctor Licenses / Diplomas slider JS */
	if ($('.doctor-license-swiper').length) {
		const doctor_license_slider = new Swiper('.doctor-license-swiper .swiper', {
			// Manje slajdova po prikazu kako bi se i kod manjeg broja slika
			// slider jasno “osetio” (prev/next ima efekat).
			slidesPerView: 3,
			speed: 850,
			spaceBetween: 24,
			loop: false,
			grabCursor: true,
			// Ne blokiraj klik na thumbnail linkove (važno za lightbox).
			preventClicks: false,
			preventClicksPropagation: false,
			// Omogućava da Swiper pravilno preračuna dimenzije kad se slike/DOM menjaju.
			observer: true,
			observeParents: true,
			pagination: {
				el: '.doctor-license-pagination',
				clickable: true,
			},
			navigation: {
				nextEl: '.doctor-license-button-next',
				prevEl: '.doctor-license-button-prev',
			},
			breakpoints: {
				1200: {
					slidesPerView: 3,
				},
				991: {
					slidesPerView: 2,
				},
				768: {
					slidesPerView: 2,
				},
				576: {
					slidesPerView: 1,
				}
			}
		});
	}

	/* Skill Bar */
	if ($('.skills-progress-bar').length) {
		$('.skills-progress-bar').waypoint(function() {
			$('.skillbar').each(function() {
				$(this).find('.count-bar').animate({
				width:$(this).attr('data-percent')
				},2000);
			});
		},{
			offset: '50%'
		});
	}

	/* Youtube Background Video JS */
	if ($('#herovideo').length) {
		var myPlayer = $("#herovideo").YTPlayer();
	}

	/* Init Counter */
	if ($('.counter').length) {
		$('.counter').counterUp({ delay: 6, time: 3000 });
	}

	/* Image Reveal Animation */
	if ($('.reveal').length) {
        gsap.registerPlugin(ScrollTrigger);
        let revealContainers = document.querySelectorAll(".reveal");
        revealContainers.forEach((container) => {
            let image = container.querySelector("img");
            let tl = gsap.timeline({
                scrollTrigger: {
                    trigger: container,
                    toggleActions: "play none none none"
                }
            });
            tl.set(container, {
                autoAlpha: 1
            });
            tl.from(container, 1, {
                xPercent: -100,
                ease: Power2.out
            });
            tl.from(image, 1, {
                xPercent: 100,
                scale: 1,
                delay: -1,
                ease: Power2.out
            });
        });
    }

	/* Text Effect Animation */
	if ($('.text-anime-style-1').length) {
		let staggerAmount 	= 0.05,
			translateXValue = 0,
			delayValue 		= 0.5,
		   animatedTextElements = document.querySelectorAll('.text-anime-style-1');
		
		animatedTextElements.forEach((element) => {
			let animationSplitText = new SplitText(element, { type: "chars, words" });
				gsap.from(animationSplitText.words, {
				duration: 1,
				delay: delayValue,
				x: 20,
				autoAlpha: 0,
				stagger: staggerAmount,
				scrollTrigger: { trigger: element, start: "top 85%" },
				});
		});		
	}
	
	if ($('.text-anime-style-2').length) {				
		let	 staggerAmount 		= 0.03,
			 translateXValue	= 20,
			 delayValue 		= 0.1,
			 easeType 			= "power2.out",
			 animatedTextElements = document.querySelectorAll('.text-anime-style-2');
		
		animatedTextElements.forEach((element) => {
			let animationSplitText = new SplitText(element, { type: "chars, words" });
				gsap.from(animationSplitText.chars, {
					duration: 1,
					delay: delayValue,
					x: translateXValue,
					autoAlpha: 0,
					stagger: staggerAmount,
					ease: easeType,
					scrollTrigger: { trigger: element, start: "top 85%"},
				});
		});		
	}
	
	if ($('.text-anime-style-3').length) {		
		let	animatedTextElements = document.querySelectorAll('.text-anime-style-3');
		
		 animatedTextElements.forEach((element) => {
			//Reset if needed
			if (element.animation) {
				element.animation.progress(1).kill();
				element.split.revert();
			}

			element.split = new SplitText(element, {
				type: "lines,words,chars",
				linesClass: "split-line",
			});
			gsap.set(element, { perspective: 400 });

			gsap.set(element.split.chars, {
				opacity: 0,
				x: "50",
			});

			element.animation = gsap.to(element.split.chars, {
				scrollTrigger: {
					trigger: element,
					start: "top 90%",
					// Ako je naslov već iznad "90%" linije (hero / page-header), ScrollTrigger nikad ne okine — tekst ostane opacity: 0
					invalidateOnRefresh: true
				},
				x: "0",
				y: "0",
				rotateX: "0",
				opacity: 1,
				duration: 1,
				ease: Back.easeOut,
				stagger: 0.02,
			});
		});

		/* Odmah prikaži naslove koji su već u kadru (npr. cenovnik, unutrašnje strane page-header) */
		requestAnimationFrame(function () {
			requestAnimationFrame(function () {
				ScrollTrigger.refresh();
				animatedTextElements.forEach(function (el) {
					if (!el.animation) return;
					var rect = el.getBoundingClientRect();
					var vh = window.innerHeight || document.documentElement.clientHeight;
					if (rect.top < vh * 0.92 && rect.bottom > -24) {
						el.animation.progress(1);
					}
				});
			});
		});
	}

	/* Parallaxie js */
	var $parallaxie = $('.parallaxie');
	if($parallaxie.length && ($window.width() > 991))
	{
		if ($window.width() > 768) {
			$parallaxie.parallaxie({
				speed: 0.55,
				offset: 0,
			});
		}
	}

	/* Zoom Gallery screenshot */
	$('.gallery-items').magnificPopup({
		delegate: 'a',
		type: 'image',
		closeOnContentClick: false,
		closeBtnInside: false,
		mainClass: 'mfp-with-zoom',
		image: {
			verticalFit: true,
		},
		gallery: {
			enabled: true,
			// Omogucava "slider" ponasanje unutar lightbox-a
			navigateByImgClick: true,
			tPrev: 'Prethodna',
			tNext: 'Sledeca',
			tCounter: '%curr% od %total%'
		},
		callbacks: {
			// Ne remeti ugrađenu magnificPopup gallery navigaciju.
			open: function() {},
			close: function() {}
		},
		zoom: {
			enabled: true,
			duration: 300, // don't foget to change the duration also in CSS
			opener: function(element) {
			  return element.find('img');
			}
		}
	});

	/* Doctor licenses - lightweight lightbox (vanilla JS) */
	(function initDoctorLicensesLightbox() {
		const swiperRoot = document.querySelector('.doctor-license-swiper');
		if (!swiperRoot) return;

		const links = Array.from(swiperRoot.querySelectorAll('a.doctor-license-link'));
		if (!links.length) return;

		const modal = document.createElement('div');
		modal.className = 'doctor-licenses-lightbox';
		modal.setAttribute('aria-hidden', 'true');
		modal.innerHTML = `
			<div class="doctor-licenses-lightbox__overlay" data-close="true"></div>
			<div class="doctor-licenses-lightbox__content" role="dialog" aria-modal="true" aria-label="Diplome/Licence">
				<button type="button" class="doctor-licenses-lightbox__close" data-close="true" aria-label="Zatvori">&times;</button>
				<button type="button" class="doctor-licenses-lightbox__nav doctor-licenses-lightbox__nav--prev" data-nav="-1" aria-label="Prethodna slika">&#10094;</button>
				<img class="doctor-licenses-lightbox__img" alt="" />
				<div class="doctor-licenses-lightbox__meta"></div>
				<button type="button" class="doctor-licenses-lightbox__nav doctor-licenses-lightbox__nav--next" data-nav="1" aria-label="Sledeca slika">&#10095;</button>
			</div>
		`;

		document.body.appendChild(modal);

		const overlay = modal.querySelector('[data-close="true"]');
		const closeBtn = modal.querySelector('.doctor-licenses-lightbox__close');
		const navPrev = modal.querySelector('.doctor-licenses-lightbox__nav--prev');
		const navNext = modal.querySelector('.doctor-licenses-lightbox__nav--next');
		const img = modal.querySelector('.doctor-licenses-lightbox__img');
		const meta = modal.querySelector('.doctor-licenses-lightbox__meta');

		let currentIndex = 0;
		let lastFocus = null;

		function show(index) {
			currentIndex = index;
			const link = links[currentIndex];
			const thumbImg = link.querySelector('img');
			const src = link.getAttribute('href') || thumbImg?.getAttribute('src') || '';
			const alt = thumbImg?.getAttribute('alt') || '';

			img.src = src;
			img.alt = alt;
			meta.textContent = alt;

			modal.classList.add('is-open');
			modal.setAttribute('aria-hidden', 'false');
			document.body.style.overflow = 'hidden';
			closeBtn.focus({ preventScroll: true });
		}

		function hide() {
			modal.classList.remove('is-open');
			modal.setAttribute('aria-hidden', 'true');
			document.body.style.overflow = '';
			img.src = '';
			if (lastFocus) lastFocus.focus({ preventScroll: true });
		}

		function move(dir) {
			if (!links.length) return;
			const nextIndex = (currentIndex + dir + links.length) % links.length;
			show(nextIndex);
		}

		links.forEach((link, idx) => {
			link.addEventListener('click', (e) => {
				e.preventDefault();
				lastFocus = document.activeElement;
				show(idx);
			});
		});

		// Close
		overlay.addEventListener('click', hide);
		closeBtn.addEventListener('click', hide);

		// Navigation
		navPrev.addEventListener('click', () => move(-1));
		navNext.addEventListener('click', () => move(1));

		// Keyboard support
		document.addEventListener('keydown', (e) => {
			if (!modal.classList.contains('is-open')) return;

			if (e.key === 'Escape') hide();
			if (e.key === 'ArrowLeft') move(-1);
			if (e.key === 'ArrowRight') move(1);
		});
	})();

	/* Contact form validation */
	var $contactform = $("#contactForm");
	$contactform.validator({focus: false}).on("submit", function (event) {
		if (!event.isDefaultPrevented()) {
			event.preventDefault();
			submitForm();
		}
	});

	function submitForm(){
		/* Ajax call to submit form */
		$.ajax({
			type: "POST",
			url: "form-process.php",
			data: $contactform.serialize(),
			success : function(text){
				if (text == "success"){
					formSuccess();
				} else {
					submitMSG(false,text);
				}
			}
		});
	}

	function formSuccess(){
		$contactform[0].reset();
		submitMSG(true, "Message Sent Successfully!")
	}

	function submitMSG(valid, msg){
		if(valid){
			var msgClasses = "h3 text-success";
		} else {
			var msgClasses = "h3 text-danger";
		}
		$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
	}
	/* Contact form validation end */

	/* Appointment form validation */
	var $appointmentForm = $("#appointmentForm");
	applySerbianValidationMessages($appointmentForm);
	$appointmentForm.validator({focus: false}).on("submit", function (event) {
		if (!event.isDefaultPrevented()) {
			event.preventDefault();
			submitappointmentForm();
		}
	});

	function applySerbianValidationMessages($form) {
		if (!$form || !$form.length) return;

		$form.find("input, textarea, select").each(function () {
			var field = this;

			field.addEventListener("invalid", function () {
				field.setCustomValidity("");

				if (field.validity.valueMissing) {
					field.setCustomValidity("Ovo polje je obavezno.");
				} else if (field.validity.typeMismatch && field.type === "email") {
					field.setCustomValidity("Unesite ispravnu adresu e-pošte.");
				} else if (field.validity.patternMismatch || field.validity.tooShort) {
					field.setCustomValidity("Unesite ispravan podatak.");
				}
			});

			field.addEventListener("input", function () {
				field.setCustomValidity("");
			});
		});
	}

	function submitappointmentForm(){
		/* Ajax call to submit form */
		$.ajax({
			type: "POST",
			url: "form-appointment.php",
			data: $appointmentForm.serialize(),
			success : function(text){
				if (text == "success"){
					appointmentformSuccess();
				} else {
					appointmentsubmitMSG(false,text);
				}
			}
		});
	}

	function appointmentformSuccess(){
		$appointmentForm[0].reset();
		appointmentsubmitMSG(true, "Upit je uspešno poslat!")
	}

	function appointmentsubmitMSG(valid, msg){
		if(valid){
			var msgClasses = "h3 text-success";
		} else {
			var msgClasses = "h3 text-danger";
		}
		$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
	}
	/* Appointment form validation end */

	/* Animated Wow Js */	
	new WOW().init();
			
})(jQuery);