// ============================================
// Theme Toggle (Dark/Light Mode)
// ============================================

function initThemeToggle() {
    const themeToggle = document.querySelector('.theme-toggle');
    const html = document.documentElement;
    
    // Get saved theme or default to light
    const savedTheme = localStorage.getItem('theme') || 'light';
    html.setAttribute('data-theme', savedTheme);
    
    if (themeToggle) {
        // Update button aria-label and icon
        updateThemeButton(themeToggle, savedTheme);
        
        themeToggle.addEventListener('click', () => {
            const currentTheme = html.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            html.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeButton(themeToggle, newTheme);
        });
    }
}

function updateThemeButton(button, theme) {
    const icon = button.querySelector('i');
    if (theme === 'dark') {
        button.setAttribute('aria-label', 'Превключи към светла тема');
        button.setAttribute('title', 'Превключи към светла тема');
        if (icon) {
            icon.className = 'bi bi-sun';
        }
    } else {
        button.setAttribute('aria-label', 'Превключи към тъмна тема');
        button.setAttribute('title', 'Превключи към тъмна тема');
        if (icon) {
            icon.className = 'bi bi-moon';
        }
    }
}

// Initialize theme on page load
initThemeToggle();

// ============================================
// Mobile Menu Toggle
// ============================================

const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
const nav = document.querySelector('.nav');

if (mobileMenuToggle) {
    mobileMenuToggle.addEventListener('click', () => {
        const isOpening = !nav.classList.contains('active');
        nav.classList.toggle('active');
        mobileMenuToggle.classList.toggle('active');
        
        // Close all dropdowns when opening the menu
        if (isOpening && window.innerWidth <= 1024) {
            document.querySelectorAll('.nav-dropdown').forEach(dropdown => {
                dropdown.style.display = 'none';
            });
        }
    });
}

// ============================================
// Dropdown Menu Toggle (Mobile)
// ============================================

// Initialize: Close all dropdowns on page load (especially for mobile)
function closeAllDropdowns() {
    if (window.innerWidth <= 1024) {
        document.querySelectorAll('.nav-dropdown').forEach(dropdown => {
            dropdown.style.display = 'none';
        });
    }
}

// Close dropdowns on page load
closeAllDropdowns();

// Close dropdowns on window resize to mobile
window.addEventListener('resize', () => {
    if (window.innerWidth <= 1024) {
        closeAllDropdowns();
    }
});

// Handle mobile dropdown navigation
function setupMobileDropdowns() {
    if (window.innerWidth <= 1024) {
document.querySelectorAll('.nav-item-dropdown > .nav-link').forEach(dropdownTrigger => {
            const chevron = dropdownTrigger.querySelector('i.bi-chevron-down, .dropdown-arrow');
            const dropdown = dropdownTrigger.nextElementSibling;
            
            if (chevron && dropdown) {
                // Click handler for the entire link
    dropdownTrigger.addEventListener('click', function(e) {
                    // Check if click is on chevron icon
                    const clickedOnChevron = e.target === chevron || 
                                           e.target.classList.contains('bi-chevron-down') || 
                                           e.target.classList.contains('dropdown-arrow') ||
                                           chevron.contains(e.target);
                    
                    if (clickedOnChevron) {
                        // If clicking chevron, toggle dropdown
            e.preventDefault();
                        e.stopPropagation();
            const isActive = dropdown.style.display === 'block';
            
            // Close all other dropdowns
            document.querySelectorAll('.nav-dropdown').forEach(dd => {
                if (dd !== dropdown) {
                    dd.style.display = 'none';
                }
            });
            
            // Toggle current dropdown
            dropdown.style.display = isActive ? 'none' : 'block';
        }
                    // If clicking link text, allow default navigation to services.html
                });
            }
        });
    }
}

// Initialize on load
setupMobileDropdowns();

// Re-initialize on resize
window.addEventListener('resize', () => {
    closeAllDropdowns();
    setupMobileDropdowns();
});

// ============================================
// Smooth Scrolling for Anchor Links
// ============================================

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        const href = this.getAttribute('href');
        if (href === '#' || href === '#home') {
            e.preventDefault();
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
            return;
        }
        
        const target = document.querySelector(href);
        if (target) {
            e.preventDefault();
            const headerOffset = 80;
            const elementPosition = target.getBoundingClientRect().top;
            const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

            window.scrollTo({
                top: offsetPosition,
                behavior: 'smooth'
            });
            
            // Close mobile menu if open
            if (nav && nav.classList.contains('active')) {
                nav.classList.remove('active');
                mobileMenuToggle.classList.remove('active');
            }
        }
    });
});

// ============================================
// Active Navigation Link on Scroll
// ============================================

const sections = document.querySelectorAll('section[id]');
const navLinks = document.querySelectorAll('.nav-link');

function updateActiveNavLink() {
    const scrollY = window.pageYOffset;

    sections.forEach(section => {
        const sectionHeight = section.offsetHeight;
        const sectionTop = section.offsetTop - 100;
        const sectionId = section.getAttribute('id');

        if (scrollY > sectionTop && scrollY <= sectionTop + sectionHeight) {
            navLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href') === `#${sectionId}`) {
                    link.classList.add('active');
                }
            });
        }
    });
}

window.addEventListener('scroll', updateActiveNavLink);

// ============================================
// Header Scroll Effect
// ============================================

const header = document.querySelector('.header');
let lastScroll = 0;

window.addEventListener('scroll', () => {
    const currentScroll = window.pageYOffset;
    
    if (currentScroll > 100) {
        header.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)';
    } else {
        header.style.boxShadow = '0 1px 2px 0 rgba(0, 0, 0, 0.05)';
    }
    
    lastScroll = currentScroll;
});

