// Initialize AOS (Animate On Scroll) with custom settings
document.addEventListener('DOMContentLoaded', function () {
    if (typeof AOS !== 'undefined') {
        AOS.init({
            duration: 600,
            easing: 'ease-out',
            once: true,
            offset: 50,
            delay: 0
        });
    }
});

// Mobile Navigation Toggle
const hamburger = document.getElementById('hamburger');
const navMenu = document.getElementById('navMenu');

if (hamburger && navMenu) {
    hamburger.addEventListener('click', () => {
        navMenu.classList.toggle('active');

        // Animate hamburger
        const spans = hamburger.querySelectorAll('span');
        if (navMenu.classList.contains('active')) {
            spans[0].style.transform = 'rotate(45deg) translateY(8px)';
            spans[1].style.opacity = '0';
            spans[2].style.transform = 'rotate(-45deg) translateY(-8px)';
        } else {
            spans[0].style.transform = 'none';
            spans[1].style.opacity = '1';
            spans[2].style.transform = 'none';
        }
    });

    // Close menu when clicking on a link (but not dropdown toggles)
    const navLinks = navMenu.querySelectorAll('a');
    navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            // Don't close menu if clicking on a dropdown toggle
            if (link.classList.contains('dropdown-toggle')) {
                return;
            }
            navMenu.classList.remove('active');
            const spans = hamburger.querySelectorAll('span');
            spans[0].style.transform = 'none';
            spans[1].style.opacity = '1';
            spans[2].style.transform = 'none';
        });
    });
}

// Gallery Filter Functionality
const filterButtons = document.querySelectorAll('.filter-btn');
const galleryItems = document.querySelectorAll('.gallery-item');

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

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

            galleryItems.forEach(item => {
                if (filterValue === 'all' || item.classList.contains(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);
                }
            });
        });
    });
}

// Initialize gallery items with transition
if (galleryItems.length > 0) {
    galleryItems.forEach(item => {
        item.style.transition = 'opacity 0.3s, transform 0.3s';
    });
}

