export function initScrollAnimations() {
  if (typeof window === 'undefined') return;

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

  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('in-view');
      }
    });
  }, observerOptions);

  // Observe all elements with the animate-on-scroll class
  const animatedElements = document.querySelectorAll('.animate-on-scroll');
  animatedElements.forEach((el) => observer.observe(el));

  return observer;
}

export function fadeIn(element: HTMLElement, duration = 300) {
  element.style.opacity = '0';
  element.style.display = 'block';

  let start: number | null = null;
  
  function animate(timestamp: number) {
    if (!start) start = timestamp;
    const progress = timestamp - start;

    element.style.opacity = String(Math.min(progress / duration, 1));

    if (progress < duration) {
      requestAnimationFrame(animate);
    }
  }

  requestAnimationFrame(animate);
}

export function slideUp(element: HTMLElement, duration = 300) {
  element.style.transform = 'translateY(20px)';
  element.style.opacity = '0';
  element.style.display = 'block';

  let start: number | null = null;
  
  function animate(timestamp: number) {
    if (!start) start = timestamp;
    const progress = timestamp - start;
    const progressRatio = Math.min(progress / duration, 1);

    element.style.transform = `translateY(${20 * (1 - progressRatio)}px)`;
    element.style.opacity = String(progressRatio);

    if (progress < duration) {
      requestAnimationFrame(animate);
    } else {
      element.style.transform = '';
      element.style.opacity = '';
    }
  }

  requestAnimationFrame(animate);
}

// Smooth scroll to element
export function scrollToElement(elementId: string, offset = 80) {
  const element = document.getElementById(elementId);
  if (element) {
    const targetPosition = element.offsetTop - offset;
    window.scrollTo({
      top: targetPosition,
      behavior: 'smooth'
    });
  }
} 