// ============================================
// Product Fetching (for future use)
// ============================================

async function fetchProducts() {
    try {
        const response = await fetch('https://www.bulclima.com/tools/api/items/');
        if (!response.ok) {
            throw new Error('Failed to fetch products');
        }
        
        const text = await response.text();
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(text, 'text/xml');
        
        // Parse XML and populate products
        // This will be implemented when we create the products page
        console.log('Products fetched successfully');
        return xmlDoc;
    } catch (error) {
        console.error('Error fetching products:', error);
        return null;
    }
}

// Uncomment when ready to use:
// fetchProducts();

// ============================================
// Intersection Observer for Animations
// ============================================

const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
        }
    });
}, observerOptions);

// Enhanced Intersection Observer for Animations
const animationObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry, index) => {
        if (entry.isIntersecting) {
            setTimeout(() => {
                entry.target.classList.add('animate-in');
            }, index * 100); // Stagger animation
            animationObserver.unobserve(entry.target);
        }
    });
}, {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
});

// Observe elements for fade-in animation
document.addEventListener('DOMContentLoaded', () => {
    // Animate cards
    const animatedElements = document.querySelectorAll('.feature-card, .product-card, .service-card, .info-card, .gallery-card, .testimonial-card, .value-item');
    animatedElements.forEach(el => {
        animationObserver.observe(el);
    });
    
    // Animate section headers
    const sectionHeaders = document.querySelectorAll('.section-header');
    sectionHeaders.forEach(header => {
        animationObserver.observe(header);
    });
    
    // Animate gallery hero elements
    const galleryHeroTitle = document.querySelector('.gallery-hero-title');
    const galleryHeroDescription = document.querySelector('.gallery-hero-description');
    const galleryStats = document.querySelector('.gallery-stats');
    
    if (galleryHeroTitle) {
        setTimeout(() => {
            galleryHeroTitle.classList.add('animate-in');
        }, 100);
    }
    
    if (galleryHeroDescription) {
        setTimeout(() => {
            galleryHeroDescription.classList.add('animate-in');
        }, 300);
    }
    
    if (galleryStats) {
        setTimeout(() => {
            galleryStats.classList.add('animate-in');
        }, 500);
    }
    
    // Animate contact hero elements
    const contactHeroTitle = document.querySelector('.contact-hero-title');
    const contactHeroSubtitle = document.querySelector('.contact-hero-subtitle');
    const contactStats = document.querySelector('.contact-hero .gallery-stats');
    
    if (contactHeroTitle) {
        setTimeout(() => {
            contactHeroTitle.classList.add('animate-in');
        }, 100);
    }
    
    if (contactHeroSubtitle) {
        setTimeout(() => {
            contactHeroSubtitle.classList.add('animate-in');
        }, 300);
    }
    
    if (contactStats) {
        setTimeout(() => {
            contactStats.classList.add('animate-in');
        }, 500);
    }
    
    // Animate tips hero elements
    const tipsHeroTitle = document.querySelector('.tips-hero-title');
    const tipsHeroDescription = document.querySelector('.tips-hero-description');
    const tipsStats = document.querySelector('.tips-stats');
    
    if (tipsHeroTitle) {
        setTimeout(() => {
            tipsHeroTitle.classList.add('animate-in');
        }, 100);
    }
    
    if (tipsHeroDescription) {
        setTimeout(() => {
            tipsHeroDescription.classList.add('animate-in');
        }, 300);
    }
    
    if (tipsStats) {
        setTimeout(() => {
            tipsStats.classList.add('animate-in');
        }, 500);
    }
    
    // Animate service hero elements
    const serviceHeroTitle = document.querySelector('.service-hero-title');
    const serviceHeroDescription = document.querySelector('.service-hero-description');
    const serviceHeroStats = document.querySelector('.service-hero-stats');
    
    if (serviceHeroTitle) {
        setTimeout(() => {
            serviceHeroTitle.classList.add('animate-in');
        }, 100);
    }
    
    if (serviceHeroDescription) {
        setTimeout(() => {
            serviceHeroDescription.classList.add('animate-in');
        }, 300);
    }
    
    if (serviceHeroStats) {
        setTimeout(() => {
            serviceHeroStats.classList.add('animate-in');
        }, 500);
    }
    
    // Expandable pricing table
    const expandTableBtn = document.getElementById('expandTableBtn');
    const pricingTable = document.querySelector('.pricing-table');
    
    if (expandTableBtn && pricingTable) {
        expandTableBtn.addEventListener('click', function() {
            pricingTable.classList.toggle('expanded');
            const isExpanded = pricingTable.classList.contains('expanded');
            
            const expandText = this.querySelector('.expand-text');
            const collapseText = this.querySelector('.collapse-text');
            
            if (isExpanded) {
                expandText.style.display = 'none';
                collapseText.style.display = 'inline';
            } else {
                expandText.style.display = 'inline';
                collapseText.style.display = 'none';
            }
        });
    }
    
    // Add parallax effect to hero image
    const heroImage = document.querySelector('.hero-image-wrapper');
    if (heroImage) {
        window.addEventListener('scroll', () => {
            const scrolled = window.pageYOffset;
            const rate = scrolled * 0.5;
            heroImage.style.transform = `translateY(${rate}px)`;
        });
    }
    
    // Add counter animation for stats
    const animateCounter = (element, target) => {
        let current = 0;
        const increment = target / 50;
        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                element.textContent = target + '+';
                clearInterval(timer);
            } else {
                element.textContent = Math.floor(current) + '+';
            }
        }, 30);
    };
    
    // Animate numbers when in view
    const numberObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const text = entry.target.textContent;
                const number = parseInt(text.match(/\d+/)?.[0] || '0');
                if (number > 0) {
                    animateCounter(entry.target, number);
                    numberObserver.unobserve(entry.target);
                }
            }
        });
    }, { threshold: 0.5 });
    
    // Observe rating numbers
    const ratingText = document.querySelector('.rating-text');
    if (ratingText) {
        numberObserver.observe(ratingText);
    }
});

