/* ================================
MOBILE MENU
================================ */
const mobileToggle = document.getElementById('mobileToggle');
const navMenu = document.getElementById('navMenu');
const body = document.body;
if (mobileToggle && navMenu) {
    mobileToggle.addEventListener('click', (e) => {
        e.stopPropagation();
        mobileToggle.classList.toggle('active');
        navMenu.classList.toggle('active');
        body.style.overflow = navMenu.classList.contains('active') ? 'hidden' : '';
    });
}
const navMenuLinks = document.querySelectorAll('.nav-menu a');
if (navMenuLinks.length > 0) {
    navMenuLinks.forEach(link => {
        link.addEventListener('click', () => {
            if (mobileToggle) mobileToggle.classList.remove('active');
            if (navMenu) navMenu.classList.remove('active');
            body.style.overflow = '';
        });
    });
}
document.addEventListener('click', (e) => {
    if (
        navMenu?.classList.contains('active') &&
        !navMenu.contains(e.target) &&
        mobileToggle && !mobileToggle.contains(e.target)
    ) {
        mobileToggle.classList.remove('active');
        navMenu.classList.remove('active');
        body.style.overflow = '';
    }
});

/* ================================
ABSOLUTE → STICKY HEADER LOGIC
================================ */
const header = document.querySelector('.header-wrapper');
const banner = document.querySelector('.page-banner');
if (header && banner) {
    const stickyTrigger = banner.offsetHeight - 120;
    window.addEventListener('scroll', () => {
        if (window.scrollY > stickyTrigger) {
            header.classList.add('is-sticky', 'scrolled');
        } else {
            header.classList.remove('is-sticky', 'scrolled');
        }
    });
}

/* ================================
GSAP SAFE INIT
================================ */
if (typeof gsap !== "undefined" && typeof ScrollTrigger !== "undefined") {
    gsap.registerPlugin(ScrollTrigger);
    const letsElement = document.getElementById("lets");
    const talknowElement = document.getElementById("talknow");

    if (letsElement) {
        gsap.to("#lets", {
            opacity: 1,
            y: 0,
            duration: 1.7,
            ease: "power3.out",
            scrollTrigger: {
                trigger: "#lets",
                start: "top 90%"
            }
        });
    }

    if (talknowElement) {
        gsap.to("#talknow", {
            opacity: 1,
            y: 0,
            duration: 2,
            ease: "power3.out",
            delay: 0.2,
            scrollTrigger: {
                trigger: "#talknow",
                start: "top 90%"
            }
        });
    }
}

/* ================================
WORK SLIDER
================================ */
(function() {
    const workSlides = document.querySelectorAll('.slide');
    const workTotal = workSlides.length;

    if (workTotal === 0) return;

    const positions = ['pos-0', 'pos-1', 'pos-2', 'pos-3', 'pos-4'];
    let workStartIndex = 0;

    function renderWorkSlider() {
        workSlides.forEach((slide, i) => {
            const posIndex = (i + workStartIndex) % workTotal;
            slide.className = 'slide ' + positions[posIndex];
        });
    }

    renderWorkSlider();

    setInterval(() => {
        workStartIndex = (workStartIndex + 1) % workTotal;
        renderWorkSlider();
    }, 3800);

    // Dots functionality
    window.addEventListener('DOMContentLoaded', function() {
        const dotContainer = document.querySelector('.slider-dots');
        if (!dotContainer) return;

        for (let i = 0; i < 5; i++) {
            const dotEl = document.createElement('div');
            dotEl.className = 'dot';
            if (i === 0) dotEl.classList.add('active');

            dotEl.onclick = function() {
                workStartIndex = i;
                renderWorkSlider();

                document.querySelectorAll('.dot').forEach(d => d.classList.remove('active'));
                dotEl.classList.add('active');
            };

            dotContainer.appendChild(dotEl);
        }

        setInterval(() => {
            const currentDot = workStartIndex % workTotal;
            document.querySelectorAll('.dot').forEach((d, idx) => {
                d.classList.toggle('active', idx === currentDot);
            });
        }, 100);
    });
})();