// Contact Form Handling with Enhanced Validation
const contactForm = document.getElementById('contactForm');
if (contactForm) {
    // Get form fields
    const nameField = document.getElementById('contact-name');
    const emailField = document.getElementById('contact-email');
    const phoneField = document.getElementById('contact-phone');
    const messageField = document.getElementById('contact-message');

    // Get error message elements
    const nameError = document.getElementById('name-error');
    const emailError = document.getElementById('email-error');
    const phoneError = document.getElementById('phone-error');
    const messageError = document.getElementById('message-error');

    // Helper function to show error
    function showError(errorElement, message) {
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
    }

    // Helper function to clear error
    function clearError(errorElement) {
        if (errorElement) {
            errorElement.textContent = '';
            errorElement.style.display = 'none';
        }
    }

    // Real-time validation
    if (nameField) {
        nameField.addEventListener('blur', function () {
            const value = this.value.trim();
            if (!value) {
                showError(nameError, 'Name is required.');
                this.classList.add('error');
            } else if (value.length < 2) {
                showError(nameError, 'Name must be at least 2 characters long.');
                this.classList.add('error');
            } else {
                clearError(nameError);
                this.classList.remove('error');
            }
        });

        nameField.addEventListener('input', function () {
            if (this.value.trim().length >= 2) {
                clearError(nameError);
                this.classList.remove('error');
            }
        });
    }

    if (emailField) {
        emailField.addEventListener('blur', function () {
            const value = this.value.trim();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!value) {
                showError(emailError, 'Email is required.');
                this.classList.add('error');
            } else if (!emailRegex.test(value)) {
                showError(emailError, 'Please enter a valid email address.');
                this.classList.add('error');
            } else {
                clearError(emailError);
                this.classList.remove('error');
            }
        });

        emailField.addEventListener('input', function () {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (emailRegex.test(this.value.trim())) {
                clearError(emailError);
                this.classList.remove('error');
            }
        });
    }

    if (phoneField) {
        phoneField.addEventListener('blur', function () {
            const value = this.value.trim();
            const phoneRegex = /^[0-9+\s\-()]{10,15}$/;
            if (!value) {
                showError(phoneError, 'Phone number is required.');
                this.classList.add('error');
            } else if (!phoneRegex.test(value) || value.replace(/\D/g, '').length < 10) {
                showError(phoneError, 'Please enter a valid phone number (10-15 digits).');
                this.classList.add('error');
            } else {
                clearError(phoneError);
                this.classList.remove('error');
            }
        });

        phoneField.addEventListener('input', function () {
            const phoneRegex = /^[0-9+\s\-()]{10,15}$/;
            if (phoneRegex.test(this.value.trim()) && this.value.replace(/\D/g, '').length >= 10) {
                clearError(phoneError);
                this.classList.remove('error');
            }
        });
    }

    if (messageField) {
        messageField.addEventListener('blur', function () {
            const value = this.value.trim();
            if (!value) {
                showError(messageError, 'Message is required.');
                this.classList.add('error');
            } else if (value.length < 10) {
                showError(messageError, 'Message must be at least 10 characters long.');
                this.classList.add('error');
            } else {
                clearError(messageError);
                this.classList.remove('error');
            }
        });

        messageField.addEventListener('input', function () {
            if (this.value.trim().length >= 10) {
                clearError(messageError);
                this.classList.remove('error');
            }
        });
    }

    // Form submission validation
    contactForm.addEventListener('submit', (e) => {
        e.preventDefault();

        let isValid = true;

        // Clear all previous errors
        clearError(nameError);
        clearError(emailError);
        clearError(phoneError);
        clearError(messageError);

        // Remove error classes
        if (nameField) nameField.classList.remove('error');
        if (emailField) emailField.classList.remove('error');
        if (phoneField) phoneField.classList.remove('error');
        if (messageField) messageField.classList.remove('error');

        // Get form data
        const formData = new FormData(contactForm);
        const data = Object.fromEntries(formData);
        const name = data.name ? data.name.trim() : '';
        const email = data.email ? data.email.trim() : '';
        const phone = data.phone ? data.phone.trim() : '';
        const message = data.message ? data.message.trim() : '';

        // Validate Name
        if (!name) {
            showError(nameError, 'Name is required.');
            if (nameField) nameField.classList.add('error');
            isValid = false;
        } else if (name.length < 2) {
            showError(nameError, 'Name must be at least 2 characters long.');
            if (nameField) nameField.classList.add('error');
            isValid = false;
        }

        // Validate Email
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!email) {
            showError(emailError, 'Email is required.');
            if (emailField) emailField.classList.add('error');
            isValid = false;
        } else if (!emailRegex.test(email)) {
            showError(emailError, 'Please enter a valid email address.');
            if (emailField) emailField.classList.add('error');
            isValid = false;
        }

        // Validate Phone
        const phoneRegex = /^[0-9+\s\-()]{10,15}$/;
        const phoneDigits = phone.replace(/\D/g, '');
        if (!phone) {
            showError(phoneError, 'Phone number is required.');
            if (phoneField) phoneField.classList.add('error');
            isValid = false;
        } else if (!phoneRegex.test(phone) || phoneDigits.length < 10) {
            showError(phoneError, 'Please enter a valid phone number (10-15 digits).');
            if (phoneField) phoneField.classList.add('error');
            isValid = false;
        }

        // Validate Message
        if (!message) {
            showError(messageError, 'Message is required.');
            if (messageField) messageField.classList.add('error');
            isValid = false;
        } else if (message.length < 10) {
            showError(messageError, 'Message must be at least 10 characters long.');
            if (messageField) messageField.classList.add('error');
            isValid = false;
        }

        // If validation fails, scroll to first error
        if (!isValid) {
            const firstError = contactForm.querySelector('.error');
            if (firstError) {
                firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstError.focus();
            }
            return;
        }

        // If all validations pass, submit the form
        // In a real application, you would send this data to a server
        // For now, we'll just show a success message
        alert('Thank you for your message! We will get back to you soon.');
        contactForm.reset();

        // Clear all errors after successful submission
        clearError(nameError);
        clearError(emailError);
        clearError(phoneError);
        clearError(messageError);
    });
}

// Smooth Scroll for Anchor Links (same-page only)
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        // Only prevent default for same-page anchors
        const href = this.getAttribute('href');
        if (href && href.startsWith('#') && !href.includes('.html')) {
            e.preventDefault();
            const target = document.querySelector(href);
            if (target) {
                const navbar = document.querySelector('.navbar');
                const navbarHeight = navbar ? navbar.offsetHeight : 0;
                const elementPosition = target.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - navbarHeight - 20;

                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
            }
        }
    });
});