// ============================================
// Form Handling (for contact forms)
// ============================================

function handleInquiry(productName) {
    // This will be implemented when we add contact forms
    console.log('Inquiry for:', productName);
    // Could open a modal or redirect to contact form
}

// Add event listeners to inquiry buttons
document.addEventListener('DOMContentLoaded', () => {
    const inquiryButtons = document.querySelectorAll('.btn-primary.btn-small');
    inquiryButtons.forEach(button => {
        if (button.textContent.includes('запитване')) {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const productCard = button.closest('.product-card');
                const productName = productCard ? productCard.querySelector('.product-brand')?.textContent : 'Продукт';
                handleInquiry(productName);
                // Scroll to contact section
                const contactSection = document.querySelector('#contact');
                if (contactSection) {
                    contactSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            });
        }
    });
});

// ============================================
// Image Lazy Loading Enhancement
// ============================================

if ('loading' in HTMLImageElement.prototype) {
    const images = document.querySelectorAll('img[data-src]');
    images.forEach(img => {
        img.src = img.dataset.src;
    });
} else {
    // Fallback for browsers that don't support lazy loading
    const script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js';
    document.body.appendChild(script);
}

// ============================================
// Utility Functions
// ============================================

// Format price
function formatPrice(price) {
    return new Intl.NumberFormat('bg-BG', {
        style: 'currency',
        currency: 'BGN',
        minimumFractionDigits: 0
    }).format(price);
}

// Debounce function for performance
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Optimized scroll handler
const optimizedScrollHandler = debounce(() => {
    updateActiveNavLink();
}, 10);

window.addEventListener('scroll', optimizedScrollHandler);

// ============================================
// Contact Page - FAQ Accordion
// ============================================

document.addEventListener('DOMContentLoaded', () => {
    const faqQuestions = document.querySelectorAll('.faq-question');
    
    faqQuestions.forEach(question => {
        question.addEventListener('click', () => {
            const faqItem = question.closest('.faq-item');
            const answer = faqItem.querySelector('.faq-answer');
            const isExpanded = question.getAttribute('aria-expanded') === 'true';
            
            // Close all other FAQ items
            faqQuestions.forEach(otherQuestion => {
                if (otherQuestion !== question) {
                    const otherItem = otherQuestion.closest('.faq-item');
                    const otherAnswer = otherItem.querySelector('.faq-answer');
                    otherQuestion.setAttribute('aria-expanded', 'false');
                    otherAnswer.classList.remove('active');
                    otherQuestion.querySelector('.faq-icon').classList.remove('bi-dash-circle');
                    otherQuestion.querySelector('.faq-icon').classList.add('bi-plus-circle');
                }
            });
            
            // Toggle current FAQ item
            if (isExpanded) {
                question.setAttribute('aria-expanded', 'false');
                answer.classList.remove('active');
                question.querySelector('.faq-icon').classList.remove('bi-dash-circle');
                question.querySelector('.faq-icon').classList.add('bi-plus-circle');
            } else {
                question.setAttribute('aria-expanded', 'true');
                answer.classList.add('active');
                question.querySelector('.faq-icon').classList.remove('bi-plus-circle');
                question.querySelector('.faq-icon').classList.add('bi-dash-circle');
            }
        });
    });
});

// ============================================
// Contact Form Handling
// ============================================