/* ================================
BOOK CALL SCROLL TEXT
================================ */
(function() {
    const el = document.querySelector('[data-scroll-text]');
    if (!el) return;

    const originalText = el.textContent.trim();

    function splitWords() {
        el.innerHTML = '';
        originalText.split(/\s+/).forEach(word => {
            const span = document.createElement('span');
            span.textContent = word + ' ';
            el.appendChild(span);
        });
    }

    splitWords();

    function updateFill() {
        const spans = el.querySelectorAll('span');
        const rect = el.getBoundingClientRect();
        const vh = window.innerHeight;

        const start = vh * 0.9;
        const end = vh * 0.6;

        let progress = (start - rect.top) / (start - end);
        progress = Math.max(0, Math.min(1, progress));

        const active = Math.floor(progress * spans.length);

        spans.forEach((span, i) => {
            span.style.color = i < active ? 'rgba(255,255,255,1)' : 'rgba(255,255,255,0.25)';
        });
    }

    window.addEventListener('scroll', updateFill);
    window.addEventListener('resize', updateFill);
    updateFill();
})();

/* ================================
SERVICE TECH ACCORDION
================================ */
(function() {
    const serviceTechItems = document.querySelectorAll('.service-tech-item');
    if (serviceTechItems.length === 0) return;

    serviceTechItems.forEach(item => {
        const header = item.querySelector('.service-tech-header');
        if (!header) return;

        header.addEventListener('mouseenter', function() {
            serviceTechItems.forEach(otherItem => {
                if (otherItem !== item) {
                    otherItem.classList.remove('active');
                }
            });
            item.classList.add('active');
        });
    });
})();

/* ================================
TESTIMONIALS STICKY
================================ */
document.addEventListener("DOMContentLoaded", () => {
    const section = document.getElementById("testimonial");
    const sticky = document.getElementById("stickyLeft");
    const wrapper = document.getElementById("leftWrapper");

    if (!section || !sticky || !wrapper) return;

    const OFFSET = 140;
    const STICKY_DELAY = 120;

    let lockedWidth, lockedHeight;

    function init() {
        lockedWidth = wrapper.offsetWidth;
        lockedHeight = sticky.offsetHeight;
        wrapper.style.minHeight = lockedHeight + "px";
    }

    function onScroll() {
        if (window.innerWidth < 992) return;

        const sectionTop = section.offsetTop;
        const sectionBottom = sectionTop + section.offsetHeight;
        const scrollY = window.scrollY;

        const start = sectionTop - OFFSET + STICKY_DELAY;
        const end = sectionBottom - lockedHeight - OFFSET;

        if (scrollY >= start && scrollY <= end) {
            sticky.classList.add("left-fixed");
            sticky.classList.remove("left-stop");
            sticky.style.width = lockedWidth + "px";
        } else if (scrollY > end) {
            sticky.classList.remove("left-fixed");
            sticky.classList.add("left-stop");
            sticky.style.width = "100%";
        } else {
            sticky.classList.remove("left-fixed", "left-stop");
            sticky.style.width = "auto";
        }
    }

    init();
    window.addEventListener("scroll", onScroll);
    window.addEventListener("resize", () => {
        init();
        onScroll();
    });
});

/* ================================
BLOG MOBILE SLIDER
================================ */
(function() {
    let currentBlogSlide = 0;
    const blogSlider = document.getElementById('mobileSlider');
    const blogDotsContainer = document.getElementById('sliderDots');

    if (!blogSlider || !blogDotsContainer) return;

    const blogCards = blogSlider.querySelectorAll('.blog-card');
    const totalBlogSlides = blogCards.length;

    if (totalBlogSlides === 0) return;

    // Create dots
    for (let i = 0; i < totalBlogSlides; i++) {
        const dot = document.createElement('div');
        dot.className = 'slider-dot' + (i === 0 ? ' active' : '');
        dot.addEventListener('click', () => goToBlogSlide(i));
        blogDotsContainer.appendChild(dot);
    }

    function updateBlogSlider() {
        const cardWidth = blogCards[0].offsetWidth;
        const gap = 20;
        const offset = -(currentBlogSlide * (cardWidth + gap));
        blogSlider.style.transform = `translateX(${offset}px)`;

        const dots = blogDotsContainer.querySelectorAll('.slider-dot');
        dots.forEach((dot, index) => {
            dot.classList.toggle('active', index === currentBlogSlide);
        });
    }

    function goToBlogSlide(index) {
        currentBlogSlide = index;
        updateBlogSlider();
    }

    // Touch/Swipe support
    let touchStartX = 0;
    let touchEndX = 0;

    blogSlider.addEventListener('touchstart', (e) => {
        touchStartX = e.changedTouches[0].screenX;
    });

    blogSlider.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].screenX;
        handleBlogSwipe();
    });

    function handleBlogSwipe() {
        if (touchStartX - touchEndX > 50 && currentBlogSlide < totalBlogSlides - 1) {
            currentBlogSlide++;
            updateBlogSlider();
        }

        if (touchEndX - touchStartX > 50 && currentBlogSlide > 0) {
            currentBlogSlide--;
            updateBlogSlider();
        }
    }

    // Auto-play
    let blogAutoplayInterval;

    function startBlogAutoplay() {
        blogAutoplayInterval = setInterval(() => {
            currentBlogSlide = (currentBlogSlide + 1) % totalBlogSlides;
            updateBlogSlider();
        }, 5000);
    }

    function stopBlogAutoplay() {
        clearInterval(blogAutoplayInterval);
    }

    if (window.innerWidth <= 767) {
        startBlogAutoplay();
        blogSlider.addEventListener('touchstart', stopBlogAutoplay);
    }
})();