// Handle anchor navigation from other pages (cross-page anchor links)
function scrollToAnchor(force = false) {
    const hash = window.location.hash;
    if (hash) {
        // Remove the # from the hash
        const targetId = hash.substring(1);

        // Function to attempt scrolling with retries
        function attemptScroll(retries = 20) {
            const targetElement = document.getElementById(targetId);

            if (targetElement) {
                // Get navbar height for offset
                const navbar = document.querySelector('.navbar');
                const navbarHeight = navbar ? navbar.offsetHeight : 0;

                // Calculate scroll position
                let elementTop = targetElement.offsetTop;

                // If element is inside a positioned parent, adjust
                let parent = targetElement.offsetParent;
                while (parent && parent !== document.body) {
                    elementTop += parent.offsetTop;
                    parent = parent.offsetParent;
                }

                const offsetPosition = elementTop - navbarHeight - 20;
                const targetScroll = Math.max(0, offsetPosition);

                // Check if we're already at the right position (within 50px)
                const currentScroll = window.pageYOffset || document.documentElement.scrollTop;
                if (!force && Math.abs(currentScroll - targetScroll) < 50) {
                    return true; // Already at the right position
                }

                // Scroll to the element
                window.scrollTo({
                    top: targetScroll,
                    behavior: force ? 'auto' : 'smooth'
                });
                return true; // Success
            } else if (retries > 0) {
                // Element not found yet, retry after a short delay
                setTimeout(() => attemptScroll(retries - 1), 100);
                return false;
            }
            return false; // Failed after all retries
        }

        // Start attempting to scroll
        attemptScroll();
    }
}

// Run on page load - use multiple strategies to ensure it works
function initAnchorScroll() {
    // Check if we have a hash in the URL
    if (window.location.hash) {
        // First, try to prevent default browser scroll by scrolling to top immediately
        window.scrollTo(0, 0);

        // Try after a short delay to let the page start loading
        setTimeout(() => {
            scrollToAnchor(true); // Force scroll
        }, 150);

        // Also try after DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                setTimeout(() => scrollToAnchor(true), 250);
            });
        } else {
            // DOM already loaded, try again
            setTimeout(() => scrollToAnchor(true), 250);
        }

        // Also try after window fully loads (including images and other resources)
        window.addEventListener('load', () => {
            setTimeout(() => scrollToAnchor(), 400);
        });

        // Final check after everything should be loaded
        setTimeout(() => {
            scrollToAnchor();
        }, 1000);
    }
}

// Initialize anchor scrolling when script loads
initAnchorScroll();

// Also handle hash changes after page load (for same-page navigation)
window.addEventListener('hashchange', () => {
    setTimeout(() => scrollToAnchor(), 100);
});

// Add active class to current page in navigation
const currentPage = window.location.pathname.split('/').pop() || 'index.html';
const navLinks = document.querySelectorAll('.nav-menu a');
navLinks.forEach(link => {
    const linkPage = link.getAttribute('href');
    if (linkPage === currentPage || (currentPage === '' && linkPage === 'index.html')) {
        link.classList.add('active');
    }
});

// Intersection Observer for Fade-in 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);

// Observe elements for animation
document.querySelectorAll('.stat-item, .sector-card, .feature-item').forEach(el => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(20px)';
    el.style.transition = 'opacity 0.6s, transform 0.6s';
    observer.observe(el);
});

// Hero Slider Auto-scroll with Curved Arc Effect - 9 Visible Images
const sliderTrack = document.querySelector('.slider-track');
const sliderWrapper = document.querySelector('.slider-wrapper');
const sliderCards = document.querySelectorAll('.slider-card');