document.addEventListener('DOMContentLoaded', () => {
    // ============================================
    // Service Package Button Handler
    // ============================================
    // Handle clicks on service package buttons to auto-fill contact form
    document.querySelectorAll('.tier-button[data-service]').forEach(button => {
        button.addEventListener('click', (e) => {
            e.preventDefault();
            
            const service = button.getAttribute('data-service');
            const packageName = button.getAttribute('data-package');
            const price = button.getAttribute('data-price');
            
            // Find the contact form on the page
            const contactFormSection = document.getElementById('contact-form');
            if (!contactFormSection) return;
            
            // Scroll to the contact form
            contactFormSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
            
            // Wait a bit for scroll to complete, then fill the form
            setTimeout(() => {
                // Get form elements - check all possible form IDs
                const formIds = ['contactForm', 'installationForm', 'maintenanceForm', 'diagnosticsForm'];
                let inquiryTypeField = null;
                let messageField = null;
                
                for (const formId of formIds) {
                    const form = document.getElementById(formId);
                    if (form) {
                        inquiryTypeField = form.querySelector('#inquiryType');
                        messageField = form.querySelector('#message');
                        break;
                    }
                }
                
                // If not found in forms, try direct IDs
                if (!inquiryTypeField) {
                    inquiryTypeField = document.getElementById('inquiryType');
                }
                if (!messageField) {
                    messageField = document.getElementById('message');
                }
                
                // Set inquiry type
                if (inquiryTypeField) {
                    inquiryTypeField.value = service;
                    inquiryTypeField.classList.add('success');
                }
                
                // Build and set message
                if (messageField) {
                    const serviceLabels = {
                        'installation': 'Монтаж на климатик',
                        'maintenance': 'Профилактика на климатици',
                        'repair': 'Диагностика и сервиз'
                    };
                    
                    let messageText = 'Здравейте,\n\n';
                    messageText += `Интересувам се от услуга: ${serviceLabels[service] || service}\n\n`;
                    messageText += `Избран пакет: ${packageName}\n`;
                    if (price) {
                        messageText += `Цена: ${price}\n`;
                    }
                    messageText += '\nМоля, свържете се с мен за повече информация и да уговорим удобен час.\n\nБлагодаря!';
                    
                    messageField.value = messageText;
                    messageField.classList.add('success');
                    
                    // Focus on the message field
                    messageField.focus();
                }
            }, 300);
        });
    });
    
    const contactForm = document.getElementById('contactForm');
    const submitBtn = document.getElementById('submitBtn');
    const formSuccess = document.getElementById('formSuccess');
    
    if (!contactForm) return;
    
    // Pre-fill form with information from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    
    // Check for inquiry type from service pages
    const inquiryTypeParam = urlParams.get('inquiryType');
    if (inquiryTypeParam) {
        const inquiryType = document.getElementById('inquiryType');
        if (inquiryType) {
            inquiryType.value = inquiryTypeParam;
            // Trigger validation to show success state
            inquiryType.classList.add('success');
        }
    }
    
    // Check for product information from product pages
    const productId = urlParams.get('productId');
    const productName = urlParams.get('productName');
    const productPrice = urlParams.get('productPrice');
    const productBrand = urlParams.get('productBrand');
    const productCode = urlParams.get('productCode');
    
    if (productId || productName) {
        // Set inquiry type to consultation (unless already set by service)
        if (!inquiryTypeParam) {
            const inquiryType = document.getElementById('inquiryType');
            if (inquiryType) {
                inquiryType.value = 'consultation';
                inquiryType.classList.add('success');
            }
        }
        
        // Pre-fill message with product information
        const messageField = document.getElementById('message');
        if (messageField) {
            let messageText = 'Здравейте,\n\nИнтересувам се от следния продукт:\n\n';
            
            if (productName) {
                messageText += `Продукт: ${productName}\n`;
            }
            if (productBrand) {
                messageText += `Марка: ${productBrand}\n`;
            }
            if (productCode) {
                messageText += `Код на продукт: ${productCode}\n`;
            }
            if (productId) {
                messageText += `ID: ${productId}\n`;
            }
            if (productPrice) {
                messageText += `Цена: ${productPrice} лв.\n`;
            }
            
            messageText += '\nМоля, свържете се с мен за повече информация.\n\nБлагодаря!';
            
            messageField.value = messageText;
            // Trigger validation to show success state
            if (messageField.value.trim()) {
                messageField.classList.add('success');
            }
        }
    }
    
    // Real-time validation
    const validateField = (field) => {
        const fieldId = field.id;
        const errorElement = document.getElementById(fieldId + 'Error');
        let isValid = true;
        let errorMessage = '';
        
        // Remove previous states
        field.classList.remove('error', 'success');
        if (errorElement) {
            errorElement.classList.remove('show');
        }
        
        // Check if required field is empty
        if (field.hasAttribute('required') && !field.value.trim()) {
            isValid = false;
            errorMessage = 'Това поле е задължително';
        }
        
        // Email validation
        if (field.type === 'email' && field.value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(field.value)) {
                isValid = false;
                errorMessage = 'Моля, въведете валиден email адрес';
            }
        }
        
        // Select validation
        if (field.tagName === 'SELECT' && field.hasAttribute('required') && !field.value) {
            isValid = false;
            errorMessage = 'Моля, изберете опция';
        }
        
        // Show error or success
        if (!isValid) {
            field.classList.add('error');
            if (errorElement) {
                errorElement.textContent = errorMessage;
                errorElement.classList.add('show');
            }
        } else if (field.value.trim()) {
            field.classList.add('success');
        }
        
        return isValid;
    };
    
    // Validate on blur
    const formFields = contactForm.querySelectorAll('input, select, textarea');
    formFields.forEach(field => {
        field.addEventListener('blur', () => {
            validateField(field);
        });
        
        field.addEventListener('input', () => {
            if (field.classList.contains('error')) {
                validateField(field);
            }
        });
    });
    
    // Checkbox validation
    const privacyCheckbox = document.getElementById('privacy');
    const privacyError = document.getElementById('privacyError');
    
    if (privacyCheckbox) {
        privacyCheckbox.addEventListener('change', () => {
            privacyCheckbox.classList.remove('error');
            if (privacyError) {
                privacyError.classList.remove('show');
            }
        });
    }
    
    // Form submission
    contactForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        // Validate all fields
        let isFormValid = true;
        formFields.forEach(field => {
            if (!validateField(field)) {
                isFormValid = false;
            }
        });
        
        // Validate checkbox
        if (privacyCheckbox && !privacyCheckbox.checked) {
            isFormValid = false;
            privacyCheckbox.classList.add('error');
            if (privacyError) {
                privacyError.textContent = 'Трябва да се съгласите с политиката за поверителност';
                privacyError.classList.add('show');
            }
        }
        
        if (!isFormValid) {
            // Scroll to first error
            const firstError = contactForm.querySelector('.error');
            if (firstError) {
                firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstError.focus();
            }
            return;
        }
        
        // Show loading state
        if (submitBtn) {
            submitBtn.classList.add('loading');
            submitBtn.querySelector('.btn-text').style.display = 'none';
            submitBtn.querySelector('.btn-loader').style.display = 'inline-block';
            submitBtn.disabled = true;
        }
        
        // Get form data
        const formData = new FormData(contactForm);
        const data = Object.fromEntries(formData);
        
        // ============================================
        // EmailJS Configuration
        // ============================================
        // SETUP INSTRUCTIONS:
        // 1. Go to https://dashboard.emailjs.com/ and create a free account
        // 2. Create an Email Service (Gmail, Outlook, etc.) and copy the Service ID
        // 3. Create an Email Template with these variables:
        //    - {{inquiry_type}}
        //    - {{first_name}}
        //    - {{last_name}}
        //    - {{email}}
        //    - {{phone}}
        //    - {{message}}
        //    - {{from_name}}
        //    - {{reply_to}}
        // 4. Copy the Template ID
        // 5. Go to Account > API Keys and copy your Public Key
        // 6. Replace the values below with your actual credentials
        // ============================================
        const EMAILJS_SERVICE_ID = 'service_z3j10gh';
        const EMAILJS_TEMPLATE_ID = 'template_fqewndp';
        const EMAILJS_PUBLIC_KEY = 'jR7yyMGVXt1m_xokq';
        
        // Initialize EmailJS (only if not already initialized)
        if (typeof emailjs !== 'undefined' && !window.emailjsInitialized) {
            emailjs.init(EMAILJS_PUBLIC_KEY);
            window.emailjsInitialized = true;
        }
        
        // Prepare email template parameters
        const inquiryTypeLabels = {
            'installation': 'Инсталация',
            'maintenance': 'Поддръжка',
            'repair': 'Ремонт',
            'consultation': 'Консултация',
            'other': 'Друго'
        };
        
        const templateParams = {
            inquiry_type: inquiryTypeLabels[data.inquiryType] || data.inquiryType,
            first_name: data.firstName,
            last_name: data.lastName,
            email: data.email,
            phone: data.phone || 'Не е предоставен',
            message: data.message,
            to_email: 'Bomiclima.office@gmail.com', // Your receiving email
            from_name: `${data.firstName} ${data.lastName}`,
            reply_to: data.email
        };
        
        // Send email via EmailJS
        try {
            if (typeof emailjs === 'undefined') {
                throw new Error('EmailJS не е зареден. Моля, проверете вашите настройки.');
            }
            
            await emailjs.send(EMAILJS_SERVICE_ID, EMAILJS_TEMPLATE_ID, templateParams);
            
            // Show success message
            contactForm.style.display = 'none';
            if (formSuccess) {
                formSuccess.style.display = 'block';
                formSuccess.classList.add('show');
                formSuccess.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
            
            // Reset form after showing success
            setTimeout(() => {
                contactForm.reset();
                contactForm.style.display = 'flex';
                if (formSuccess) {
                    formSuccess.style.display = 'none';
                    formSuccess.classList.remove('show');
                }
                // Reset character counter if exists
                const charCount = document.getElementById('charCount');
                if (charCount) {
                    charCount.textContent = '0';
                }
            }, 5000);
            
        } catch (error) {
            console.error('Error submitting form:', error);
            
            // Show user-friendly error message
            let errorMessage = 'Възникна грешка при изпращане на формата. ';
            
            if (error.text) {
                errorMessage += 'Моля, проверете вашите EmailJS настройки или опитайте отново.';
            } else if (EMAILJS_SERVICE_ID === 'YOUR_SERVICE_ID' || 
                      EMAILJS_TEMPLATE_ID === 'YOUR_TEMPLATE_ID' || 
                      EMAILJS_PUBLIC_KEY === 'YOUR_PUBLIC_KEY') {
                errorMessage += 'Моля, конфигурирайте EmailJS в script.js файла.';
            } else {
                errorMessage += 'Моля, опитайте отново по-късно.';
            }
            
            alert(errorMessage);
        } finally {
            // Reset button state
            if (submitBtn) {
                submitBtn.classList.remove('loading');
                submitBtn.querySelector('.btn-text').style.display = 'inline-block';
                submitBtn.querySelector('.btn-loader').style.display = 'none';
                submitBtn.disabled = false;
            }
        }
    });
});

