(function( $ ) {
	'use strict';
    //TODO: organize this file better, it is getting a bit messy
	//written without jquery because it was being funny in public pages
	// Ensure YouTube Iframe API is loaded once and reusable
	function ats_ensureYouTubeAPI() {
		if (window._atsYouTubeAPIPromise) {
			return window._atsYouTubeAPIPromise;
		}

		window._atsYouTubeAPIPromise = new Promise(function(resolve) {
			if (window.YT && window.YT.Player) {
				return resolve(window.YT);
			}

			// Create global ready callback if not present
			var previousOnYouTubeIframeAPIReady = window.onYouTubeIframeAPIReady;
			window.onYouTubeIframeAPIReady = function() {
				if (typeof previousOnYouTubeIframeAPIReady === 'function') {
					try { previousOnYouTubeIframeAPIReady(); } catch (e) {}
				}
				resolve(window.YT);
			};

			// Inject script only once
			if (!document.querySelector('script[src*="youtube.com/iframe_api"]')) {
				var tag = document.createElement('script');
				tag.src = 'https://www.youtube.com/iframe_api';
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
			}
		});

		return window._atsYouTubeAPIPromise;
	}

	// Ensure iframe has enablejsapi=1 (required for control)
	function ats_enableJsApiOnIframe(iframe) {
		try {
			var src = iframe.getAttribute('src') || '';
			if (!src) return;
			
			// Add enablejsapi=1 if not present
			var hasParam = /[?&]enablejsapi=1(?!\d)/.test(src);
			if (!hasParam) {
				var joiner = src.indexOf('?') === -1 ? '?' : '&';
				src = src + joiner + 'enablejsapi=1';
				iframe.setAttribute('src', src);
			}
			
			// Add origin parameter to fix postMessage errors
			var currentOrigin = window.location.origin;
			var hasOrigin = /[?&]origin=/.test(iframe.getAttribute('src') || '');
			if (!hasOrigin) {
				var srcWithOrigin = iframe.getAttribute('src');
				var joiner2 = srcWithOrigin.indexOf('?') === -1 ? '?' : '&';
				iframe.setAttribute('src', srcWithOrigin + joiner2 + 'origin=' + encodeURIComponent(currentOrigin));
			}
		} catch (e) {}
	}

    function ats_openTab(evt, eventID) {
        var i, tabcontent, tablinks;
        tabcontent = document.getElementsByClassName("ats-tab-content");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }
        tablinks = document.getElementsByClassName("tab-btn");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }
        document.getElementById(eventID).style.display = "block";
        evt.currentTarget.className += " active";
    }

	window.ats_openTab = ats_openTab;

    // Event delegation for tab buttons - works regardless of when content is loaded
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('tab-btn')) {
            var tabId = e.target.getAttribute('data-tab-id');
            if (tabId) {
                // Create a synthetic event object that ats_openTab expects
                var syntheticEvent = {
                    currentTarget: e.target
                };
                ats_openTab(syntheticEvent, tabId);
            }
        }
    });

    function ats_initializeCarousels() {
        // Handle multiple carousels on the same page
        document.querySelectorAll(".carousel-container").forEach(container => {
            let carousel = container.querySelector(".carousel");
            let items = carousel.querySelectorAll(".item");
            let dotsContainer = container.querySelector(".dots");
            let prevBtn = container.querySelector(".prev");
            let nextBtn = container.querySelector(".next");

            // Skip if no items
            if (items.length === 0) return;

            // Insert dots into the DOM
            items.forEach((_, index) => {
                let dot = document.createElement("span");
                dot.classList.add("dot");
                if (index === 0) dot.classList.add("active");
                dot.dataset.index = index;
                if (dotsContainer) {
                    dotsContainer.appendChild(dot);
                }
            });

            let dots = container.querySelectorAll(".dot");

            // Function to show a specific item
            function showItem(index) {
                items.forEach((item, idx) => {
                    item.classList.remove("active");
                    dots[idx].classList.remove("active");
                    if (idx === index) {
                        item.classList.add("active");
                        dots[idx].classList.add("active");
                    }
                });
            }

            if (prevBtn) {
                // Event listeners for buttons
                prevBtn.addEventListener("click", () => {
                    let index = [...items].findIndex((item) =>
                        item.classList.contains("active")
                    );
                    showItem((index - 1 + items.length) % items.length);
                    resetAutoPlayOnInteraction();
                });
            }
            
            if (nextBtn) {
                nextBtn.addEventListener("click", () => {
                    let index = [...items].findIndex((item) =>
                        item.classList.contains("active")
                    );
                    showItem((index + 1) % items.length);
                    resetAutoPlayOnInteraction();
                });
            }
            
            if (dots) {
                // Event listeners for dots
                dots.forEach((dot) => {
                    dot.addEventListener("click", () => {
                        let index = parseInt(dot.dataset.index);
                        showItem(index);
                        resetAutoPlayOnInteraction();
                    });
                });
            }
            

            const autoScroll = container.dataset.autoScroll === 'true';
            const autoScrollInterval = parseInt(container.dataset.autoScrollInterval) || 5000;
            const pauseOnHover = container.dataset.pauseOnHover !== 'false';

            let autoPlayTimer;
            let isAutoPlaying = false;

            function startAutoPlay() {
                if (!autoScroll || items.length <= 1) return;

                stopAutoPlay(); // Clear any existing timer
                isAutoPlaying = true;

                autoPlayTimer = setInterval(() => {
                    let index = [...items].findIndex((item) =>
                        item.classList.contains("active")
                    );
                    showItem((index + 1) % items.length);
                }, autoScrollInterval);
            }

            function stopAutoPlay() {
                if (autoPlayTimer) {
                    clearInterval(autoPlayTimer);
                    autoPlayTimer = null;
                }
                isAutoPlaying = false;
            }

            function resetAutoPlay() {
                if (autoScroll) {
                    stopAutoPlay();
                    startAutoPlay();
                }
            }

            // Start auto-play if enabled
            if (autoScroll) {
                startAutoPlay();
            }

            // Pause/resume on hover if enabled
            const hoverTarget = carousel || container;
            if (pauseOnHover && autoScroll) {
				hoverTarget.addEventListener('pointerenter', stopAutoPlay);
				hoverTarget.addEventListener('pointerleave', () => {
                    if (autoScroll) startAutoPlay();
                });
            }

            // Reset auto-play timer when user interacts with controls
            const resetAutoPlayOnInteraction = () => {
                if (autoScroll) {
                    resetAutoPlay();
                }
            };

			// Stop autoplay when a YouTube video inside this carousel plays; resume on pause/end
			const youtubeIframes = container.querySelectorAll('iframe[src*="youtube.com"], iframe[src*="youtube-nocookie.com"], iframe[src*="youtu.be"]');
			if (youtubeIframes.length) {
				// Prepare iframes for JS API
				youtubeIframes.forEach(function(iframe){ ats_enableJsApiOnIframe(iframe); });

				ats_ensureYouTubeAPI().then(function(YT){
					youtubeIframes.forEach(function(iframe){
						if (iframe.dataset.atsYtBound === '1') return;
						try {
							/* eslint-disable no-new */
							new YT.Player(iframe, {
								events: {
									onStateChange: function(e) {
										if (e && e.data === YT.PlayerState.PLAYING) {
											stopAutoPlay();
										} else if (e && (e.data === YT.PlayerState.PAUSED || e.data === YT.PlayerState.ENDED)) {
											if (autoScroll) startAutoPlay();
										}
									}
								}
							});
							/* eslint-enable no-new */
							iframe.dataset.atsYtBound = '1';
						} catch (err) {}
					});
				});
			}
        });
    }

    document.addEventListener("DOMContentLoaded", ats_initializeCarousels);


    document.addEventListener('DOMContentLoaded', function () {

        const mapLinks = document.querySelectorAll('.ats-map-link');

        mapLinks.forEach(function (link) {
            const address = link.getAttribute('data-address');

            if (address) {
                let mapUrl = '';

                if (/iPhone|iPad|iPod/.test(navigator.userAgent)) {
                    // Apple Maps URL for iPhone
                    mapUrl = "https://maps.apple.com/?q=" + encodeURIComponent(address);
                } else {
                    // Google Maps URL for everything else
                    mapUrl = 'https://www.google.com/maps/dir/?api=1&destination=' + encodeURIComponent(address);
                }

                link.setAttribute('href', mapUrl);
            }
        });

    });


    document.addEventListener('DOMContentLoaded', function () {
        function handleCarouselConditionalThumbnails() {
            const conditionalThumbnails = document.querySelectorAll('img.wp-post-image[data-carousel-conditional="true"]');

            conditionalThumbnails.forEach(img => {
                const contentArea = img.closest('.entry-content, .post-content, article, .content') || document;
                const carousel = contentArea.querySelector('.carousel-container[data-carousel-id]');

                const hasVisibleCarousel = carousel &&
                    carousel.offsetHeight > 0 &&
                    carousel.offsetWidth > 0 &&
                    window.getComputedStyle(carousel).display !== 'none';

                if (hasVisibleCarousel) {
                    img.style.display = 'none';

                    // Check if parent has the wp-block-post-featured-image class
                    const wrapper = img.parentElement?.classList.contains('wp-block-post-featured-image') ? img.parentElement : null;
                    if (wrapper && wrapper.children.length === 1) {
                        wrapper.style.display = 'none';
                    }
                } else {
                    img.style.display = '';

                    const wrapper = img.parentElement?.classList.contains('wp-block-post-featured-image') ? img.parentElement : null;
                    if (wrapper) {
                        wrapper.style.display = '';
                    }
                }
            });
        }

        // Check on load
        handleCarouselConditionalThumbnails();

        // Check after short delay for dynamic content
        setTimeout(handleCarouselConditionalThumbnails, 200);
    });


})( jQuery );
