// Portfolio Web Application
class PortfolioApp {
    constructor() {
        this.init();
    }

    init() {
        this.setupMobileMenu();
        this.setupSmoothScrolling();
        this.setupScrollEffects();
        this.setupPortfolioFilter();
        this.setupFormHandling();
        this.setupScrollToTop();
        this.setupLanguageSwitch();
        this.setupAnimations();
        
        console.log('Portfolio aplikace úspěšně načtena! 🚀');
    }

    // ==========================================
    // MOBILE MENU
    // ==========================================
    setupMobileMenu() {
        const menuToggle = document.getElementById('menuToggle');
        const navLinks = document.getElementById('navLinks');
        const links = navLinks.querySelectorAll('a');

        if (menuToggle && navLinks) {
            menuToggle.addEventListener('click', () => {
                navLinks.classList.toggle('active');
                menuToggle.classList.toggle('active');
            });

            // Zavření menu po kliknutí na odkaz
            links.forEach(link => {
                link.addEventListener('click', () => {
                    navLinks.classList.remove('active');
                    menuToggle.classList.remove('active');
                });
            });

            // Zavření menu při kliknutí mimo
            document.addEventListener('click', (e) => {
                if (!menuToggle.contains(e.target) && !navLinks.contains(e.target)) {
                    navLinks.classList.remove('active');
                    menuToggle.classList.remove('active');
                }
            });
        }
    }