// ============================================
// Gallery Sub-pages and Lightbox
// ============================================

let currentImageIndex = 0;
let galleryImages = [];

function initGallery(images) {
    galleryImages = images;
    const galleryGrid = document.getElementById('galleryGrid');
    
    if (!galleryGrid) return;
    
    // Clear existing content
    galleryGrid.innerHTML = '';
    
    // Create image items
    images.forEach((imageSrc, index) => {
        const imageItem = document.createElement('div');
        imageItem.className = 'gallery-image-item';
        imageItem.setAttribute('data-index', index);
        
        const img = document.createElement('img');
        img.src = imageSrc;
        img.alt = `Gallery image ${index + 1}`;
        img.loading = 'lazy';
        
        const overlay = document.createElement('div');
        overlay.className = 'gallery-image-overlay';
        overlay.innerHTML = '<i class="bi bi-zoom-in"></i>';
        
        imageItem.appendChild(img);
        imageItem.appendChild(overlay);
        
        // Add click event
        imageItem.addEventListener('click', () => {
            openLightbox(index);
        });
        
        galleryGrid.appendChild(imageItem);
        
        // Observe for animation
        animationObserver.observe(imageItem);
    });
}

function initGalleryWithInfo(projects) {
    // Extract image paths for lightbox
    galleryImages = projects.map(p => p.image);
    
    const galleryGrid = document.getElementById('galleryGrid');
    
    if (!galleryGrid) return;
    
    // Clear existing content
    galleryGrid.innerHTML = '';
    
    // Create project cards with info
    projects.forEach((project, index) => {
        const card = document.createElement('div');
        card.className = 'gallery-project-card';
        card.setAttribute('data-index', index);
        
        const imageWrapper = document.createElement('div');
        imageWrapper.className = 'gallery-project-image-wrapper';
        
        const img = document.createElement('img');
        img.src = project.image;
        img.alt = project.title;
        img.loading = 'lazy';
        
        const overlay = document.createElement('div');
        overlay.className = 'gallery-project-overlay';
        overlay.innerHTML = '<i class="bi bi-zoom-in"></i>';
        
        imageWrapper.appendChild(img);
        imageWrapper.appendChild(overlay);
        
        const info = document.createElement('div');
        info.className = 'gallery-project-info';
        
        const title = document.createElement('h3');
        title.className = 'gallery-project-title';
        title.textContent = project.title;
        
        const location = document.createElement('p');
        location.className = 'gallery-project-location';
        location.innerHTML = `<i class="bi bi-geo-alt-fill"></i> ${project.location}`;
        
        info.appendChild(title);
        info.appendChild(location);
        
        card.appendChild(imageWrapper);
        card.appendChild(info);
        
        // Add click event
        card.addEventListener('click', () => {
            openLightbox(index);
        });
        
        galleryGrid.appendChild(card);
        
        // Observe for animation
        animationObserver.observe(card);
    });
}