if (sliderTrack && sliderCards.length > 0 && sliderWrapper) {
    // Clone cards for seamless infinite loop
    const originalCards = Array.from(sliderCards);

    // Duplicate the entire set multiple times for seamless looping
    // Create at least 3 copies to ensure smooth continuous scrolling
    for (let i = 0; i < 3; i++) {
        originalCards.forEach(card => {
            const clone = card.cloneNode(true);
            sliderTrack.appendChild(clone);
        });
    }

    const allCards = sliderTrack.querySelectorAll('.slider-card');

    // Function to update card styles based on position (curved arc effect)
    // Center images are largest, edges are smaller and rotated
    function updateCardStyles() {
        const wrapperRect = sliderWrapper.getBoundingClientRect();
        const wrapperCenter = wrapperRect.left + wrapperRect.width / 2;
        // Calculate max distance for 9 visible images (4.5 images on each side)
        const cardWidth = originalCards[0]?.offsetWidth || 200;
        const gap = 10;
        const maxDistance = (cardWidth + gap) * 4.5;

        allCards.forEach((card) => {
            const cardRect = card.getBoundingClientRect();
            const cardCenter = cardRect.left + cardRect.width / 2;
            const distanceFromCenter = Math.abs(cardCenter - wrapperCenter);
            const normalizedDistance = Math.min(distanceFromCenter / maxDistance, 1);

            // Curved arc: center images are largest (scale 1.0), edges are smaller (scale 0.7)
            const sizeScale = 1.0 - (normalizedDistance * 0.3);

            // Rotation: center images have no rotation, edges rotate outward
            const maxRotation = 35; // Maximum rotation angle in degrees
            const rotation = normalizedDistance * maxRotation;
            const rotationDirection = cardCenter < wrapperCenter ? -1 : 1;

            // Depth: center images are closer (translateZ 0), edges are further back
            const maxDepth = -200; // Maximum depth in pixels
            const depth = normalizedDistance * maxDepth;

            // Z-index: center images are on top
            const zIndex = Math.round(100 - normalizedDistance * 80);

            // Apply transforms for curved arc effect
            card.style.transform = `translate3d(0, 0, ${depth}px) scale(${sizeScale}) rotateY(${rotation * rotationDirection}deg)`;
            card.style.zIndex = zIndex;
        });
    }

    // Calculate exact width for seamless looping
    setTimeout(() => {
        // Wait for layout to be complete
        const firstCard = originalCards[0];
        const cardWidth = firstCard.offsetWidth;
        const gap = 10;

        // Calculate the exact width of one complete set (including gaps)
        // Formula: (cardWidth + gap) * numberOfCards - gap (last card doesn't have gap after it)
        const originalSetWidth = (cardWidth + gap) * originalCards.length - gap;

        // Animation should move exactly one set width to loop seamlessly
        const animationDistance = -originalSetWidth;

        // Update CSS animation dynamically for seamless loop
        const styleId = 'slider-animation-style';
        let styleEl = document.getElementById(styleId);
        if (!styleEl) {
            styleEl = document.createElement('style');
            styleEl.id = styleId;
            document.head.appendChild(styleEl);
        }
        styleEl.textContent = `
            @keyframes slideRightToLeft {
                0% {
                    transform: translateX(0) translateZ(0);
                }
                100% {
                    transform: translateX(${animationDistance}px) translateZ(0);
                }
            }
        `;

        // Reset and apply animation for seamless loop
        sliderTrack.style.animation = 'none';
        sliderTrack.style.transform = 'translateX(0) translateZ(0)';

        // Force reflow to ensure reset is applied
        void sliderTrack.offsetHeight;

        // Apply animation: slower, smoother movement (12 images = 24 seconds)
        requestAnimationFrame(() => {
            sliderTrack.style.animation = 'slideRightToLeft 24s linear infinite';
        });
    }, 150);

    // Update styles on animation frame (throttled for performance)
    let lastUpdate = 0;
    let rafId = null;
    let isVisible = true;
    function animateStyles(timestamp) {
        if (!isVisible) {
            rafId = null;
            return;
        }
        if (timestamp - lastUpdate >= 16) { // ~60fps
            updateCardStyles();
            lastUpdate = timestamp;
        }
        rafId = requestAnimationFrame(animateStyles);
    }
    animateStyles(0);

    // Optimize: Use Intersection Observer to pause updates when slider is not visible
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            isVisible = entry.isIntersecting;
            if (!isVisible && rafId) {
                cancelAnimationFrame(rafId);
                rafId = null;
            } else if (isVisible && !rafId) {
                animateStyles(performance.now());
            }
        });
    }, { threshold: 0.1 });

    if (sliderWrapper) {
        observer.observe(sliderWrapper);
    }
}

// Confetti Animation for Intro Section
const introSection = document.querySelector('.intro-section');
const confettiCanvas = document.getElementById('confetti-canvas');

