/**
 * Epic Fitness Coach — Animations JS
 *
 * All GSAP ScrollTrigger animations:
 *  1. Generic scroll reveals (.gsap-fade-up, .gsap-slide-left etc.)
 *  2. Homepage counter animation
 *  3. Process step stagger
 *  4. Testimonial card reveals
 *  5. Final CTA reveal
 *
 * Runs after main.js (which registers ScrollTrigger).
 * Respects prefers-reduced-motion.
 */

(function () {
	'use strict';

	document.addEventListener('DOMContentLoaded', function () {
		// Respect reduced motion preference
		const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
		if (prefersReduced) {
			revealAllImmediate();
			return;
		}

		// Wait a tick to ensure GSAP + ScrollTrigger are registered
		requestAnimationFrame(function () {
			if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') {
				console.warn('EFC Animations: GSAP/ScrollTrigger not available');
				revealAllImmediate();
				return;
			}

			initGenericReveals();
			initCounters();
			initProcessSteps();
			initProgramCards();
			initTestimonialCards();
			initFinalCta();
		});
	});


	/* =====================================================
	   FALLBACK — reveal everything immediately
	   Used when GSAP fails to load or reduced motion
	   ===================================================== */
	function revealAllImmediate() {
		var elements = document.querySelectorAll(
			'.gsap-fade-up, .gsap-fade-in, .gsap-slide-left, .gsap-slide-right, .gsap-scale-in'
		);
		elements.forEach(function (el) {
			el.style.opacity    = '1';
			el.style.transform  = 'none';
		});
	}


	/* =====================================================
	   1. GENERIC SCROLL REVEALS
	   Finds all elements with gsap-* classes and animates
	   based on class name. Respects data-delay attribute.
	   ===================================================== */
	function initGenericReveals() {

		// Fade up
		animateGroup('.gsap-fade-up', {
			y:       40,
			opacity: 0,
		}, {
			y:       0,
			opacity: 1,
		});

		// Fade in
		animateGroup('.gsap-fade-in', {
			opacity: 0,
		}, {
			opacity: 1,
		});

		// Slide left
		animateGroup('.gsap-slide-left', {
			x:       -50,
			opacity: 0,
		}, {
			x:       0,
			opacity: 1,
		});

		// Slide right
		animateGroup('.gsap-slide-right', {
			x:       50,
			opacity: 0,
		}, {
			x:       0,
			opacity: 1,
		});

		// Scale in
		animateGroup('.gsap-scale-in', {
			scale:   0.92,
			opacity: 0,
		}, {
			scale:   1,
			opacity: 1,
		});
	}

	/**
	 * Helper: animate a group of elements with ScrollTrigger
	 * Respects data-delay on each element for staggering
	 */
	function animateGroup(selector, fromVars, toVars) {
		var elements = document.querySelectorAll(selector);
		if (!elements.length) return;

		elements.forEach(function (el) {
			var delay = parseFloat(el.getAttribute('data-delay') || 0);

			// Set initial state
			gsap.set(el, fromVars);

			// Animate in on scroll
			gsap.to(el, Object.assign({}, toVars, {
				delay:    delay,
				duration: 0.8,
				ease:     'power3.out',
				scrollTrigger: {
					trigger:   el,
					start:     'top 88%',
					end:       'bottom 20%',
					toggleActions: 'play none none none',
				},
			}));
		});
	}


	/* =====================================================
	   2. COUNTER ANIMATION
	   Animates .counter-value elements from 0 to data-target
	   ===================================================== */
	function initCounters() {
		var counters = document.querySelectorAll('.counter-value');
		if (!counters.length) return;

		counters.forEach(function (counter) {
			var target = parseInt(counter.getAttribute('data-target') || 0, 10);
			var obj    = { val: 0 };

			gsap.to(obj, {
				val:      target,
				duration: 2,
				ease:     'power2.out',
				scrollTrigger: {
					trigger:       counter,
					start:         'top 85%',
					toggleActions: 'play none none none',
					once:          true,
				},
				onUpdate: function () {
					counter.textContent = Math.round(obj.val);
				},
				onComplete: function () {
					counter.textContent = target;
				},
			});
		});
	}


	/* =====================================================
	   3. PROCESS STEPS
	   Staggered reveal for the How It Works section
	   ===================================================== */
	function initProcessSteps() {
		var steps = document.querySelectorAll('.efc-process__step');
		if (!steps.length) return;

		// Set initial state
		gsap.set(steps, { y: 50, opacity: 0 });

		// Stagger reveal
		ScrollTrigger.create({
			trigger: '.efc-process__steps',
			start:   'top 80%',
			onEnter: function () {
				gsap.to(steps, {
					y:        0,
					opacity:  1,
					duration: 0.7,
					stagger:  0.2,
					ease:     'power3.out',
				});
			},
			once: true,
		});

		// Connectors fade in
		var connectors = document.querySelectorAll('.efc-process__connector');
		if (connectors.length) {
			gsap.set(connectors, { scaleX: 0, opacity: 0, transformOrigin: 'left center' });
			ScrollTrigger.create({
				trigger: '.efc-process__steps',
				start:   'top 80%',
				onEnter: function () {
					gsap.to(connectors, {
						scaleX:   1,
						opacity:  1,
						duration: 0.6,
						stagger:  0.2,
						delay:    0.4,
						ease:     'power2.out',
					});
				},
				once: true,
			});
		}
	}


	/* =====================================================
	   4. PROGRAM CARDS
	   Staggered scale-in for the two program cards
	   ===================================================== */
	function initProgramCards() {
		var cards = document.querySelectorAll('.efc-programs__card');
		if (!cards.length) return;

		cards.forEach(function (card, index) {
			gsap.set(card, { y: 60, opacity: 0 });

			ScrollTrigger.create({
				trigger: card,
				start:   'top 85%',
				onEnter: function () {
					gsap.to(card, {
						y:        0,
						opacity:  1,
						duration: 0.8,
						delay:    index * 0.15,
						ease:     'power3.out',
					});
				},
				once: true,
			});
		});
	}


	/* =====================================================
	   5. TESTIMONIAL CARDS
	   Staggered reveal for testimonial preview section
	   ===================================================== */
	function initTestimonialCards() {
		var cards = document.querySelectorAll('.efc-testimonials-preview__card');
		if (!cards.length) return;

		gsap.set(cards, { y: 40, opacity: 0 });

		ScrollTrigger.create({
			trigger: '.efc-testimonials-preview__grid',
			start:   'top 85%',
			onEnter: function () {
				gsap.to(cards, {
					y:        0,
					opacity:  1,
					duration: 0.7,
					stagger:  0.15,
					ease:     'power3.out',
				});
			},
			once: true,
		});
	}


	/* =====================================================
	   6. FINAL CTA
	   Parallax background + fade-in content
	   ===================================================== */
	function initFinalCta() {
		var ctaSection = document.querySelector('.efc-final-cta');
		var ctaBg      = document.querySelector('.efc-final-cta__bg');
		var ctaContent = document.querySelector('.efc-final-cta__content');

		if (!ctaSection) return;

		// Parallax on background
		if (ctaBg) {
			gsap.to(ctaBg, {
				yPercent: -20,
				ease:     'none',
				scrollTrigger: {
					trigger: ctaSection,
					start:   'top bottom',
					end:     'bottom top',
					scrub:   true,
				},
			});
		}

		// Content fade-in
		if (ctaContent) {
			gsap.set(ctaContent, { y: 30, opacity: 0 });
			ScrollTrigger.create({
				trigger: ctaSection,
				start:   'top 80%',
				onEnter: function () {
					gsap.to(ctaContent, {
						y:        0,
						opacity:  1,
						duration: 1,
						ease:     'power3.out',
					});
				},
				once: true,
			});
		}
	}

})();