function openLightbox(index) {
    currentImageIndex = index;
    const lightbox = document.getElementById('lightbox');
    const lightboxImage = document.getElementById('lightboxImage');
    
    if (!lightbox || !lightboxImage) return;
    
    lightboxImage.src = galleryImages[index];
    lightboxImage.alt = `Gallery image ${index + 1}`;
    
    lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
    
    // Update navigation buttons visibility
    updateLightboxButtons();
}

function closeLightbox() {
    const lightbox = document.getElementById('lightbox');
    if (!lightbox) return;
    
    lightbox.classList.remove('active');
    document.body.style.overflow = '';
}

function showNextImage() {
    if (currentImageIndex < galleryImages.length - 1) {
        currentImageIndex++;
    } else {
        currentImageIndex = 0; // Loop to first image
    }
    updateLightboxImage();
}

function showPrevImage() {
    if (currentImageIndex > 0) {
        currentImageIndex--;
    } else {
        currentImageIndex = galleryImages.length - 1; // Loop to last image
    }
    updateLightboxImage();
}

function updateLightboxImage() {
    const lightboxImage = document.getElementById('lightboxImage');
    if (!lightboxImage) return;
    
    lightboxImage.src = galleryImages[currentImageIndex];
    lightboxImage.alt = `Gallery image ${currentImageIndex + 1}`;
    updateLightboxButtons();
}

function updateLightboxButtons() {
    const lightboxPrev = document.getElementById('lightboxPrev');
    const lightboxNext = document.getElementById('lightboxNext');
    
    // Always show buttons (we loop through images)
    if (lightboxPrev) lightboxPrev.style.display = 'flex';
    if (lightboxNext) lightboxNext.style.display = 'flex';
}

// Initialize lightbox event listeners
document.addEventListener('DOMContentLoaded', () => {
    const lightbox = document.getElementById('lightbox');
    const lightboxClose = document.getElementById('lightboxClose');
    const lightboxPrev = document.getElementById('lightboxPrev');
    const lightboxNext = document.getElementById('lightboxNext');
    
    if (lightboxClose) {
        lightboxClose.addEventListener('click', closeLightbox);
    }
    
    if (lightboxPrev) {
        lightboxPrev.addEventListener('click', showPrevImage);
    }
    
    if (lightboxNext) {
        lightboxNext.addEventListener('click', showNextImage);
    }
    
    // Close lightbox when clicking outside the image
    if (lightbox) {
        lightbox.addEventListener('click', (e) => {
            if (e.target === lightbox) {
                closeLightbox();
            }
        });
    }
    
    // Keyboard navigation
    document.addEventListener('keydown', (e) => {
        if (!lightbox || !lightbox.classList.contains('active')) return;
        
        if (e.key === 'Escape') {
            closeLightbox();
        } else if (e.key === 'ArrowLeft') {
            showPrevImage();
        } else if (e.key === 'ArrowRight') {
            showNextImage();
        }
    });
});

// ============================================
// Filter Section Collapse/Expand
// ============================================

document.addEventListener('DOMContentLoaded', () => {
    const filterHeaders = document.querySelectorAll('.filter-section-header');
    
    filterHeaders.forEach(header => {
        header.addEventListener('click', () => {
            const filterSection = header.closest('.filter-section');
            const isExpanded = header.getAttribute('aria-expanded') === 'true';
            
            // Toggle aria-expanded
            header.setAttribute('aria-expanded', !isExpanded);
            
            // Toggle collapsed class
            filterSection.classList.toggle('collapsed');
        });
    });
    
    // Initialize mobile filter drawer
    initMobileFilterDrawer();
    
    // Initialize "show more" functionality for long filter lists
    initFilterShowMore();
    
    // Initialize mobile category dropdown
    initMobileCategoryDropdown();
    
    // Initialize mobile sort functionality
    initMobileSort();
});

// ============================================
// Mobile Filter Drawer
// ============================================