if (introSection && confettiCanvas) {
    let confettiAnimationId = null;
    let confettiParticles = [];
    let hasPlayed = false;

    // Set canvas size
    function resizeCanvas() {
        const rect = introSection.getBoundingClientRect();
        confettiCanvas.width = rect.width;
        confettiCanvas.height = rect.height;
    }

    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    const ctx = confettiCanvas.getContext('2d');

    // Confetti particle class
    class ConfettiParticle {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this.size = Math.random() * 5 + 2;
            // Increased horizontal spread for wider area coverage
            this.speedX = (Math.random() - 0.5) * 12;
            this.speedY = Math.random() * 3 + 2;
            this.color = ['#6366F1', '#A855F7', '#EC4899', '#F59E0B', '#10B981', '#3B82F6', '#EF4444'][Math.floor(Math.random() * 7)];
            this.rotation = Math.random() * 360;
            this.rotationSpeed = (Math.random() - 0.5) * 10;
            this.gravity = 0.1;
        }

        update() {
            this.x += this.speedX;
            this.y += this.speedY;
            this.speedY += this.gravity;
            this.rotation += this.rotationSpeed;
        }

        draw() {
            ctx.save();
            ctx.translate(this.x, this.y);
            ctx.rotate((this.rotation * Math.PI) / 180);
            ctx.fillStyle = this.color;
            ctx.fillRect(-this.size / 2, -this.size / 2, this.size, this.size);
            ctx.restore();
        }
    }

    // Create confetti particles
    function createConfetti() {
        const h2Element = introSection.querySelector('h2');
        if (!h2Element) return;

        // Get h2 position relative to the intro-section
        const sectionRect = introSection.getBoundingClientRect();
        const h2Rect = h2Element.getBoundingClientRect();

        // Calculate h2 center position relative to canvas
        const centerX = h2Rect.left - sectionRect.left + (h2Rect.width / 2);
        const centerY = h2Rect.top - sectionRect.top + (h2Rect.height / 2);

        const particleCount = 200; // Increased particle count for wider spread

        for (let i = 0; i < particleCount; i++) {
            const angle = (Math.PI * 2 * i) / particleCount;
            // Increased distance for wider spread across the container
            const distance = Math.random() * 150 + 20;
            const x = centerX + Math.cos(angle) * distance;
            const y = centerY + Math.sin(angle) * distance;
            confettiParticles.push(new ConfettiParticle(x, y));
        }
    }

    // Animation loop
    function animateConfetti() {
        ctx.clearRect(0, 0, confettiCanvas.width, confettiCanvas.height);

        for (let i = confettiParticles.length - 1; i >= 0; i--) {
            const particle = confettiParticles[i];
            particle.update();
            particle.draw();

            // Remove particles that are out of bounds
            if (particle.y > confettiCanvas.height + 50 ||
                particle.x < -50 ||
                particle.x > confettiCanvas.width + 50) {
                confettiParticles.splice(i, 1);
            }
        }

        if (confettiParticles.length > 0) {
            confettiAnimationId = requestAnimationFrame(animateConfetti);
        } else {
            confettiAnimationId = null;
        }
    }

    // Intersection Observer to trigger confetti
    const confettiObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting && !hasPlayed) {
                hasPlayed = true;
                resizeCanvas();
                createConfetti();
                animateConfetti();
            }
        });
    }, { threshold: 0.3 });

    confettiObserver.observe(introSection);
}

// Testimonials Carousel
const testimonialsCarousel = document.querySelector('.testimonials-carousel');
const testimonialCards = document.querySelectorAll('.testimonial-card');
let currentIndex = 0;
let autoRotateInterval = null;

if (testimonialsCarousel && testimonialCards.length > 0) {
    // Function to update card positions
    function updateCardPositions() {
        testimonialCards.forEach((card, originalIndex) => {
            // Calculate relative position from current front card
            const relativePosition = (originalIndex - currentIndex + testimonialCards.length) % testimonialCards.length;

            // Update transform based on relative position
            switch (relativePosition) {
                case 0:
                    card.style.transform = 'translateX(0) translateZ(0) scale(1)';
                    card.style.zIndex = '4';
                    card.style.opacity = '1';
                    break;
                case 1:
                    card.style.transform = 'translateX(80px) translateZ(-50px) scale(0.9)';
                    card.style.zIndex = '3';
                    card.style.opacity = '0.8';
                    break;
                case 2:
                    card.style.transform = 'translateX(160px) translateZ(-100px) scale(0.8)';
                    card.style.zIndex = '2';
                    card.style.opacity = '0.6';
                    break;
                case 3:
                    card.style.transform = 'translateX(240px) translateZ(-150px) scale(0.7)';
                    card.style.zIndex = '1';
                    card.style.opacity = '0.4';
                    break;
            }
        });
    }

    // Function to move to next card
    function moveToNext() {
        currentIndex = (currentIndex + 1) % testimonialCards.length;
        updateCardPositions();
    }

    // Click handler to bring card to front
    testimonialCards.forEach((card, originalIndex) => {
        card.addEventListener('click', () => {
            // Calculate relative position
            const relativePosition = (originalIndex - currentIndex + testimonialCards.length) % testimonialCards.length;

            if (relativePosition !== 0) {
                // Move clicked card to front
                currentIndex = originalIndex;
                updateCardPositions();

                // Reset auto-rotate timer
                clearInterval(autoRotateInterval);
                autoRotateInterval = setInterval(moveToNext, 4000);
            }
        });
    });

    // Initialize positions
    updateCardPositions();

    // Auto-rotate every 4 seconds
    autoRotateInterval = setInterval(moveToNext, 4000);

    // Pause on hover
    testimonialsCarousel.addEventListener('mouseenter', () => {
        clearInterval(autoRotateInterval);
    });

    testimonialsCarousel.addEventListener('mouseleave', () => {
        autoRotateInterval = setInterval(moveToNext, 4000);
    });
}

// Product Category Navigation
const productCategories = document.querySelectorAll('.product-category[data-category]');

productCategories.forEach(category => {
    category.addEventListener('click', (e) => {
        const sector = category.getAttribute('data-sector');
        const categoryName = category.getAttribute('data-category');
        const galleryUrl = `gallery-${sector}-${categoryName}.html`;
        window.location.href = galleryUrl;
    });
});

