import {
  Injectable,
  inject,
  PLATFORM_ID
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({ providedIn: 'root' })
export class ScrollAnimationService {
  private readonly platformId = inject(PLATFORM_ID);
  private observer: IntersectionObserver | null = null;

  init(): void {
    if (!isPlatformBrowser(this.platformId))
      return;

    this.observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('visible');
          }
        });
      },
      { threshold: 0.1, rootMargin: '0px 0px -50px 0px' }
    );

    // Observe all elements with section-fade class
    document.querySelectorAll('.section-fade').forEach((el) => {
      this.observer?.observe(el);
    });
  }

  observe(element: HTMLElement): void {
    this.observer?.observe(element);
  }

  destroy(): void {
    this.observer?.disconnect();
  }
}
