document.addEventListener("DOMContentLoaded", () => {
	
	const header = document.querySelector('.site-header');
	const showAfter = 1;

	function handleHeader() {
		if (!header) return; // FIX: guard in case markup changes again
		if (window.scrollY > showAfter) {
			header.classList.add("show");
		} else {
			header.classList.remove("show");
		}
	}
	window.addEventListener("scroll", handleHeader);
	handleHeader();

	const heroLogo = document.querySelector('.hero-content img');

	if (heroLogo) {

		window.addEventListener('scroll', () => {

			const rect = heroLogo.getBoundingClientRect();

			const startFade = 150;
			const endFade = 16;

			let progress = (rect.top - endFade) / (startFade - endFade);

			progress = Math.max(0, Math.min(1, progress));

			heroLogo.style.opacity = progress;
			heroLogo.style.transform = `scale(${progress})`;

		});

	}

	const menuTrigger = document.querySelector('.menu-trigger');
	const sidebar = document.querySelector('.sidebar');
	const overlay = document.querySelector('.sidebar-overlay');

	function closeSidebar() {
		if (!menuTrigger || !sidebar || !overlay) return;
		menuTrigger.classList.remove('active');
		sidebar.classList.remove('show');
		overlay.classList.remove('show');
	}

	if (menuTrigger && sidebar && overlay) {
		menuTrigger.addEventListener('click', () => {
			menuTrigger.classList.toggle('active');
			sidebar.classList.toggle('show');
			overlay.classList.toggle('show');
		});
		overlay.addEventListener('click', closeSidebar);
	}

	document.addEventListener('keydown', (e) => {
		if (e.key === 'Escape') {
			closeSidebar();
		}
	});

	document.querySelectorAll('.submenu-trigger').forEach(trigger => {
		trigger.addEventListener('click', () => {
			const submenu = trigger.nextElementSibling;
			if (!submenu) return; // FIX: guard missing sibling
			submenu.classList.toggle('show');
			trigger.classList.toggle('active');
		});
	});

	document.querySelectorAll('.featured-services').forEach(section => {
		const track = section.querySelector('.featured-track');
		if (!track) return;

		function setSectionHeight() {
			const horizontalDistance =
				track.scrollWidth - window.innerWidth;
			section.style.height =
				`${window.innerHeight + horizontalDistance}px`;
		}

		function updateHorizontalScroll() {
			const sectionTop = section.offsetTop;
			const scrollPosition =
				window.scrollY - sectionTop;
			const maxTranslate =
				track.scrollWidth - window.innerWidth;
			const translateX = Math.min(
				Math.max(scrollPosition, 0),
				maxTranslate
			);
			if (section.classList.contains('featured-services-reverse')) {
				track.style.transform =
					`translateX(${translateX - maxTranslate}px)`;
			} else {
				track.style.transform =
					`translateX(-${translateX}px)`;
			}
		}
		setSectionHeight();
		window.addEventListener(
			'resize',
			setSectionHeight
		);
		window.addEventListener(
			'scroll',
			updateHorizontalScroll
		);
		updateHorizontalScroll();
	});

	const workBlock = document.querySelector('#workBlock');
	const workImage = document.querySelector('.work-bg img');
	const workSteps = document.querySelectorAll('.work-step');
	window.addEventListener('scroll', () => {
		if (!workBlock || !workImage) return; // FIX: also guard workImage
		const rect = workBlock.getBoundingClientRect();
		const totalScroll =
			workBlock.offsetHeight - window.innerHeight;

		
		if (totalScroll <= 0) return;

		const progress =
			Math.min(
				Math.max(
					-rect.top / totalScroll,
					0
				),
				1
			);
		
		workImage.style.transform =
			`scale(${1 + progress * 0.35})
translateY(${progress * 80}px)`;
		
		const currentStep =
			Math.min(
				workSteps.length - 1,
				Math.floor(progress * workSteps.length)
			);
		workSteps.forEach((step, index) => {
			step.classList.toggle(
				'active',
				index === currentStep
			);
		});
	});

	/* =========================================
	SCROLL DRIVEN SERVICES ANIMATION
	========================================= */
	const timelineItems =
		document.querySelectorAll('.timeline-item');

	function animateTimelineCards() {
		timelineItems.forEach((item, index) => {
			const card =
				item.querySelector('.timeline-card');
			if (!card) return; // FIX: guard missing card
			const rect =
				item.getBoundingClientRect();
			const viewportHeight =
				window.innerHeight;
			
			
			let progress =
				(viewportHeight - rect.top) /
				(viewportHeight + rect.height);
			progress =
				Math.max(
					0,
					Math.min(progress, 1)
				);
			
			const startOffset = 50;
			const direction =
				index % 2 === 0 ? -1 : 1;
			const translateX =
				direction *
				startOffset *
				(1 - progress);
			const scale =
				0.9 + (progress * 0.1);
			const opacity =
				progress +
                0.5;
			card.style.transform =
				`
translateX(${translateX}px)
scale(${scale})
`;
			card.style.opacity =
				opacity;
		});
	}
	window.addEventListener(
		'scroll',
		animateTimelineCards
	);
	window.addEventListener(
		'resize',
		animateTimelineCards
	);
	animateTimelineCards();

	/* ==========================
	Accessories Scale Effect
	========================== */
	const accessoriesBlock =
		document.querySelector('#accessoriesBlock');
	window.addEventListener('scroll', () => {
		if (!accessoriesBlock) return;
		const accessoriesImage =
			accessoriesBlock.querySelector('img');
		if (!accessoriesImage) return; // FIX: guard missing image
		const rect =
			accessoriesBlock.getBoundingClientRect();
		const viewportHeight =
			window.innerHeight;
		const progress =
			Math.min(
				Math.max(
					(viewportHeight - rect.top) /
					(viewportHeight + rect.height),
					0
				),
				1
			);
		const scale =
			1 - (progress * 0.15);
		accessoriesImage.style.transform =
			`scale(${scale})`;
	});

	/* =========================================
	FABRIC COLLECTION SCROLL REVEAL
	========================================= */
	const fabricSection =
		document.querySelector('#fabricCollection');
	if (fabricSection) {
		const fabricElements = [
			fabricSection.querySelector('.fabric-label'),
			fabricSection.querySelector('h2'),
			fabricSection.querySelector('p'),
			fabricSection.querySelector('.fabric-brands'),
			fabricSection.querySelector('a')
		].filter(Boolean); // FIX: drop any selector that didn't match instead of throwing later

		function animateFabricSection() {
			const rect =
				fabricSection.getBoundingClientRect();
			const viewportHeight =
				window.innerHeight;
			
				
			let progress =
				(viewportHeight - rect.top) /
				(viewportHeight * 0.9);
			progress =
				Math.max(
					0,
					Math.min(progress, 1)
				);
			fabricElements.forEach((element, index) => {
				
				
				const delay =
					index * 0.12;
				const localProgress =
					Math.max(
						0,
						Math.min(
							(progress - delay) /
							(1 - delay),
							1
						)
					);
				const translateY =
					100 * (1 - localProgress);
				const opacity =
					localProgress;
				element.style.transform =
					`translateY(${translateY}px)`;
				element.style.opacity =
					opacity;
			});
		}
		window.addEventListener(
			'scroll',
			animateFabricSection
		);
		window.addEventListener(
			'resize',
			animateFabricSection
		);
		animateFabricSection();
	}

	/* ==========================================
	TESTIMONIAL SLIDER
	========================================== */
	const testimonialSlider =
		document.querySelector(".testimonial-slider");
	if (testimonialSlider) {
		const slides =
			testimonialSlider.querySelectorAll(".testimonial-slide");
		const nextBtn =
			testimonialSlider.querySelector(".testimonial-next");
		const prevBtn =
			testimonialSlider.querySelector(".testimonial-prev");
		const progressBar =
			testimonialSlider.querySelector(
				".testimonial-progress span"
			);
		const currentSlideText =
			testimonialSlider.querySelector(
				".current-slide"
			);
		const totalSlidesText =
			testimonialSlider.querySelector(
				".total-slides"
			);
		let currentIndex = 0;
		let autoplay;
		const slideDuration = 6000;
		/* ==========================================
		COUNTER
		========================================== */
		if (totalSlidesText) {
			totalSlidesText.textContent =
				String(slides.length).padStart(2, "0");
		}

		function updateCounter() {
			if (!currentSlideText) return;
			currentSlideText.textContent =
				String(currentIndex + 1).padStart(2, "0");
		}
		/* ==========================================
		PROGRESS BAR
		========================================== */
		function restartProgress() {
			if (!progressBar) return;
			progressBar.style.transition = "none";
			progressBar.style.width = "0%";
			progressBar.offsetWidth;
			progressBar.style.transition =
				`width ${slideDuration}ms linear`;
			progressBar.style.width = "100%";
		}
		/* ==========================================
		SHOW SLIDE
		========================================== */
		function showSlide(index) {
			if (!slides.length) return; // FIX: guard empty slide list
			if (index < 0) {
				index = slides.length - 1;
			}
			if (index >= slides.length) {
				index = 0;
			}
			slides.forEach(slide => {
				slide.classList.remove("active");
			});
			slides[index].classList.add("active");
			currentIndex = index;
			updateCounter();
			restartProgress();
		}
		/* ==========================================
		NEXT
		========================================== */
		function nextSlide() {
			showSlide(currentIndex + 1);
		}
		/* ==========================================
		PREV
		========================================== */
		function prevSlide() {
			showSlide(currentIndex - 1);
		}
		/* ==========================================
		AUTOPLAY
		========================================== */
		function startAutoplay() {
			clearInterval(autoplay);
			autoplay = setInterval(() => {
				nextSlide();
			}, slideDuration);
			restartProgress();
		}

		function stopAutoplay() {
			clearInterval(autoplay);
		}
		/* ==========================================
		BUTTON EVENTS
		========================================== */
		if (nextBtn) {
			nextBtn.addEventListener("click", () => {
				nextSlide();
				startAutoplay();
			});
		}
		if (prevBtn) {
			prevBtn.addEventListener("click", () => {
				prevSlide();
				startAutoplay();
			});
		}
		/* ==========================================
		PAUSE ON HOVER
		========================================== */
		testimonialSlider.addEventListener(
			"mouseenter",
			stopAutoplay
		);
		testimonialSlider.addEventListener(
			"mouseleave",
			startAutoplay
		);
		/* ==========================================
		TOUCH SWIPE
		========================================== */
		let startX = 0;
		testimonialSlider.addEventListener(
			"touchstart",
			e => {
				startX =
					e.touches[0].clientX;
			}, {
				passive: true
			}
		);
		testimonialSlider.addEventListener(
			"touchend",
			e => {
				const endX =
					e.changedTouches[0].clientX;
				const distance =
					startX - endX;
				if (distance > 60) {
					nextSlide();
					startAutoplay();
				}
				if (distance < -60) {
					prevSlide();
					startAutoplay();
				}
			}, {
				passive: true
			}
		);
		/* ==========================================
		INIT
		========================================== */
		if (slides.length) {
			showSlide(0);
			startAutoplay();
		}
	}

	/* =========================================
	FAQ ACCORDION
	========================================= */
	const faqItems = document.querySelectorAll(".faq-item");
	if (faqItems.length) {
		function closeAllFaqs() {
			faqItems.forEach(item => {
				item.classList.remove("active");
				const body =
					item.querySelector(".faq-body");
				if (body) {
					body.style.maxHeight = null;
				}
			});
		}

		function openFaq(item) {
			const body =
				item.querySelector(".faq-body");
			if (!body) return;
			item.classList.add("active");
			body.style.maxHeight =
				body.scrollHeight + "px";
		}
		faqItems.forEach(item => {
			const trigger =
				item.querySelector(".faq-trigger");
			if (!trigger) return;
			trigger.addEventListener("click", () => {
				const isActive =
					item.classList.contains("active");
				closeAllFaqs();
				if (!isActive) {
					openFaq(item);
				}
			});
		});
		const firstActive =
			document.querySelector(".faq-item.active");
		if (firstActive) {
			openFaq(firstActive);
		} else {
			openFaq(faqItems[0]);
		}
		window.addEventListener("resize", () => {
			const activeItem =
				document.querySelector(".faq-item.active");
			if (!activeItem) return;
			const body =
				activeItem.querySelector(".faq-body");
			if (!body) return; // FIX: guard missing body
			body.style.maxHeight =
				body.scrollHeight + "px";
		});
	}

    /* ==========================================
    LUXURY FOOTER
    ========================================== */

    const footer = document.querySelector(".footer-parallax");

    if (footer) {

        /* ==========================================
        PARALLAX BACKGROUND
        ========================================== */

        const bgImage = footer.querySelector(".footer-background img");

        function footerParallax() {

            if (!bgImage) return;

            const rect = footer.getBoundingClientRect();

            const speed = 0.15;

            const yPos = rect.top * speed;

            bgImage.style.transform =
                `translateY(${yPos}px) scale(2.08)`;
        }

        window.addEventListener(
            "scroll",
            footerParallax,
            { passive: true }
        );

        footerParallax();

        /* ==========================================
        REVEAL ITEMS
        ========================================== */

        const revealItems =
            footer.querySelectorAll(`
                .footer-hero,
                .footer-contact,
                .footer-nav,
                .footer-map-card,
                .footer-marquee,
                .footer-bottom
            `);

        const observer =
            new IntersectionObserver(
                entries => {

                    entries.forEach(entry => {

                        if (
                            entry.isIntersecting
                        ) {

                            entry.target.classList.add(
                                "is-visible"
                            );

                        }

                    });

                },
                {
                    threshold: 0.15
                }
            );

        revealItems.forEach(item => {

            item.classList.add(
                "reveal-item"
            );

            observer.observe(item);

        });

        /* ==========================================
        CTA BUTTON MAGNETIC EFFECT
        ========================================== */

        const footerBtn =
            footer.querySelector(
                ".footer-btn"
            );

        if (footerBtn) {

            footerBtn.addEventListener(
                "mousemove",
                e => {

                    const rect =
                        footerBtn.getBoundingClientRect();

                    const x =
                        e.clientX -
                        rect.left -
                        rect.width / 2;

                    const y =
                        e.clientY -
                        rect.top -
                        rect.height / 2;

                    footerBtn.style.transform =
                        `translate(${x * 0.12}px, ${y * 0.12}px)`;

                }
            );

            footerBtn.addEventListener(
                "mouseleave",
                () => {

                    footerBtn.style.transform =
                        "translate(0,0)";

                }
            );

        }

        /* ==========================================
        NAVIGATION HOVER
        ========================================== */

        footer
            .querySelectorAll(
                ".footer-nav a"
            )
            .forEach(link => {

                link.addEventListener(
                    "mouseenter",
                    () => {

                        link.style.paddingLeft =
                            "15px";

                    }
                );

                link.addEventListener(
                    "mouseleave",
                    () => {

                        link.style.paddingLeft =
                            "0";

                    }
                );

            });

        /* ==========================================
        BACK TO TOP
        ========================================== */

        const topBtn =
            footer.querySelector(
                ".footer-top"
            );

        if (topBtn) {

            topBtn.addEventListener(
                "click",
                () => {

                    window.scrollTo({

                        top: 0,

                        behavior: "smooth"

                    });

                }
            );

        }

        /* ==========================================
        MARQUEE
        ========================================== */

        const marquee =
            footer.querySelector(
                ".footer-marquee-track"
            );

        if (marquee) {

            marquee.innerHTML +=
                marquee.innerHTML;

            let position = 0;
            let speed = 0.5;

            function animateMarquee() {

                position -= speed;

                if (
                    Math.abs(position)
                    >= marquee.scrollWidth / 2
                ) {

                    position = 0;

                }

                marquee.style.transform =
                    `translateX(${position}px)`;

                requestAnimationFrame(
                    animateMarquee
                );

            }

            animateMarquee();

            marquee.addEventListener(
                "mouseenter",
                () => speed = 0.15
            );

            marquee.addEventListener(
                "mouseleave",
                () => speed = 0.5
            );

        }

    }
});