/* ================================
ABOUT US TAB
================================ */
(function() {
    const aboutTabs = document.querySelectorAll('.about-tabs .nav-link');
    const aboutImage = document.getElementById('aboutTabImage');
    const aboutCaption = document.querySelector('.about-image-wrapper .image-caption');

    if (aboutTabs.length === 0 || !aboutImage || !aboutCaption) return;

    aboutTabs.forEach(tab => {
        tab.addEventListener('shown.bs.tab', function() {
            const newImage = this.dataset.image;
            const newCaption = this.dataset.caption;

            aboutImage.style.opacity = '0';
            aboutCaption.style.opacity = '0';

            setTimeout(() => {
                if (newImage) aboutImage.src = newImage;
                if (newCaption) aboutCaption.textContent = newCaption;

                aboutImage.style.opacity = '1';
                aboutCaption.style.opacity = '1';
            }, 200);
        });
    });
})();

/* ================================
TEAM GALLERY
================================ */
(function() {
    const teamGallerySlider = document.querySelector('.team-gallery-slider');
    const teamGalleryDotsContainer = document.getElementById('teamGalleryDotsContainer');

    if (!teamGallerySlider || !teamGalleryDotsContainer) return;

    let teamGalleryCurrentIndex = 0;

    function initTeamGallerySlider() {
        const slides = document.querySelectorAll('.team-gallery-slide-item');
        if (slides.length === 0) return;

        slides.forEach((slide, index) => {
            const dot = document.createElement('div');
            dot.className = 'team-gallery-dot-indicator';
            dot.addEventListener('click', () => goToTeamGallerySlide(index));
            teamGalleryDotsContainer.appendChild(dot);

            slide.addEventListener('click', () => goToTeamGallerySlide(index));
        });
        updateTeamGallerySlider();
    }

    function updateTeamGallerySlider() {
        const slides = document.querySelectorAll('.team-gallery-slide-item');
        const dots = document.querySelectorAll('.team-gallery-dot-indicator');
        const total = slides.length;

        slides.forEach((slide, index) => {
            slide.classList.remove('tgs-active', 'tgs-left', 'tgs-right', 'tgs-hidden');
            if (index === teamGalleryCurrentIndex) {
                slide.classList.add('tgs-active');
            } else if (index === (teamGalleryCurrentIndex - 1 + total) % total) {
                slide.classList.add('tgs-left');
            } else if (index === (teamGalleryCurrentIndex + 1) % total) {
                slide.classList.add('tgs-right');
            } else {
                slide.classList.add('tgs-hidden');
            }
        });

        dots.forEach((dot, index) => {
            dot.classList.toggle('tgs-dot-active', index === teamGalleryCurrentIndex);
        });
    }

    function goToTeamGallerySlide(index) {
        teamGalleryCurrentIndex = index;
        updateTeamGallerySlider();
    }

    document.addEventListener('keydown', (e) => {
        const slides = document.querySelectorAll('.team-gallery-slide-item');
        if (slides.length === 0) return;

        if (e.key === 'ArrowLeft') {
            teamGalleryCurrentIndex = (teamGalleryCurrentIndex - 1 + slides.length) % slides.length;
            updateTeamGallerySlider();
        } else if (e.key === 'ArrowRight') {
            teamGalleryCurrentIndex = (teamGalleryCurrentIndex + 1) % slides.length;
            updateTeamGallerySlider();
        }
    });

    let teamGalleryAutoPlay = setInterval(() => {
        const slides = document.querySelectorAll('.team-gallery-slide-item');
        if (slides.length === 0) return;
        teamGalleryCurrentIndex = (teamGalleryCurrentIndex + 1) % slides.length;
        updateTeamGallerySlider();
    }, 4000);

    teamGallerySlider.addEventListener('mouseenter', () => {
        clearInterval(teamGalleryAutoPlay);
    });

    teamGallerySlider.addEventListener('mouseleave', () => {
        teamGalleryAutoPlay = setInterval(() => {
            const slides = document.querySelectorAll('.team-gallery-slide-item');
            if (slides.length === 0) return;
            teamGalleryCurrentIndex = (teamGalleryCurrentIndex + 1) % slides.length;
            updateTeamGallerySlider();
        }, 4000);
    });

    initTeamGallerySlider();
})();

