import { Component, ElementRef, ViewChild, AfterViewInit, OnDestroy, Inject, PLATFORM_ID } from '@angular/core';
import { CommonModule, isPlatformBrowser } from '@angular/common';

interface Partner {
  name: string;
  logo: string;
}

@Component({
  selector: 'app-partners-section',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './partners-section.component.html',
  styleUrls: ['./partners-section.component.scss']
})
export class PartnersSectionComponent implements AfterViewInit, OnDestroy {
  @ViewChild('scrollContainer') scrollContainer!: ElementRef<HTMLDivElement>;
  
  partners: Partner[] = [
    { name: "FreshMart", logo: "🛒" },
    { name: "TechZone", logo: "📱" },
    { name: "Golden Bakery", logo: "🥐" },
    { name: "Ocean Fish", logo: "🐟" },
    { name: "Luxe Jewels", logo: "💎" },
    { name: "MediCare Plus", logo: "💊" },
    { name: "Fashion Hub", logo: "👗" },
    { name: "Gourmet Kitchen", logo: "🍽️" },
    { name: "Pet Paradise", logo: "🐕" },
    { name: "Green Grocer", logo: "🥬" },
    { name: "Book Haven", logo: "📚" },
    { name: "Fitness First", logo: "💪" },
  ];

  scrollingPartners: Partner[] = [];
  
  private animationId!: number;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    this.scrollingPartners = [...this.partners, ...this.partners];
  }

  ngAfterViewInit() {
    if (isPlatformBrowser(this.platformId)) {
      const scroll = () => {
        if (this.scrollContainer) {
          const scrollContainer = this.scrollContainer.nativeElement;
          let scrollPosition = scrollContainer.scrollLeft;
          scrollPosition += 0.5;
          if (scrollPosition >= scrollContainer.scrollWidth / 2) {
            scrollPosition = 0;
          }
          scrollContainer.scrollLeft = scrollPosition;
          this.animationId = requestAnimationFrame(scroll);
        }
      };
      this.animationId = requestAnimationFrame(scroll);
    }
  }

  ngOnDestroy() {
    if (isPlatformBrowser(this.platformId) && this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
  }
}