// Branch Data
const branchData = {
    branch1: {
        phone: "+91 70122 16787",
        email: "Mktrading.ka@gmail.com",
        whatsapp: "+91 7012103160",
        office: "Near KSEB office, Cherkala. Kasaragod 671541"
    },
    branch2: {
        phone: "+91 8590442966",
        email: "Mktrading.ka@gmail.com",
        whatsapp: "+91 73061 04974",
        office: "I-180(5), Pallathur Adoor Road, Ishwaramangala, Nettanigemudnoor, Dakshina Kannada , Karnataka, 674313"
    }
};

// Product Card WhatsApp Link
const productGallerySection = document.querySelector('.product-gallery-section');
if (productGallerySection) {
    const productCards = productGallerySection.querySelectorAll('.product-card[data-product-id]');

    productCards.forEach(card => {
        card.addEventListener('click', (e) => {
            e.preventDefault();

            // Get product information from data attributes
            const productId = card.getAttribute('data-product-id') || '';
            const productTitle = card.getAttribute('data-product-title') || '';
            const productBrand = card.getAttribute('data-product-brand') || '';
            const productPrice = card.getAttribute('data-product-price') || '';

            // Get selected branch from sessionStorage or default to branch1
            const selectedBranch = sessionStorage.getItem('selectedBranch') || 'branch1';
            const whatsappNumber = branchData[selectedBranch]?.whatsapp || branchData.branch1.whatsapp;

            // Remove spaces and special characters from phone number for WhatsApp URL
            const cleanPhoneNumber = whatsappNumber.replace(/\s+/g, '').replace(/[^0-9+]/g, '');

            // Create WhatsApp message
            let message = `Hello, I'm interested in the following product:\n\n`;
            message += `Product: ${productTitle}\n`;
            if (productId) {
                message += `Code: ${productId}\n`;
            }
            if (productBrand) {
                message += `Brand: ${productBrand}\n`;
            }
            if (productPrice) {
                message += `Price: ${productPrice}\n`;
            }
            message += `Status: active`;

            // Encode message for URL
            const encodedMessage = encodeURIComponent(message);

            // Create WhatsApp URL
            const whatsappUrl = `https://wa.me/${cleanPhoneNumber}?text=${encodedMessage}`;

            // Open WhatsApp in a new window
            window.open(whatsappUrl, '_blank');
        });
    });
}

// Home Dropdown - Refresh page on branch selection (hover dropdown)
const homeBranchOptions = document.querySelectorAll('.home-dropdown .branch-option');
homeBranchOptions.forEach(option => {
    option.addEventListener('click', (e) => {
        e.preventDefault();
        const branch = option.getAttribute('data-branch');
        // Store branch selection in sessionStorage
        sessionStorage.setItem('selectedBranch', branch);
        // Refresh the page
        window.location.reload();
    });
});

// Contact Us and CTA Dropdown - Show contact section and update content
const contactBranchOptions = document.querySelectorAll('.branch-option-contact');
const contactSection = document.querySelector('.contact-section');
const contactDetails = document.querySelectorAll('.contact-details');

contactBranchOptions.forEach(option => {
    option.addEventListener('click', (e) => {
        e.preventDefault();
        const branch = option.getAttribute('data-branch');

        // Store branch selection in sessionStorage
        sessionStorage.setItem('selectedBranch', branch);

        // Update contact details based on selected branch
        if (branchData[branch]) {
            const details = branchData[branch];
            const detailElements = Array.from(contactDetails);

            // Update Phone Number
            if (detailElements[0]) {
                detailElements[0].querySelector('p').textContent = details.phone;
            }

            // Update Email Address
            if (detailElements[1]) {
                detailElements[1].querySelector('p').textContent = details.email;
            }

            // Update Whatsapp
            if (detailElements[2]) {
                detailElements[2].querySelector('p').textContent = details.whatsapp;
            }

            // Update Office Address
            if (detailElements[3]) {
                detailElements[3].querySelector('p').textContent = details.office;
            }
        }

        // Update map based on selected branch
        const branchMaps = document.querySelectorAll('.branch-map');
        branchMaps.forEach(map => {
            if (map.getAttribute('data-branch') === branch) {
                map.style.display = 'block';
            } else {
                map.style.display = 'none';
            }
        });

        // Show contact section
        // Show contact section
        if (contactSection) {
            contactSection.style.display = 'block';
            contactSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } else {
            // Redirect to the dedicated contact page
            window.location.href = 'contact.php#contact-branch';
            return;
        }

        // Close dropdown
        const dropdown = option.closest('.dropdown');
        if (dropdown) {
            dropdown.classList.remove('dropdown-open');
        }

        // Close mobile menu after selecting a branch (on mobile screens)
        const navMenu = document.getElementById('navMenu');
        const hamburger = document.getElementById('hamburger');
        if (navMenu && hamburger && window.innerWidth <= 1022) {
            navMenu.classList.remove('active');
            const spans = hamburger.querySelectorAll('span');
            if (spans) {
                spans[0].style.transform = 'none';
                spans[1].style.opacity = '1';
                spans[2].style.transform = 'none';
            }
        }
    });
});

