// script.js - Základná klientska logika pre ezamki.com

(function() {
    'use strict';

    // ==================== INICIALIZÁCIA ====================
    
    document.addEventListener('DOMContentLoaded', function() {
        initSmoothScroll();
        initFAQ();
        initCookieBanner();
        initVisitorCounter();
        initContactForm();
        initMobileMenu();
    });

    // ==================== PLAVNÝ SKROLL ====================
    
    function initSmoothScroll() {
        // Plavný skroll pre všetky interné anchor odkazy
        const anchors = document.querySelectorAll('a[href^="#"]');
        
        anchors.forEach(function(anchor) {
            anchor.addEventListener('click', function(e) {
                const href = this.getAttribute('href');
                
                // Ignoruj prázdne alebo len # odkazy
                if (!href || href === '#') {
                    return;
                }
                
                const target = document.querySelector(href);
                
                if (target) {
                    e.preventDefault();
                    
                    const headerOffset = 80; // Výška sticky header
                    const elementPosition = target.getBoundingClientRect().top;
                    const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                    
                    window.scrollTo({
                        top: offsetPosition,
                        behavior: 'smooth'
                    });
                }
            });
        });
    }

    // ==================== FAQ ACCORDION ====================
    
    function initFAQ() {
        const faqQuestions = document.querySelectorAll('.faq-question');
        
        faqQuestions.forEach(function(question) {
            question.addEventListener('click', function() {
                toggleFaqItem(this);
            });
        });
    }
    
    function toggleFaqItem(element) {
        const answer = element.nextElementSibling;
        const icon = element.querySelector('.faq-icon i');
        const allAnswers = document.querySelectorAll('.faq-answer');
        const allIcons = document.querySelectorAll('.faq-icon i');
        
        // Zatvor všetky ostatné odpovede
        allAnswers.forEach(function(item) {
            if (item !== answer && item.classList.contains('active')) {
                item.classList.remove('active');
            }
        });
        
        // Reset všetkých ikon
        allIcons.forEach(function(item) {
            if (item !== icon) {
                item.style.transform = 'rotate(0deg)';
            }
        });
        
        // Toggle aktuálnej odpovede
        answer.classList.toggle('active');
        
        if (answer.classList.contains('active')) {
            icon.style.transform = 'rotate(180deg)';
        } else {
            icon.style.transform = 'rotate(0deg)';
        }
    }

    // ==================== COOKIE BANNER ====================
    
    function initCookieBanner() {
        const cookieBanner = document.getElementById('cookieBanner');
        
        if (!cookieBanner) {
            return;
        }
        
        // Zobraz banner, ak nie je súhlas uložený
        if (!getCookieConsent()) {
            setTimeout(function() {
                cookieBanner.classList.add('show');
            }, 1000);
        }
    }
    
    function getCookieConsent() {
        return localStorage.getItem('cookiesAccepted');
    }
    
    window.acceptCookies = function() {
        localStorage.setItem('cookiesAccepted', 'true');
        hideCookieBanner();
        
        // Tu môžeš aktivovať analytics a marketing cookies
        if (typeof gtag !== 'undefined') {
            gtag('consent', 'update', {
                'analytics_storage': 'granted',
                'ad_storage': 'granted'
            });
        }
    };
    
    window.declineCookies = function() {
        localStorage.setItem('cookiesAccepted', 'false');
        hideCookieBanner();
        
        // Deaktivuj analytics a marketing cookies
        if (typeof gtag !== 'undefined') {
            gtag('consent', 'update', {
                'analytics_storage': 'denied',
                'ad_storage': 'denied'
            });
        }
    };
    
    function hideCookieBanner() {
        const cookieBanner = document.getElementById('cookieBanner');
        if (cookieBanner) {
            cookieBanner.classList.remove('show');
        }
    }

    // ==================== POČÍTADLO NÁVŠTEVNÍKOV ====================
    
    function initVisitorCounter() {
        const visitorElement = document.getElementById('visitors');
        
        if (!visitorElement) {
            return;
        }
        
        // Získaj aktuálny počet alebo začni od 1247
        let count = parseInt(localStorage.getItem('visitorCount')) || 1247;
        count++;
        localStorage.setItem('visitorCount', count);
        
        // Animovaný počítač
        animateCounter(visitorElement, 0, count, 1500);
    }
    
    function animateCounter(element, start, end, duration) {
        const increment = Math.ceil((end - start) / 50);
        let current = start;
        
        const timer = setInterval(function() {
            current += increment;
            if (current >= end) {
                current = end;
                clearInterval(timer);
            }
            element.textContent = current.toLocaleString('sk-SK');
        }, duration / 50);
    }

    // ==================== KONTAKTNÝ FORMULÁR ====================
    
    function initContactForm() {
        const contactForm = document.getElementById('contactForm');
        
        if (!contactForm) {
            return;
        }
        
        contactForm.addEventListener('submit', function(e) {
            handleContactFormSubmit(e);
        });
    }
    
    function handleContactFormSubmit(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        
        // Validácia
        const name = formData.get('name');
        const email = formData.get('email');
        const message = formData.get('message');
        
        if (!name || !email || !message) {
            showNotification('Prosím vyplňte všetky povinné polia.', 'error');
            return;
        }
        
        if (!isValidEmail(email)) {
            showNotification('Prosím zadajte platnú emailovú adresu.', 'error');
            return;
        }
        
        // Simuluj odoslanie (v reálnej aplikácii by tu bol AJAX request)
        showSuccessModal();
        form.reset();
        
        // Tu by bolo skutočné odoslanie:
        // submitFormData(formData);
    }
    
    function isValidEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
    
    function showSuccessModal() {
        const modal = document.getElementById('successModal');
        if (modal) {
            modal.classList.add('show');
        }
    }
    
    window.closeModal = function() {
        const modal = document.getElementById('successModal');
        if (modal) {
            modal.classList.remove('show');
        }
    };
    
    function showNotification(message, type) {
        // Jednoduchá notifikácia (môžeš nahradiť toast knižnicou)
        alert(message);
    }

    // ==================== MOBILNÉ MENU ====================
    
    function initMobileMenu() {
        const header = document.querySelector('header');
        const nav = document.querySelector('nav');
        
        if (!header || !nav) {
            return;
        }
        
        // Vytvor burger menu button pre mobile
        if (window.innerWidth <= 768) {
            createBurgerMenu(header, nav);
        }
        
        // Re-init pri zmene veľkosti okna
        window.addEventListener('resize', debounce(function() {
            if (window.innerWidth <= 768) {
                createBurgerMenu(header, nav);
            } else {
                removeBurgerMenu(nav);
            }
        }, 250));
    }
    
    function createBurgerMenu(header, nav) {
        // Skontroluj, či burger už neexistuje
        if (document.querySelector('.burger-menu')) {
            return;
        }
        
        const burger = document.createElement('button');
        burger.className = 'burger-menu';
        burger.innerHTML = '<i class="fas fa-bars"></i>';
        burger.setAttribute('aria-label', 'Menu');
        
        // Pridaj štýly
        burger.style.cssText = `
            background: none;
            border: none;
            font-size: 24px;
            color: #667eea;
            cursor: pointer;
            padding: 10px;
            display: block;
        `;
        
        burger.addEventListener('click', function() {
            nav.classList.toggle('mobile-open');
            
            if (nav.classList.contains('mobile-open')) {
                burger.innerHTML = '<i class="fas fa-times"></i>';
                nav.style.display = 'block';
            } else {
                burger.innerHTML = '<i class="fas fa-bars"></i>';
                nav.style.display = 'none';
            }
        });
        
        const headerContent = header.querySelector('.header-content');
        if (headerContent) {
            headerContent.appendChild(burger);
        }
        
        // Skry nav defaultne na mobile
        if (window.innerWidth <= 768) {
            nav.style.display = 'none';
        }
    }
    
    function removeBurgerMenu(nav) {
        const burger = document.querySelector('.burger-menu');
        if (burger) {
            burger.remove();
        }
        nav.style.display = '';
        nav.classList.remove('mobile-open');
    }

    // ==================== POMOCNÉ FUNKCIE ====================
    
    function debounce(func, wait) {
        let timeout;
        return function executedFunction() {
            const context = this;
            const args = arguments;
            const later = function() {
                timeout = null;
                func.apply(context, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // ==================== BACK TO TOP ====================
    
    function initBackToTop() {
        const backToTopBtn = document.createElement('button');
        backToTopBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
        backToTopBtn.className = 'back-to-top';
        backToTopBtn.setAttribute('aria-label', 'Späť hore');
        
        backToTopBtn.style.cssText = `
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            font-size: 20px;
            cursor: pointer;
            display: none;
            z-index: 999;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transition: all 0.3s;
        `;
        
        document.body.appendChild(backToTopBtn);
        
        // Zobraz/skry button pri scrolle
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                backToTopBtn.style.display = 'block';
            } else {
                backToTopBtn.style.display = 'none';
            }
        });
        
        // Scroll hore pri kliku
        backToTopBtn.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
    
    // Inicializuj back to top
    initBackToTop();

    // ==================== LAZY LOADING OBRÁZKOV ====================
    
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver(function(entries, observer) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    if (img.dataset.src) {
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                    }
                    imageObserver.unobserve(img);
                }
            });
        });
        
        document.querySelectorAll('img[data-src]').forEach(function(img) {
            imageObserver.observe(img);
        });
    }

})();