document.addEventListener('DOMContentLoaded', () => {

    const header = document.querySelector('.site-header');
    const lightSections = document.querySelectorAll('.light-section');

    function updateHeaderLogo() {

        if (!header) return;

        const headerHeight = header.offsetHeight;
        const checkPoint = headerHeight / 2;

        let onLightSection = false;

        lightSections.forEach(section => {

            const rect = section.getBoundingClientRect();

            if (
                rect.top <= checkPoint &&
                rect.bottom >= checkPoint
            ) {
                onLightSection = true;
            }

        });

        if (onLightSection) {
            header.classList.add('light-logo');
        } else {
            header.classList.remove('light-logo');
        }
    }

    window.addEventListener('scroll', updateHeaderLogo);
    window.addEventListener('resize', updateHeaderLogo);

    updateHeaderLogo();


    /* ==========================================
    ABOUT HERO
    ========================================== */

    const aboutHero = document.querySelector(".about-hero");

    if (aboutHero) {

        const heroImage =
            aboutHero.querySelector(".about-hero-bg img");

        const heroContent =
            aboutHero.querySelector(".about-hero-content");

        /* ======================================
        INTRO ANIMATION
        ====================================== */

        requestAnimationFrame(() => {

            aboutHero.classList.add("loaded");

        });

        /* ======================================
        PARALLAX
        ====================================== */

        function updateHero() {

            if (!heroImage || !heroContent) return; // FIX: guard missing elements

            const rect =
                aboutHero.getBoundingClientRect();

            const progress =
                Math.min(
                    Math.max(
                        -rect.top / window.innerHeight,
                        0
                    ),
                    1
                );

            /* Background */

            heroImage.style.transform =
                `translateY(${progress * 80}px)
                 scale(${1.08 + progress * .18})`;

            /* Content */

            heroContent.style.transform =
                `translateY(${progress * 100}px)`;

            heroContent.style.opacity =
                1 - (progress * 1.25);

        }

        window.addEventListener(
            "scroll",
            updateHero,
            { passive:true }
        );

        window.addEventListener(
            "resize",
            updateHero
        );

        updateHero();

    }

    /*=========================================
    Brand Story Image Parallax
    =========================================*/

    const brandStory = document.querySelector(".brand-story");
    const brandImage = document.querySelector(".brand-story-media img");

    if (brandStory && brandImage) {

        window.addEventListener("scroll", () => {

            const rect = brandStory.getBoundingClientRect();
            const sectionHeight = brandStory.offsetHeight;
            const windowHeight = window.innerHeight;

            // Only animate while section is visible
            if (rect.bottom > 0 && rect.top < windowHeight) {

                const progress = Math.min(
                    Math.max((windowHeight - rect.top) / (sectionHeight + windowHeight), 0),
                    1
                );

                // Move image up to 18%
                const translateY = progress * -18;

                brandImage.style.transform = `translateY(${translateY}%) scale(1.08)`;

            }

        });

    }

    /*=========================================
    Story Reveal Animation
    =========================================*/

    const storyBlocks = document.querySelectorAll(".story-block");

    const storyObserver = new IntersectionObserver((entries) => {

        entries.forEach(entry => {

            if (entry.isIntersecting) {

                entry.target.classList.add("visible");

            }

        });

    }, {
        threshold: 0.2
    });

    storyBlocks.forEach(block => {

        storyObserver.observe(block);

    });



    /*=========================================
    CRAFTSMANSHIP JOURNEY
    =========================================*/
    (() => {

        const section = document.querySelector(".craftsmanship-section");

        if (!section) return;

        const steps = [...section.querySelectorAll(".craft-step")];
        const images = [...section.querySelectorAll(".craft-image")];

        const progressFill = section.querySelector(".craft-progress-fill");

        const currentStep = section.querySelector(".current-step");

        let activeIndex = 0;

        /*=========================================
        CHANGE ACTIVE STEP
        =========================================*/

        function setActive(index) {

            if (index === activeIndex) return;

            activeIndex = index;

            steps.forEach((step, i) => {

                step.classList.toggle("active", i === index);

            });

            images.forEach((img, i) => {

                img.classList.toggle("active", i === index);

            });

            if (currentStep) { // FIX: guard missing element
                currentStep.textContent = String(index + 1).padStart(2, "0");
            }

        }

        /*=========================================
        INTERSECTION OBSERVER
        =========================================*/

        const observer = new IntersectionObserver(entries => {

            entries.forEach(entry => {

                if (!entry.isIntersecting) return;

                const index = Number(entry.target.dataset.image);

                setActive(index);

            });

        }, {

            threshold: 0.55

        });

        steps.forEach(step => observer.observe(step));



        /*=========================================
        PROGRESS LINE
        =========================================*/

        function updateProgress() {

            if (!progressFill) return; // FIX: guard missing element

            const rect = section.getBoundingClientRect();

            const total = rect.height - window.innerHeight;

            if (total <= 0) return; // FIX: avoid NaN/Infinity

            let progress = (-rect.top / total);

            progress = Math.max(0, Math.min(progress, 1));

            progressFill.style.height = progress * 100 + "%";

        }

        updateProgress();

        window.addEventListener("scroll", updateProgress);



        /*=========================================
        IMAGE PARALLAX
        =========================================*/

        let ticking = false;

        function parallax() {

            const activeImage = section.querySelector(".craft-image.active img");

            if (!activeImage) {

                ticking = false;

                return;

            }

            const rect = section.getBoundingClientRect();

            const speed = rect.top * -0.04;

            activeImage.style.transform = `scale(1.05) translateY(${speed}px)`;

            ticking = false;

        }

        function requestParallax() {

            if (!ticking) {

                requestAnimationFrame(parallax);

                ticking = true;

            }

        }

        window.addEventListener("scroll", requestParallax);



        /*=========================================
        HOVER SUPPORT
        =========================================*/

        steps.forEach(step => {

            step.addEventListener("mouseenter", () => {

                const index = Number(step.dataset.image);

                setActive(index);

            });

        });



        /*=========================================
        REVEAL ANIMATION
        =========================================*/

        const revealObserver = new IntersectionObserver(entries => {

            entries.forEach(entry => {

                if (entry.isIntersecting) {

                    entry.target.classList.add("active");

                }

            });

        }, {

            threshold: .25

        });

        steps.forEach(step => revealObserver.observe(step));



        /*=========================================
        RESIZE FIX
        =========================================*/

        window.addEventListener("resize", updateProgress);

    })();



    /*=========================================
    WHY CHOOSE LIBAS COUNTER
    =========================================*/
    // FIX: same nested-DOMContentLoaded dead-code issue as above — flattened.
    (() => {

        const counters = document.querySelectorAll(".counter");

        if (!counters.length) return;

        const observer = new IntersectionObserver((entries, obs) => {

            entries.forEach(entry => {

                if (!entry.isIntersecting) return;

                const counter = entry.target;

                const target = parseInt(counter.dataset.count, 10);

                const duration = 1800;
                const start = 0;
                const startTime = performance.now();

                function animate(currentTime) {

                    const progress = Math.min((currentTime - startTime) / duration, 1);

                    // Ease Out Cubic
                    const ease = 1 - Math.pow(1 - progress, 3);

                    const value = Math.floor(start + (target - start) * ease);

                    counter.textContent = value.toLocaleString();

                    if (progress < 1) {
                        requestAnimationFrame(animate);
                    } else {
                        counter.textContent = target.toLocaleString();
                    }

                }

                requestAnimationFrame(animate);

                obs.unobserve(counter);

            });

        }, {

            threshold: 0.4

        });

        counters.forEach(counter => observer.observe(counter));

    })();

});