// Click dropdown toggle for all dropdowns (Sectors, Contact Us, and CTA buttons)
const allDropdowns = document.querySelectorAll('.dropdown');
allDropdowns.forEach(dropdown => {
    const toggle = dropdown.querySelector('.dropdown-toggle');
    if (toggle) {
        toggle.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation(); // Prevent event from bubbling up
            // Toggle dropdown
            const isOpen = dropdown.classList.contains('dropdown-open');
            document.querySelectorAll('.dropdown').forEach(d => d.classList.remove('dropdown-open'));
            if (!isOpen) {
                dropdown.classList.add('dropdown-open');
            }
        });
    }

    // Close dropdown when clicking on a dropdown menu item
    const dropdownItems = dropdown.querySelectorAll('.dropdown-menu a');
    dropdownItems.forEach(item => {
        item.addEventListener('click', () => {
            dropdown.classList.remove('dropdown-open');
            // Close mobile menu after navigation
            if (navMenu) {
                navMenu.classList.remove('active');
                const spans = hamburger?.querySelectorAll('span');
                if (spans) {
                    spans[0].style.transform = 'none';
                    spans[1].style.opacity = '1';
                    spans[2].style.transform = 'none';
                }
            }
        });
    });
});

// Close dropdowns when clicking outside
document.addEventListener('click', (e) => {
    if (!e.target.closest('.dropdown')) {
        document.querySelectorAll('.dropdown').forEach(d => d.classList.remove('dropdown-open'));
    }
});

// Load branch data on page load - default to Branch1 if no branch is stored
window.addEventListener('DOMContentLoaded', () => {
    const storedBranch = sessionStorage.getItem('selectedBranch');
    const branchToLoad = storedBranch && branchData[storedBranch] ? storedBranch : 'branch1';
    const details = branchData[branchToLoad];
    const detailElements = Array.from(document.querySelectorAll('.contact-details'));

    if (details && detailElements.length >= 4) {
        detailElements[0].querySelector('p').textContent = details.phone;
        detailElements[1].querySelector('p').textContent = details.email;
        detailElements[2].querySelector('p').textContent = details.whatsapp;
        detailElements[3].querySelector('p').textContent = details.office;
    }

    // Show appropriate map based on selected branch
    const branchMaps = document.querySelectorAll('.branch-map');
    branchMaps.forEach(map => {
        if (map.getAttribute('data-branch') === branchToLoad) {
            map.style.display = 'block';
        } else {
            map.style.display = 'none';
        }
    });
});

// WhatsApp Widget
// (function () {
//     // Create WhatsApp widget HTML
//     const whatsappWidget = document.createElement('div');
//     whatsappWidget.className = 'whatsapp-widget';
//     whatsappWidget.innerHTML = `
//         <div class="whatsapp-icon" id="whatsappIcon">
//             <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
//                 <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
//             </svg>
//         </div>
//         <div class="whatsapp-chatbox" id="whatsappChatbox">
//             <div class="chatbox-header">
//                 <div class="chatbox-header-info">
//                     <div class="chatbox-avatar">MK</div>
//                     <div class="chatbox-header-text">
//                         <h3>MK Trading Company</h3>
//                         <p>Typically replies within minutes</p>
//                     </div>
//                 </div>
//                 <button class="chatbox-close" id="chatboxClose">
//                     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
//                         <line x1="18" y1="6" x2="6" y2="18"></line>
//                         <line x1="6" y1="6" x2="18" y2="18"></line>
//                     </svg>
//                 </button>
//             </div>
//             <div class="chatbox-messages" id="chatboxMessages">
//                 <div class="chatbox-welcome">
//                     <p>👋 Hello! Welcome to MK Trading Company. How can we help you today?</p>
//                 </div>
//             </div>
//             <div class="chatbox-input-area">
//                 <input type="text" class="chatbox-input" id="chatboxInput" placeholder="Type a message...">
//                 <button class="chatbox-send" id="chatboxSend">
//                     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
//                         <line x1="22" y1="2" x2="11" y2="13"></line>
//                         <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
//                     </svg>
//                 </button>
//             </div>
//         </div>
//     `;
//     document.body.appendChild(whatsappWidget);

//     // Get selected branch from sessionStorage or default to branch1
//     const getWhatsAppNumber = () => {
//         const selectedBranch = sessionStorage.getItem('selectedBranch') || 'branch1';
//         return branchData[selectedBranch]?.whatsapp || branchData.branch1.whatsapp;
//     };