/* ================================
OUR WORK PORTFOLIO SECTION
================================ */
(function() {
    const filterTabs = document.querySelectorAll('.filter-tab');
    const portfolioCards = document.querySelectorAll('.portfolio-card');
    const seeMoreBtn = document.getElementById('seeMoreBtn');
    const hiddenCards = document.getElementById('hiddenCards');
    const btnText = document.getElementById('btnText');

    if (!filterTabs.length || !portfolioCards.length || !seeMoreBtn || !hiddenCards || !btnText) {
        return;
    }

    let portfolioExpanded = false;

    function checkPortfolioSeeMoreButton() {
        const allCards = document.querySelectorAll('.portfolio-card');
        const hiddenVisibleCards = Array.from(hiddenCards.querySelectorAll('.portfolio-card')).filter(card => {
            return card.style.display !== 'none';
        });

        if (hiddenVisibleCards.length > 0) {
            seeMoreBtn.classList.add('visible');
        } else {
            seeMoreBtn.classList.remove('visible');
        }
    }

    filterTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const filter = tab.dataset.filter;

            filterTabs.forEach(t => t.classList.remove('active'));
            tab.classList.add('active');

            portfolioExpanded = false;
            hiddenCards.classList.remove('show');
            btnText.textContent = 'SEE MORE';
            seeMoreBtn.classList.remove('active');

            portfolioCards.forEach((card, index) => {
                card.style.animation = 'none';

                setTimeout(() => {
                    if (filter === 'all' || card.dataset.categories.includes(filter)) {
                        card.style.display = 'block';
                        card.style.animation = `fadeInUp 0.6s ease ${index * 0.1}s forwards`;
                    } else {
                        card.style.display = 'none';
                    }
                }, 10);
            });

            setTimeout(() => {
                checkPortfolioSeeMoreButton();
            }, 50);
        });
    });

    seeMoreBtn.addEventListener('click', () => {
        portfolioExpanded = !portfolioExpanded;

        if (portfolioExpanded) {
            hiddenCards.classList.add('show');
            btnText.textContent = 'SEE LESS';
            seeMoreBtn.classList.add('active');

            const newCards = hiddenCards.querySelectorAll('.portfolio-card');
            newCards.forEach((card, index) => {
                if (card.style.display !== 'none') {
                    card.style.animation = `fadeInUp 0.6s ease ${index * 0.1}s forwards`;
                }
            });
        } else {
            hiddenCards.classList.remove('show');
            btnText.textContent = 'SEE MORE';
            seeMoreBtn.classList.remove('active');

            const portfolioGrid = document.getElementById('portfolioGrid');
            if (portfolioGrid) {
                portfolioGrid.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        }
    });

    checkPortfolioSeeMoreButton();
})();

/* ================================
ABOUT TIMELINE
================================ */
(function() {
    const yearInfos = document.querySelectorAll('.year-info');
    const yearImages = document.querySelectorAll('.year-img img');
    
    if (yearInfos.length === 0) return;

    class TimelineScroller {
        constructor() {
            this.yearInfos = yearInfos;
            this.yearImages = yearImages;
            this.currentYear = 1;
            this.previousYear = null;
            this.ticking = false;
            this.init();
        }
        init() {
            this.setActiveYear(1);
            window.addEventListener('scroll', () => {
                if (!this.ticking) {
                    requestAnimationFrame(() => {
                        this.handleScroll();
                        this.ticking = false;
                    });
                    this.ticking = true;
                }
            });
            this.handleScroll();
        }
        handleScroll() {
            const viewportHeight = window.innerHeight;
            const triggerPoint = viewportHeight * 0.45;
            this.yearInfos.forEach((yearInfo) => {
                const rect = yearInfo.getBoundingClientRect();
                const year = parseInt(yearInfo.dataset.year);
                if (rect.top <= triggerPoint && rect.bottom >= triggerPoint) {
                    if (this.currentYear !== year) {
                        this.previousYear = this.currentYear;
                        this.setActiveYear(year);
                    }
                }
            });
        }
        setActiveYear(year) {
            this.currentYear = year;
            this.yearInfos.forEach(info => {
                const infoYear = parseInt(info.dataset.year);
                if (infoYear === year) {
                    info.classList.add('active');
                } else {
                    info.classList.remove('active');
                }
            });
            this.yearImages.forEach(img => {
                const imgYear = parseInt(img.dataset.year);
                if (imgYear === year) {
                    img.classList.remove('exit');
                    setTimeout(() => {
                        img.classList.add('active');
                    }, 50);
                } else if (imgYear === this.previousYear) {
                    img.classList.remove('active');
                    img.classList.add('exit');
                    setTimeout(() => {
                        img.classList.remove('exit');
                    }, 700);
                } else {
                    img.classList.remove('active', 'exit');
                }
            });
        }
    }
    
    document.addEventListener('DOMContentLoaded', () => {
        new TimelineScroller();
    });
})();

