document.addEventListener('DOMContentLoaded', () => {

    /**
     * Funkcija za nalaganje HTML komponent (glava, noga).
     */
    const loadComponent = (componentPath, placeholderId) => {
        return fetch(componentPath)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Napaka pri nalaganju komponente: ${componentPath}`);
                }
                return response.text();
            })
            .then(data => {
                const placeholder = document.getElementById(placeholderId);
                if (placeholder) {
                    placeholder.innerHTML = data;
                }
            })
            .catch(error => console.error(error));
    };

    /**
     * Funkcija za nastavitev trenutnega leta v nogi.
     */
    const setCurrentYear = () => {
        const yearSpan = document.getElementById('current-year');
        if (yearSpan) {
            yearSpan.textContent = new Date().getFullYear();
        }
    };

    /**
     * Funkcija, ki nastavi `.active` razred na trenutno aktivno povezavo v navigaciji.
     */
    const setActiveNavLink = () => {
        const navLinks = document.querySelectorAll('.main-nav a');
        const currentPagePath = window.location.pathname;

        navLinks.forEach(link => {
            const linkPath = new URL(link.href).pathname;
            if (linkPath === currentPagePath || (linkPath !== '/' && currentPagePath.startsWith(linkPath))) {
                link.classList.add('active');
            }
        });
    };

    /**
     * Glavna funkcija za inicializacijo vseh interaktivnih elementov spletne strani.
     */
    const initializeApp = () => {

        // =================================================================
        // === LOGIKA ZA DRSNIK NA DOMAČI STRANI (PRILAGOJENO ZA MOBILNE NAPRAVE) ===
        // =================================================================
        const sliderElement = document.getElementById("slider");

        if (sliderElement) {
            const slides = sliderElement.querySelectorAll(".slide");
            const prevBtn = document.getElementById("prevBtn");
            const nextBtn = document.getElementById("nextBtn");
            let current = 0;
            const total = slides.length;
            let slideInterval;
            const autoPlayDelay = 5000; // 5 sekund

            // Funkcija za prikaz prosojnice
            const showSlide = (index) => {
                if (slides.length === 0) return;
                slides[current].classList.remove("active");
                current = (index + total) % total; // Modulo za ciklično ponavljanje
                slides[current].classList.add("active");
            };

            // Funkcije za premikanje in pavzo
            const nextSlide = () => showSlide(current + 1);
            const prevSlide = () => showSlide(current - 1);
            const pauseSlider = () => clearInterval(slideInterval);

            // Funkcija za zagon (ali ponovni zagon) drsnika
            const startSlider = () => {
                pauseSlider(); // Najprej ustavimo morebitni obstoječi interval
                if (slides.length > 1) { // Zaženemo samo, če je več kot en slide
                    slideInterval = setInterval(nextSlide, autoPlayDelay);
                }
            };
            
            // Dogodki za ročno navigacijo
            prevBtn.addEventListener("click", () => {
                prevSlide();
                startSlider(); // Ponovno zaženi časovnik ob ročni interakciji
            });

            nextBtn.addEventListener("click", () => {
                nextSlide();
                startSlider(); // Ponovno zaženi časovnik ob ročni interakciji
            });
            
            // --- DOGODKI ZA PAVZO ---
            // 1. Pavza ob preletu z miško (za namizne računalnike)
            sliderElement.addEventListener('mouseenter', pauseSlider);

            // 2. Nadaljevanje ob umiku miške (za namizne računalnike)
            sliderElement.addEventListener('mouseleave', startSlider);
            
            // 3. Pavza ob dotiku (za mobilne naprave)
            sliderElement.addEventListener('touchstart', pauseSlider, { passive: true });

            // Zagon drsnika ob nalaganju strani
            startSlider();
        }

        // =================================================================
        // === KODA ZA MOBILNI MENI (NESPREMENJENO)                       ===
        // =================================================================
        const mobileNavToggle = document.querySelector('.mobile-nav-toggle');
        const mainNav = document.querySelector('.main-nav');
        
        if (mobileNavToggle && mainNav) {
            mobileNavToggle.addEventListener('click', () => {
                const isExpanded = mobileNavToggle.getAttribute('aria-expanded') === 'true';
                mobileNavToggle.setAttribute('aria-expanded', !isExpanded);
                
                mobileNavToggle.classList.toggle('open');
                mainNav.classList.toggle('open');
            });

            const navLinks = mainNav.querySelectorAll('a');
            navLinks.forEach(link => {
                link.addEventListener('click', () => {
                    if (mainNav.classList.contains('open')) {
                        mainNav.classList.remove('open');
                        mobileNavToggle.classList.remove('open');
                        mobileNavToggle.setAttribute('aria-expanded', 'false');
                    }
                });
            });
        }

        // =================================================================
        // === OBSTOJEČA KODA ZA PODSTRANI (NESPREMENJENO)               ===
        // =================================================================

        // Animacije ob pomikanju (Intersection Observer)
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('is-visible');
                }
            });
        }, { threshold: 0.1 });
        document.querySelectorAll('.animate-on-scroll').forEach(el => observer.observe(el));

        // Accordion (Cenik)
        document.querySelectorAll('.accordion-item').forEach(item => {
            const header = item.querySelector('.accordion-header');
            const content = item.querySelector('.accordion-content');
            if(header && content) {
                header.addEventListener('click', () => {
                    const isActive = item.classList.toggle('active');
                    content.style.maxHeight = isActive ? content.scrollHeight + 'px' : null;
                });
                if (item.classList.contains('active')) {
                    content.style.maxHeight = content.scrollHeight + 'px';
                }
            }
        });

        // Koda za kontaktni obrazec
        const contactForm = document.getElementById('contact-form');
        if (contactForm) {
            let formMessageElement = contactForm.querySelector('.form-message');
            if (!formMessageElement) {
                formMessageElement = document.createElement('div');
                formMessageElement.className = 'form-message';
                formMessageElement.setAttribute('aria-live', 'polite');
                contactForm.appendChild(formMessageElement);
            }
            
            contactForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const name = document.getElementById('name').value;
                const email = document.getElementById('email').value;
                const message = document.getElementById('message').value;
                formMessageElement.textContent = '';
                formMessageElement.className = 'form-message';

                if (name.trim() === '' || email.trim() === '' || message.trim() === '') {
                    formMessageElement.textContent = 'Prosimo, izpolnite vsa polja.';
                    formMessageElement.classList.add('error', 'visible');
                    return;
                }
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(email)) {
                    formMessageElement.textContent = 'Prosimo, vnesite veljaven e-poštni naslov.';
                    formMessageElement.classList.add('error', 'visible');
                    return;
                }

                formMessageElement.textContent = 'Hvala za vaše sporočilo! Odgovoril/a vam bom v najkrajšem možnem času.';
                formMessageElement.classList.add('success', 'visible');
                contactForm.reset();
                setTimeout(() => formMessageElement.classList.remove('visible'), 5000);
            });

            const messageTextarea = document.getElementById('message');
            const charCounter = document.getElementById('char-counter');

            if (messageTextarea && charCounter) {
                const maxLength = messageTextarea.getAttribute('maxlength');

                messageTextarea.addEventListener('input', () => {
                    const currentLength = messageTextarea.value.length;
                    const remaining = maxLength - currentLength;
                    
                    charCounter.textContent = `${remaining} znakov na voljo`;

                    if (remaining < 0) {
                        charCounter.classList.add('limit');
                        charCounter.classList.remove('warning');
                    } else if (remaining <= 20) {
                        charCounter.classList.add('warning');
                        charCounter.classList.remove('limit');
                    } else {
                        charCounter.classList.remove('warning');
                        charCounter.classList.remove('limit');
                    }
                });
            }
        }

        // Gumb za na vrh
        const backToTopButton = document.getElementById('back-to-top-btn');
        if (backToTopButton) {
            window.addEventListener('scroll', () => {
                if (window.scrollY > 300) {
                    backToTopButton.classList.add('visible');
                } else {
                    backToTopButton.classList.remove('visible');
                }
            });

            backToTopButton.addEventListener('click', (e) => {
                e.preventDefault();
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
        }
    };

    // --- Glavni Zagon Aplikacije ---
    if (document.getElementById('header-placeholder') && document.getElementById('footer-placeholder')) {
        Promise.all([
            loadComponent('/layouts/header.html', 'header-placeholder'),
            loadComponent('/layouts/footer.html', 'footer-placeholder')
        ]).then(() => {
            setCurrentYear();
            setActiveNavLink();
            initializeApp();
        });
    } else {
        setCurrentYear();
        setActiveNavLink();
        initializeApp();
    }
});