//     // Format phone number for WhatsApp URL
//     const formatPhoneNumber = (phone) => {
//         return phone.replace(/\s+/g, '').replace(/[^0-9+]/g, '');
//     };

//     // Get current time
//     const getCurrentTime = () => {
//         const now = new Date();
//         return now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
//     };

//     // Add message to chatbox
//     const addMessage = (text, isReceived = false) => {
//         const messagesContainer = document.getElementById('chatboxMessages');
//         const messageDiv = document.createElement('div');
//         messageDiv.className = `chatbox-message ${isReceived ? 'received' : 'sent'}`;
//         messageDiv.innerHTML = `
//             <div>${text}</div>
//             <div class="chatbox-message-time">${getCurrentTime()}</div>
//         `;
//         messagesContainer.appendChild(messageDiv);
//         messagesContainer.scrollTop = messagesContainer.scrollHeight;
//     };

//     // Toggle chatbox
//     const toggleChatbox = () => {
//         const chatbox = document.getElementById('whatsappChatbox');
//         chatbox.classList.toggle('active');
//         if (chatbox.classList.contains('active')) {
//             document.getElementById('chatboxInput').focus();
//         }
//     };

//     // Send message
//     const sendMessage = () => {
//         const input = document.getElementById('chatboxInput');
//         const message = input.value.trim();

//         if (message) {
//             addMessage(message, false);
//             input.value = '';

//             // Simulate auto-reply after 1 second
//             setTimeout(() => {
//                 addMessage('Thank you for your message! We will get back to you shortly. For immediate assistance, please contact us directly on WhatsApp.', true);
//             }, 1000);
//         }
//     };

//     // Open WhatsApp with message
//     const openWhatsApp = (message = '') => {
//         const whatsappNumber = getWhatsAppNumber();
//         const cleanPhoneNumber = formatPhoneNumber(whatsappNumber);
//         const defaultMessage = message || 'Hello, I would like to know more about your products and services.';
//         const encodedMessage = encodeURIComponent(defaultMessage);
//         const whatsappUrl = `https://wa.me/${cleanPhoneNumber}?text=${encodedMessage}`;
//         window.open(whatsappUrl, '_blank');
//     };

//     // Event listeners
//     document.getElementById('whatsappIcon').addEventListener('click', toggleChatbox);
//     document.getElementById('chatboxClose').addEventListener('click', toggleChatbox);
//     document.getElementById('chatboxSend').addEventListener('click', () => {
//         const input = document.getElementById('chatboxInput');
//         const message = input.value.trim();
//         if (message) {
//             sendMessage();
//             // Also open WhatsApp with the message
//             setTimeout(() => {
//                 openWhatsApp(message);
//             }, 500);
//         }
//     });

//     // Send on Enter key
//     document.getElementById('chatboxInput').addEventListener('keypress', (e) => {
//         if (e.key === 'Enter') {
//             const input = document.getElementById('chatboxInput');
//             const message = input.value.trim();
//             if (message) {
//                 sendMessage();
//                 setTimeout(() => {
//                     openWhatsApp(message);
//                 }, 500);
//             }
//         }
//     });
// })();

// Job Application Form - Handle button clicks in job listings
document.addEventListener('DOMContentLoaded', function () {
    const jobListingButtons = document.querySelectorAll('.job-listing .btn-primary');

    

    // Handle file input change to show file name
    const fileInput = document.getElementById('applicantResume');
    const fileName = document.getElementById('fileName');

    if (fileInput && fileName) {
        fileInput.addEventListener('change', function (e) {
            if (this.files && this.files.length > 0) {
                fileName.textContent = this.files[0].name;
            } else {
                fileName.textContent = 'No file chosen';
            }
        });
    }

    // Handle form submission
    const jobApplicationForm = document.getElementById('jobApplicationForm');
    if (jobApplicationForm) {
        jobApplicationForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const formData = new FormData(this);
            const jobTitle = sessionStorage.getItem('jobTitle') || 'General Application';

            // Create email subject and body
            const subject = encodeURIComponent(`Application for ${jobTitle}`);
            const body = encodeURIComponent(
                `Application Details:\n\n` +
                `Name: ${formData.get('name')}\n` +
                `Email: ${formData.get('email')}\n` +
                `Phone: ${formData.get('phone')}\n` +
                `Position: ${jobTitle}\n\n` +
                `Resume attached.`
            );

            // Create mailto link
            const mailtoLink = `mailto:careers@mktradingcompany.com?subject=${subject}&body=${body}`;

            // Open email client
            window.location.href = mailtoLink;

            // Show success message
            alert('Thank you for your application! Your email client will open to send your application. Please attach your resume file.');
        });
    }
});