/* ================================
SERVICE INNER FAQ
================================ */
(function() {
    const faqItems = document.querySelectorAll('.service-child-faq .faq-item');
    
    if (faqItems.length === 0) return;

    function closeFaq(item) {
        const body = item.querySelector('.faq-body');
        const icon = item.querySelector('.faq-icon');

        icon.textContent = '+';
        body.style.height = body.scrollHeight + 'px';

        requestAnimationFrame(() => {
            body.style.height = 0;
        });

        item.classList.remove('active');
    }

    function openFaq(item) {
        const body = item.querySelector('.faq-body');
        const icon = item.querySelector('.faq-icon');

        item.classList.add('active');
        icon.textContent = '−';
        body.style.height = body.scrollHeight + 'px';
    }

    faqItems.forEach(item => {
        const head = item.querySelector('.faq-head');

        head.addEventListener('click', () => {
            faqItems.forEach(faq => {
                if (faq !== item && faq.classList.contains('active')) {
                    closeFaq(faq);
                }
            });

            if (item.classList.contains('active')) {
                closeFaq(item);
            } else {
                openFaq(item);
            }
        });
    });

    window.addEventListener('load', () => {
        const activeItem = document.querySelector('.service-child-faq .faq-item.active');
        if (activeItem) {
            const body = activeItem.querySelector('.faq-body');
            const icon = activeItem.querySelector('.faq-icon');

            icon.textContent = '−';
            body.style.height = body.scrollHeight + 'px';
        }
    });
})();

/* ================================
BLOG PAGE
================================ */
document.addEventListener("DOMContentLoaded", () => {
    const items = [...document.querySelectorAll(".blog-item")];
    const pagination = document.getElementById("pagination");
    const sidebar = document.getElementById("blogSidebar");
    const main = document.getElementById("blogMain");
    const container = document.getElementById("blogContainer");
    
    if (!pagination || !sidebar || !main || !container || items.length === 0) {
        return;
    }
    
    let perPage = 9;
    let page = 1;
    
    document.querySelectorAll(".view-toggle .btn").forEach(btn => {
        btn.onclick = () => {
            document.querySelectorAll(".view-toggle .btn").forEach(b => b.classList.remove("active"));
            btn.classList.add("active");
            
            const isList = btn.dataset.view === "list";
            
            perPage = isList ? 4 : 9;
            page = 1;
            
            items.forEach(i => {
                i.classList.toggle("col-lg-4", !isList);
                i.classList.toggle("col-md-6", !isList);
                i.classList.toggle("col-12", isList);
            });
            
            container.classList.toggle("list-view-active", isList);
            sidebar.classList.toggle("hide-sidebar", !isList);
            main.className = isList ? "col-lg-9" : "col-lg-12";
            
            showPage(page);
        };
    });
    
    function showPage(p) {
        page = p;
        items.forEach((item, i) => {
            item.style.display = (i >= (p - 1) * perPage && i < p * perPage) ? "" : "none";
        });
        renderPagination();
    }
    
    function renderPagination() {
        pagination.innerHTML = "";
        const total = Math.ceil(items.length / perPage);
        for (let i = 1; i <= total; i++) {
            pagination.innerHTML += `
            <li class="page-item ${i === page ? 'active' : ''}">
            <a href="#" class="page-link">${i}</a>
            </li>`;
        }
        [...pagination.children].forEach((li, i) => {
            li.onclick = e => { e.preventDefault(); showPage(i + 1); }
        });
    }
    
    showPage(1);
});