    // ==========================================
    // SMOOTH SCROLLING
    // ==========================================
    setupSmoothScrolling() {
        const links = document.querySelectorAll('a[href^="#"]');
        
        links.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const targetId = link.getAttribute('href');
                
                if (targetId === '#') return;
                
                const targetSection = document.querySelector(targetId);
                if (targetSection) {
                    const headerHeight = 80;
                    const targetPosition = targetSection.offsetTop - headerHeight;
                    
                    window.scrollTo({
                        top: targetPosition,
                        behavior: 'smooth'
                    });
                }
            });
        });
    }

    // ==========================================
    // SCROLL EFFECTS
    // ==========================================
    setupScrollEffects() {
        const header = document.getElementById('header');
        let lastScroll = 0;

        window.addEventListener('scroll', () => {
            const currentScroll = window.pageYOffset;

            // Header background
            if (currentScroll > 100) {
                header.style.background = 'rgba(255, 255, 255, 0.98)';
                header.style.backdropFilter = 'blur(10px)';
                header.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.15)';
            } else {
                header.style.background = '#ffffff';
                header.style.backdropFilter = 'none';
                header.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.1)';
            }

            // Aktivní odkaz v navigaci
            this.updateActiveNavLink();

            // Scroll to top button
            this.toggleScrollToTop(currentScroll);

            lastScroll = currentScroll;
        });
    }

    updateActiveNavLink() {
        const sections = document.querySelectorAll('section[id]');
        const navLinks = document.querySelectorAll('.nav-links a');
        
        let currentSection = '';
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop - 100;
            const sectionHeight = section.clientHeight;
            
            if (window.pageYOffset >= sectionTop && 
                window.pageYOffset < sectionTop + sectionHeight) {
                currentSection = section.getAttribute('id');
            }
        });
        
        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${currentSection}`) {
                link.classList.add('active');
            }
        });
    }

    // ==========================================
    // PORTFOLIO FILTER
    // ==========================================
    setupPortfolioFilter() {
        const filterButtons = document.querySelectorAll('.filter-btn');
        const portfolioItems = document.querySelectorAll('.portfolio-item');

        filterButtons.forEach(button => {
            button.addEventListener('click', () => {
                // Remove active class from all buttons
                filterButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');

                const filterValue = button.getAttribute('data-filter');

                portfolioItems.forEach(item => {
                    if (filterValue === 'all') {
                        item.style.display = 'block';
                        setTimeout(() => {
                            item.style.opacity = '1';
                            item.style.transform = 'scale(1)';
                        }, 10);
                    } else {
                        const categories = item.getAttribute('data-category');
                        
                        if (categories && categories.includes(filterValue)) {
                            item.style.display = 'block';
                            setTimeout(() => {
                                item.style.opacity = '1';
                                item.style.transform = 'scale(1)';
                            }, 10);
                        } else {
                            item.style.opacity = '0';
                            item.style.transform = 'scale(0.8)';
                            setTimeout(() => {
                                item.style.display = 'none';
                            }, 300);
                        }
                    }
                });
            });
        });
    }

    // ==========================================
    // FORM HANDLING
    // ==========================================
    setupFormHandling() {
        const contactForm = document.getElementById('contactForm');
        
        if (contactForm) {
            contactForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                await this.handleFormSubmit(contactForm);
            });
        }
    }

    async handleFormSubmit(form) {
        const submitButton = form.querySelector('button[type="submit"]');
        const originalText = submitButton.textContent;
        const formData = new FormData(form);
        
        // Validace
        const name = formData.get('name');
        const email = formData.get('email');
        const subject = formData.get('subject');
        const message = formData.get('message');
        
        if (!name || !email || !subject || !message) {
            this.showNotification('Prosím vyplňte všechna povinná pole', 'error');
            return;
        }
        
        if (!this.validateEmail(email)) {
            this.showNotification('Prosím zadejte platnou emailovou adresu', 'error');
            return;
        }

        try {
            // Loading state
            submitButton.innerHTML = '<div class="loading"></div>';
            submitButton.disabled = true;

            // Simulace odeslání (zde by byla skutečná API request)
            await new Promise(resolve => setTimeout(resolve, 2000));

            this.showNotification(
                '✅ Zpráva úspěšně odeslána! Ozveme se vám co nejdříve.',
                'success'
            );
            
            form.reset();

        } catch (error) {
            this.showNotification(
                '❌ Chyba při odesílání zprávy. Zkuste to prosím znovu.',
                'error'
            );
            console.error('Form submission error:', error);
        } finally {
            submitButton.textContent = originalText;
            submitButton.disabled = false;
        }
    }

    validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    // ==========================================
    // SCROLL TO TOP
    // ==========================================
    setupScrollToTop() {
        // Create button if it doesn't exist
        let scrollButton = document.querySelector('.scroll-top');
        
        if (!scrollButton) {
            scrollButton = document.createElement('button');
            scrollButton.className = 'scroll-top';
            scrollButton.innerHTML = '↑';
            scrollButton.setAttribute('aria-label', 'Zpět nahoru');
            document.body.appendChild(scrollButton);
        }

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

    toggleScrollToTop(scrollY) {
        const scrollButton = document.querySelector('.scroll-top');
        if (scrollButton) {
            if (scrollY > 400) {
                scrollButton.style.display = 'flex';
                scrollButton.style.opacity = '1';
            } else {
                scrollButton.style.opacity = '0';
                setTimeout(() => {
                    if (window.pageYOffset <= 400) {
                        scrollButton.style.display = 'none';
                    }
                }, 300);
            }
        }
    }

    // ==========================================
    // LANGUAGE SWITCH
    // ==========================================
    setupLanguageSwitch() {
        const langButtons = document.querySelectorAll('.lang-btn');
        
        langButtons.forEach(button => {
            button.addEventListener('click', () => {
                langButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                
                const lang = button.getAttribute('data-lang');
                this.changeLanguage(lang);
            });
        });
    }

    changeLanguage(lang) {
        // Zde by byla implementace změny jazyka
        console.log(`Změna jazyka na: ${lang}`);
        this.showNotification(
            lang === 'cs' ? 'Jazyk změněn na češtinu' : 'Language changed to English',
            'success'
        );
    }

    // ==========================================
    // ANIMATIONS
    // ==========================================
    setupAnimations() {
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -100px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('fade-in');
                    
                    // Animace skill barů
                    if (entry.target.classList.contains('skill-item')) {
                        const progress = entry.target.querySelector('.skill-progress');
                        if (progress) {
                            const width = progress.style.width;
                            progress.style.width = '0';
                            setTimeout(() => {
                                progress.style.width = width;
                            }, 200);
                        }
                    }
                }
            });
        }, observerOptions);

        // Elementy k pozorování
        const animatedElements = document.querySelectorAll(`
            .service-card,
            .portfolio-item,
            .process-step,
            .skill-item,
            .contact-item
        `);
        
        animatedElements.forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(30px)';
            observer.observe(el);
        });
    }

    // ==========================================
    // NOTIFICATION SYSTEM
    // ==========================================
    showNotification(message, type = 'info') {
        // Odstranit existující notifikaci
        const existingNotification = document.querySelector('.notification');
        if (existingNotification) {
            existingNotification.remove();
        }

        // Vytvořit novou notifikaci
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;

        // Styly
        const bgColors = {
            success: '#28a745',
            error: '#dc3545',
            info: '#667eea'
        };

        Object.assign(notification.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            background: bgColors[type] || bgColors.info,
            color: 'white',
            padding: '1rem 1.5rem',
            borderRadius: '10px',
            boxShadow: '0 10px 30px rgba(0, 0, 0, 0.2)',
            zIndex: '10000',
            transform: 'translateX(400px)',
            transition: 'transform 0.3s ease',
            maxWidth: '400px',
            fontWeight: '500'
        });

        document.body.appendChild(notification);

        // Animace vstupu
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);

        // Automatické odstranění
        setTimeout(() => {
            notification.style.transform = 'translateX(400px)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 300);
        }, 5000);
    }
}

// ==========================================
// INICIALIZACE
// ==========================================
document.addEventListener('DOMContentLoaded', () => {
    new PortfolioApp();
});

// Service Worker registrace (pro PWA)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('./service-worker.js')
            .then(reg => console.log('Service Worker registered'))
            .catch(err => console.log('Service Worker registration failed'));
    });
}