function initMobileFilterDrawer() {
    const mobileFilterBtn = document.getElementById('mobileFilterBtn');
    const mobileFilterDrawer = document.getElementById('mobileFilterDrawer');
    const drawerClose = document.getElementById('drawerClose');
    const drawerOverlay = document.getElementById('drawerOverlay');
    const drawerBody = document.getElementById('drawerBody');
    const drawerReset = document.getElementById('drawerReset');
    const drawerApply = document.getElementById('drawerApply');
    const filtersSidebar = document.getElementById('filtersSidebar');
    
    if (!mobileFilterBtn || !mobileFilterDrawer) return;
    
    // Copy filter content to drawer on first open
    let drawerInitialized = false;
    
    function openDrawer() {
        if (!drawerInitialized && filtersSidebar && drawerBody) {
            // Clone the filter sidebar content
            const filterContent = filtersSidebar.cloneNode(true);
            filterContent.id = 'filtersSidebarDrawer';
            filterContent.classList.remove('filters-sidebar');
            filterContent.classList.add('drawer-filters');
            drawerBody.innerHTML = '';
            drawerBody.appendChild(filterContent);
            
            // Re-initialize accordions in drawer
            const drawerFilterHeaders = drawerBody.querySelectorAll('.filter-section-header');
            drawerFilterHeaders.forEach(header => {
                header.addEventListener('click', () => {
                    const filterSection = header.closest('.filter-section');
                    const isExpanded = header.getAttribute('aria-expanded') === 'true';
                    header.setAttribute('aria-expanded', !isExpanded);
                    filterSection.classList.toggle('collapsed');
                });
            });
            
            // Re-initialize show more in drawer
            initFilterShowMore(drawerBody);
            
            // Re-attach filter event listeners
            attachFilterListeners(drawerBody);
            
            drawerInitialized = true;
        }
        
        mobileFilterDrawer.classList.add('active');
        document.body.classList.add('drawer-open');
    }
    
    function closeDrawer() {
        mobileFilterDrawer.classList.remove('active');
        document.body.classList.remove('drawer-open');
    }
    
    // Open drawer
    mobileFilterBtn.addEventListener('click', openDrawer);
    
    // Close drawer
    if (drawerClose) {
        drawerClose.addEventListener('click', closeDrawer);
    }
    
    if (drawerOverlay) {
        drawerOverlay.addEventListener('click', closeDrawer);
    }
    
    // Reset filters
    if (drawerReset) {
        drawerReset.addEventListener('click', () => {
            // Reset all filters in drawer
            const drawerRadios = drawerBody.querySelectorAll('input[type="radio"]');
            const drawerCheckboxes = drawerBody.querySelectorAll('input[type="checkbox"]');
            
            drawerRadios.forEach(radio => {
                if (radio.value === 'all') {
                    radio.checked = true;
                } else {
                    radio.checked = false;
                }
            });
            
            drawerCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            
            // Also reset in main sidebar
            const mainRadios = filtersSidebar?.querySelectorAll('input[type="radio"]');
            const mainCheckboxes = filtersSidebar?.querySelectorAll('input[type="checkbox"]');
            
            if (mainRadios) {
                mainRadios.forEach(radio => {
                    if (radio.value === 'all') {
                        radio.checked = true;
                    } else {
                        radio.checked = false;
                    }
                });
            }
            
            if (mainCheckboxes) {
                mainCheckboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
            }
            
            // Apply filters
            if (typeof applyFilters === 'function') {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters([], category);
            }
        });
    }
    
    // Apply filters
    if (drawerApply) {
        drawerApply.addEventListener('click', () => {
            // Sync drawer filters to main sidebar
            if (filtersSidebar && drawerBody) {
                const drawerRadios = drawerBody.querySelectorAll('input[type="radio"]');
                const drawerCheckboxes = drawerBody.querySelectorAll('input[type="checkbox"]');
                
                drawerRadios.forEach(drawerRadio => {
                    const name = drawerRadio.name;
                    const value = drawerRadio.value;
                    const mainRadio = filtersSidebar.querySelector(`input[name="${name}"][value="${value}"]`);
                    if (mainRadio && drawerRadio.checked) {
                        mainRadio.checked = true;
                    }
                });
                
                drawerCheckboxes.forEach(drawerCheckbox => {
                    const name = drawerCheckbox.name;
                    const id = drawerCheckbox.id;
                    const mainCheckbox = filtersSidebar.querySelector(`input[name="${name}"]#${id}`);
                    if (mainCheckbox) {
                        mainCheckbox.checked = drawerCheckbox.checked;
                    }
                });
            }
            
            // Apply filters
            if (typeof applyFilters === 'function') {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters([], category);
            }
            
            closeDrawer();
        });
    }
    
    // Close drawer on escape key
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && mobileFilterDrawer.classList.contains('active')) {
            closeDrawer();
        }
    });
}

// ============================================
// Filter Show More Functionality
// ============================================

function initFilterShowMore(container = document) {
    const filterSections = container.querySelectorAll('.filter-section');
    
    filterSections.forEach(section => {
        const filterOptions = section.querySelectorAll('.filter-option');
        if (filterOptions.length <= 6) return; // Only apply to lists with more than 6 items
        
        // Hide items beyond the first 6
        filterOptions.forEach((option, index) => {
            if (index >= 6) {
                option.classList.add('filter-option-hidden');
            }
        });
        
        // Create "Show more" button if it doesn't exist
        let showMoreBtn = section.querySelector('.filter-show-more');
        if (!showMoreBtn) {
            showMoreBtn = document.createElement('button');
            showMoreBtn.className = 'filter-show-more';
            showMoreBtn.textContent = 'Покажи още';
            showMoreBtn.type = 'button';
            
            const filterOptionsContainer = section.querySelector('.filter-options');
            if (filterOptionsContainer) {
                filterOptionsContainer.appendChild(showMoreBtn);
            }
        }
        
        let isExpanded = false;
        
        showMoreBtn.addEventListener('click', () => {
            isExpanded = !isExpanded;
            
            if (isExpanded) {
                // Show all hidden options
                filterOptions.forEach(option => {
                    option.classList.remove('filter-option-hidden');
                    option.classList.add('show');
                });
                showMoreBtn.textContent = 'Покажи по-малко';
            } else {
                // Hide options beyond first 6
                filterOptions.forEach((option, index) => {
                    if (index >= 6) {
                        option.classList.add('filter-option-hidden');
                        option.classList.remove('show');
                    }
                });
                showMoreBtn.textContent = 'Покажи още';
            }
        });
    });
}