/* ================================
CAREER SLIDER
================================ */
(function() {
    const careerSlider = document.querySelector('.career-slider');
    if (!careerSlider) return;
    
    const sliderRows = careerSlider.querySelectorAll('.slider-row');
    
    sliderRows.forEach(row => {
        row.addEventListener('mouseenter', () => {
            row.classList.add('paused');
        });
        
        row.addEventListener('mouseleave', () => {
            row.classList.remove('paused');
        });
    });
})();

/* ================================
PROJECT GALLERY SLIDER
================================ */
(function() {
    const projectGallerySlider = document.querySelector('.project-gallery-slider');
    const projectGalleryDotsContainer = document.getElementById('projectGalleryDots');
    
    if (!projectGallerySlider || !projectGalleryDotsContainer) return;
    
    let projectGalleryCurrentIndex = 0;
    let projectGalleryAutoPlay;

    function initProjectGallerySlider() {
        const slides = document.querySelectorAll('.project-gallery-slide');
        if (slides.length === 0) return;

        slides.forEach((slide, index) => {
            const dot = document.createElement('div');
            dot.className = 'project-gallery-dot';
            dot.addEventListener('click', () => goToProjectGallerySlide(index));
            projectGalleryDotsContainer.appendChild(dot);

            slide.addEventListener('click', () => {
                if (slide.classList.contains('pgs-left')) {
                    goToProjectGallerySlide((projectGalleryCurrentIndex - 1 + slides.length) % slides.length);
                } else if (slide.classList.contains('pgs-right')) {
                    goToProjectGallerySlide((projectGalleryCurrentIndex + 1) % slides.length);
                }
            });
        });

        updateProjectGallerySlider();
    }

    function updateProjectGallerySlider() {
        const slides = document.querySelectorAll('.project-gallery-slide');
        const dots = document.querySelectorAll('.project-gallery-dot');
        const total = slides.length;

        slides.forEach((slide, index) => {
            slide.classList.remove('pgs-active', 'pgs-left', 'pgs-right', 'pgs-hidden');
            
            if (index === projectGalleryCurrentIndex) {
                slide.classList.add('pgs-active');
            } else if (index === (projectGalleryCurrentIndex - 1 + total) % total) {
                slide.classList.add('pgs-left');
            } else if (index === (projectGalleryCurrentIndex + 1) % total) {
                slide.classList.add('pgs-right');
            } else {
                slide.classList.add('pgs-hidden');
            }
        });

        dots.forEach((dot, index) => {
            dot.classList.toggle('pgs-dot-active', index === projectGalleryCurrentIndex);
        });
    }

    function goToProjectGallerySlide(index) {
        projectGalleryCurrentIndex = index;
        updateProjectGallerySlider();
    }

    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');

    if (prevBtn) {
        prevBtn.addEventListener('click', () => {
            const slides = document.querySelectorAll('.project-gallery-slide');
            projectGalleryCurrentIndex = (projectGalleryCurrentIndex - 1 + slides.length) % slides.length;
            updateProjectGallerySlider();
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', () => {
            const slides = document.querySelectorAll('.project-gallery-slide');
            projectGalleryCurrentIndex = (projectGalleryCurrentIndex + 1) % slides.length;
            updateProjectGallerySlider();
        });
    }

    document.addEventListener('keydown', (e) => {
        const slides = document.querySelectorAll('.project-gallery-slide');
        if (slides.length === 0) return;

        if (e.key === 'ArrowLeft') {
            projectGalleryCurrentIndex = (projectGalleryCurrentIndex - 1 + slides.length) % slides.length;
            updateProjectGallerySlider();
        } else if (e.key === 'ArrowRight') {
            projectGalleryCurrentIndex = (projectGalleryCurrentIndex + 1) % slides.length;
            updateProjectGallerySlider();
        }
    });

    function startAutoPlay() {
        projectGalleryAutoPlay = setInterval(() => {
            const slides = document.querySelectorAll('.project-gallery-slide');
            if (slides.length === 0) return;
            projectGalleryCurrentIndex = (projectGalleryCurrentIndex + 1) % slides.length;
            updateProjectGallerySlider();
        }, 3000);
    }

    projectGallerySlider.addEventListener('mouseenter', () => {
        clearInterval(projectGalleryAutoPlay);
    });

    projectGallerySlider.addEventListener('mouseleave', () => {
        startAutoPlay();
    });

    initProjectGallerySlider();
    startAutoPlay();
})();