// ============================================
// Attach Filter Listeners (for drawer)
// ============================================

function attachFilterListeners(container) {
    // Brand filter
    const brandRadios = container.querySelectorAll('input[name="brand"]');
    brandRadios.forEach(radio => {
        radio.addEventListener('change', () => {
            if (typeof applyFilters === 'function') {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters([], category);
            }
        });
    });
    
    // Room size filter
    const roomSizeRadios = container.querySelectorAll('input[name="roomSize"]');
    roomSizeRadios.forEach(radio => {
        radio.addEventListener('change', () => {
            if (typeof applyFilters === 'function') {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters([], category);
            }
        });
    });
    
    // Promotional filters
    const promoPriceCheckbox = container.querySelector('#promoPrice');
    const promoInstallationCheckbox = container.querySelector('#promoInstallation');
    
    if (promoPriceCheckbox) {
        promoPriceCheckbox.addEventListener('change', () => {
            if (typeof applyFilters === 'function') {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters([], category);
            }
        });
    }
    
    if (promoInstallationCheckbox) {
        promoInstallationCheckbox.addEventListener('change', () => {
            if (typeof applyFilters === 'function') {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters([], category);
            }
        });
    }
}

// ============================================
// Mobile Category Dropdown
// ============================================

function initMobileCategoryDropdown() {
    const dropdownBtn = document.getElementById('categoryDropdownBtn');
    const dropdownMenu = document.getElementById('categoryDropdownMenu');
    const dropdownSelected = document.getElementById('categoryDropdownSelected');
    const dropdownContainer = document.querySelector('.category-dropdown-mobile');
    const categoryLinks = document.querySelectorAll('.category-dropdown-link');
    
    if (!dropdownBtn || !dropdownMenu) return;
    
    // Get current category from URL
    const urlParams = new URLSearchParams(window.location.search);
    const currentCategory = urlParams.get('category') || 'all';
    
    // Set initial selected text
    const activeLink = Array.from(categoryLinks).find(link => {
        const linkCategory = link.getAttribute('data-category') || 'all';
        return linkCategory === currentCategory;
    });
    
    if (activeLink) {
        dropdownSelected.textContent = activeLink.textContent.trim();
        activeLink.classList.add('active');
    }
    
    // Toggle dropdown
    dropdownBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        const isExpanded = dropdownBtn.getAttribute('aria-expanded') === 'true';
        dropdownBtn.setAttribute('aria-expanded', !isExpanded);
        dropdownContainer.classList.toggle('active');
    });
    
    // Close dropdown when clicking outside
    document.addEventListener('click', (e) => {
        if (!dropdownContainer.contains(e.target)) {
            dropdownBtn.setAttribute('aria-expanded', 'false');
            dropdownContainer.classList.remove('active');
        }
    });
    
    // Handle category selection
    categoryLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            
            // Update selected text
            dropdownSelected.textContent = link.textContent.trim();
            
            // Update active state
            categoryLinks.forEach(l => l.classList.remove('active'));
            link.classList.add('active');
            
            // Navigate to selected category
            window.location.href = link.getAttribute('href');
        });
    });
}

// ============================================
// Mobile Sort Functionality
// ============================================

function initMobileSort() {
    const sortPriceAsc = document.getElementById('sortPriceAsc');
    const sortPriceDesc = document.getElementById('sortPriceDesc');
    
    if (!sortPriceAsc || !sortPriceDesc) return;
    
    let currentSort = null; // 'asc' or 'desc'
    
    function sortProducts(sortOrder) {
        const productsGrid = document.getElementById('productsGrid');
        if (!productsGrid) return;
        
        const productCards = Array.from(productsGrid.querySelectorAll('.product-card'));
        if (productCards.length === 0) return;
        
        // Remove active class from both buttons
        sortPriceAsc.classList.remove('active');
        sortPriceDesc.classList.remove('active');
        
        // Sort products by price using data-price attribute
        productCards.sort((a, b) => {
            const priceA = parseFloat(a.getAttribute('data-price')) || 999999;
            const priceB = parseFloat(b.getAttribute('data-price')) || 999999;
            
            if (sortOrder === 'asc') {
                return priceA - priceB;
            } else {
                return priceB - priceA;
            }
        });
        
        // Re-append sorted cards
        productCards.forEach(card => {
            productsGrid.appendChild(card);
        });
        
        // Add active class to current button
        if (sortOrder === 'asc') {
            sortPriceAsc.classList.add('active');
        } else {
            sortPriceDesc.classList.add('active');
        }
        
        currentSort = sortOrder;
    }
    
    // Sort ascending
    sortPriceAsc.addEventListener('click', () => {
        if (currentSort === 'asc') {
            // If already sorted ascending, remove sort and reload
            sortPriceAsc.classList.remove('active');
            currentSort = null;
            if (typeof applyFilters === 'function' && window.filteredProducts) {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters(window.filteredProducts || window.allProducts || [], category);
            }
        } else {
            sortProducts('asc');
        }
    });
    
    // Sort descending
    sortPriceDesc.addEventListener('click', () => {
        if (currentSort === 'desc') {
            // If already sorted descending, remove sort and reload
            sortPriceDesc.classList.remove('active');
            currentSort = null;
            if (typeof applyFilters === 'function' && window.filteredProducts) {
                const urlParams = new URLSearchParams(window.location.search);
                const category = urlParams.get('category') || 'all';
                applyFilters(window.filteredProducts || window.allProducts || [], category);
            }
        } else {
            sortProducts('desc');
        }
    });
}

