import { Component, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { HeaderComponent } from "../header/header.component";
import { AllapiService } from '../allapi.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { AuthService } from '../auth.service';
import { BrowserModule, Title, Meta } from '@angular/platform-browser';
import { slugify as translitSlug } from 'transliteration';
import { LanguagePopupComponent } from '../language-popup/language-popup.component';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [HeaderComponent, CommonModule, RouterModule, LanguagePopupComponent],
  providers:[Title, Meta],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent  {
  stories: any[] = [];
  libraryMessage = '';
  categoryColumns: any[] = [];
  likedStories: number[] = [];
  userId: string | null = null;
  storyImgPath = 'https://infoways.in/funtelapi';
  userProgress: any[] = [];
isLoggedIn: boolean = true;

  topAuthors: {
    author_name: string;
    user_id: string;
    views: number;
    story_count: number;
    profileImg?: string;
  }[] = [];

  isFollowingMap: { [authorId: string]: boolean } = {};

  latestStories: any[] = [];
  allLatestStories: any[] = [];
  showAllLatest = false;

  visibleCategories: any[] = [];
  showAllCategories = false;

  trendingStories: any[] = [];

   private isMouseDown: boolean = false;
  private startX: number = 0;
private scrollLeft: number = 0;
  private velocity: number = 0;
  private lastX: number = 0;
  private timestamp: number = 0;
  private rafId: number | null = null;

  // ---- carousel refs ----
  @ViewChild('carousel', { static: false }) carousel!: ElementRef;
  currentSlideIndex = 0;
  slideWidth = 0;
  isDragging = false;
  startPos = 0;
  currentTranslate = 0;
  prevTranslate = 0;
  categoryWiseStories: { [category: string]: any[] } = {};
categoryOrder: string[] = [];
featuredStories: any[] = [];
selectedLanguage: string = 'en';
otherLanguageStories: any[] = [];

  constructor(
    private allApi: AllapiService,
    private http: HttpClient,
    public router: Router,
    private authService: AuthService,
    private titleService: Title, private meta: Meta,
    private languageService: LanguageService,
    public translationService: TranslationService
  ) {}
private isVerticalScroll: boolean = false;
private touchStartX: number = 0;
private touchStartY: number = 0;
private readonly VERTICAL_SCROLL_THRESHOLD = 5;
  // ---------------- lifecycle ----------------
  ngOnInit(): void {
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
      this.refreshAllData(); 
    });
    this.translationService.currentLang$.subscribe(() => {
      
    });


    this.selectedLanguage = this.languageService.getCurrentLanguage();

    
    this.titleService.setTitle('Funtel Studio Read Stories, Web Series &amp; TV Shows Online in HD');
    this.meta.updateTag({
      name: 'description',
      content: 'Stream the latest Story, trending web series, and TV shows in HD on Funtel Studio. Enjoy uninterrupted entertainment with a vast collection of content across genres, anytime and anywhere.'
    });

    // Meta Keywords
    this.meta.updateTag({
      name: 'keywords',
      content: 'Funtel, Read Story'
    });

    const userId = this.authService.getCurrentUserId();
    this.getAllStories();
    this.getCategory();
    this.loadLikedStories();
    this.loadUserStoryProgress();
    this.getAllCategoryStories();
    this.loadOtherLanguageStories(); 
  }
  t(key: string): string {
    return this.translationService.translate(key);
  }
 refreshAllData() {
    this.getAllStories();
    this.getAllCategoryStories();
    // Aur bhi API calls jo language dependent hain
  }
  ngAfterViewInit() {
    this.calculateSlideWidth();
    this.setupCarousel();
  }

  // ---------------- carousel helpers ----------------
  @HostListener('window:resize')
  onResize() { this.calculateSlideWidth(); }

  calculateSlideWidth() {
    if (this.carousel?.nativeElement?.firstElementChild) {
      this.slideWidth = this.carousel.nativeElement.firstElementChild.clientWidth;
    }
  }
  setupCarousel() {
  const c = this.carousel.nativeElement;
  
  // Mouse events
  c.addEventListener('mousedown', (e) => this.startDrag(e));
  c.addEventListener('mouseleave', () => this.endDrag());
  c.addEventListener('mouseup', () => this.endDrag());
  c.addEventListener('mousemove', (e) => this.dragMove(e));
  
  // Touch events with improved handling
  c.addEventListener('touchstart', (e) => this.touchStart(e), { passive: true });
  c.addEventListener('touchend', () => this.touchEnd());
  c.addEventListener('touchmove', (e) => this.touchMove(e), { passive: false });
}

 startDrag(e: MouseEvent | TouchEvent) {
  // For touch events, we've already handled this in touchStart
  if (e.type !== 'touchstart') {
    this.isDragging = true;
    this.startPos = this.getPositionX(e);
    this.carousel.nativeElement.style.cursor = 'grabbing';
  }
}
createNewStory(): void {
    if (this.isLoggedIn) {
      this.router.navigate(['/new']);
    } else {
      this.router.navigate(['/login']);
    }
  }
  navigateToLogin(): void {
  this.router.navigate(['/login']);
}
touchStart(e: TouchEvent) {
  this.touchStartX = e.touches[0].clientX;
  this.touchStartY = e.touches[0].clientY;
  this.isVerticalScroll = false;
}
touchMove(e: TouchEvent) {
  if (!this.touchStartX || !this.touchStartY) return;
  
  const touchX = e.touches[0].clientX;
  const touchY = e.touches[0].clientY;
  
  const diffX = Math.abs(touchX - this.touchStartX);
  const diffY = Math.abs(touchY - this.touchStartY);
  
  
  if (!this.isVerticalScroll && diffY > this.VERTICAL_SCROLL_THRESHOLD && diffY > diffX) {
    this.isVerticalScroll = true;
    return; 
  }
  
  
  if (!this.isVerticalScroll && diffX > diffY) {
    e.preventDefault();
    
    
    if (!this.isDragging) {
      this.isDragging = true;
      this.startPos = this.touchStartX;
      this.prevTranslate = this.currentTranslate;
    }
    
    
    this.currentTranslate = this.prevTranslate + touchX - this.startPos;
    this.carousel.nativeElement.style.transform = `translateX(${this.currentTranslate}px)`;
  }
}

touchEnd() {
  this.isDragging = false;
  this.prevTranslate = this.currentTranslate;
  this.touchStartX = 0;
  this.touchStartY = 0;
  this.isVerticalScroll = false;
}
  endDrag() {
    this.isDragging = false;
    this.prevTranslate = this.currentTranslate;
    this.carousel.nativeElement.style.cursor = 'grab';
  }
  dragMove(e: MouseEvent) {
  if (!this.isDragging) return;
  e.preventDefault();
  const currentPosition = this.getPositionX(e);
  this.currentTranslate = this.prevTranslate + currentPosition - this.startPos;
  this.carousel.nativeElement.style.transform = `translateX(${this.currentTranslate}px)`;
}
  getPositionX(e: MouseEvent | TouchEvent): number {
    return e.type.includes('mouse')
      ? (e as MouseEvent).pageX
      : (e as TouchEvent).touches[0].clientX;
  }
  scrollCarousel(direction: number) {
    this.currentSlideIndex = Math.max(
      0,
      Math.min(this.currentSlideIndex + direction, this.latestStories.length - 1)
    );
    const scrollAmount = this.currentSlideIndex * this.slideWidth;
    this.carousel.nativeElement.scrollTo({ left: scrollAmount, behavior: 'smooth' });
  }

  filterStoriesByLanguage(stories: any[]): any[] {
    if (!stories) return [];
    return stories.filter(story => {
      
      return story.language === this.selectedLanguage || 
             !story.language || 
             this.selectedLanguage === 'en'; 
    });
  }

  // ---------------- path helpers ----------------
  private normPath(p: string | null | undefined): string {
    return p ? p.replace(/^\/+/, '') : '';
  }
  private fullAsset(rel?: string): string {
    const path = this.normPath(rel?.trim() || '');
    return path ? `${this.storyImgPath}/${path}` : '';
  }

  // ---------------- decorate story w/ author assets ----------------
  /** Normalizes API record; returns new object. */
  private decorateStory(raw: any): any {
    const rec = { ...raw };

    const profRaw  =
      rec.profileImg ??
      rec.profileimg_url ??
      rec.profileimg ??
      '';
    const coverRaw =
      rec.coverImg ??
      rec.coverimage_url ??
      rec.coverimage ??
      '';
    rec.authorProfileUrl = this.fullAsset(profRaw);
    rec.authorCoverUrl   = this.fullAsset(coverRaw);
    rec.authorInitial    = rec.author_name
      ? rec.author_name.trim().charAt(0).toUpperCase()
      : 'U';

    // numeric safe values
    rec.views          = +rec.views || 0;
    rec.average_rating = +rec.average_rating || 0;
    rec.total_ratings  = +rec.total_ratings || 0;

    return rec;
  }
getEmptyStateMessage(): string {
    const messages: { [key: string]: string } = {
      'en': 'No stories available yet.',
      'hi': 'यहाँ अभी तक कोई कहानियाँ उपलब्ध नहीं हैं।',
      'mr': 'येथे अद्याप कथा नाहीत.',
      'bn': 'এখানে এখনও কোন গল্প পাওয়া যায়নি।',
      'ta': 'இங்கு இன்னும் கதைகள் எதுவும் இல்லை.',
      'te': 'ఇంకా ఇక్కడ కథలు లేవు.'
    };
    return messages[this.selectedLanguage] || messages['en'];
  }

  getEmptyStateSubtitle(): string {
    const messages: { [key: string]: string } = {
      'en': 'Publish your first {{language}} story and get the early-mover advantage. <a href="contest" class="redcolor">Click here for more info</a>.',
      'hi': 'अपनी पहली {{language}} कहानी प्रकाशित करें और early-mover advantage प्राप्त करें। <a href="contest" class="redcolor">अधिक माहितीसाठी इथे क्लिक करें</a>.',
      'mr': 'इथे तुमची कथा लिहा आणि मिळवा Funtel StoryFest चे प्रमाणपत्र आणि जिंका ₹5000 रुपये!<br>अटी व शर्ती लागू — <a href="contest" class="redcolor">अधिक माहितीसाठी इथे क्लिक करा</a>.',
      'bn': 'আপনার প্রথম {{language}} গল্প প্রকাশ করুন এবং early-mover advantage পান। <a href="contest" class="redcolor">আরও তথ্যের জন্য এখানে ক্লিক করুন</a>.',
      'ta': 'உங்கள் முதல் {{language}} கதையை வெளியிட்டு early-mover advantage பெறுங்கள். <a href="contest" class="redcolor">மேலும் தகவலுக்கு இங்கே கிளிக் செய்யவும்</a>.',
      'te': 'మీ మొదటి {{language}} కథను ప్రచురించండి మరియు early-mover advantage పొందండి. <a href="contest" class="redcolor">మరిన్ని వివరాలకు ఇక్కడ క్లిక్ చేయండి</a>.',

    };
    
    const languageNames: { [key: string]: string } = {
      'en': 'English',
      'hi': 'Hindi',
      'mr': 'Marathi', 
      'bn': 'Bengali',
      'ta': 'Tamil',
      'te': 'Telugu'
    };
    
    const languageName = languageNames[this.selectedLanguage] || 'English';
    return (messages[this.selectedLanguage] || messages['en']).replace('{{language}}', languageName);
  }

  getCategoryEmptyMessage(): string {
    const messages: { [key: string]: string } = {
      'en': 'No stories in this category yet.',
      'hi': 'इस श्रेणी में अभी तक कोई कहानियाँ नहीं हैं।',
      'mr': 'या श्रेणीत अद्याप कथा नाहीत.',
      'bn': 'এই বিভাগে এখনও কোন গল্প নেই।',
      'ta': 'இந்த வகையில் இன்னும் கதைகள் இல்லை.',
      'te': 'ఈ వర్గంలో ఇంకా కథలు లేవు.'
    };
    return messages[this.selectedLanguage] || messages['en'];
  }

  scrollLeft() {
    this.carousel.nativeElement.scrollBy({ left: -300, behavior: 'smooth' });
  }

  scrollRight() {
    this.carousel.nativeElement.scrollBy({ left: 300, behavior: 'smooth' });
  }
  // ---------------- API: all stories ----------------
getAllStories() {

    const dbLanguage = this.languageService.getCurrentLanguageForDB();
    const langParam = this.selectedLanguage !== 'en' ? `?language=${dbLanguage}` : '';
    
    console.log('Fetching stories with language:', dbLanguage);
    
    this.http.get<any>(`https://infoways.in/funtelapi/allstory.php${langParam}`, {
      withCredentials: true
    }).subscribe({
      next: (response) => {
        if (response.status === 'success') {
          const decorated = response.data.map((s: any) => this.decorateStory(s));

          // Featured stories
          this.featuredStories = decorated.filter((story: any) => story.story_action === 1);
          
          // Master list
          this.allLatestStories = decorated.sort(
            (a: any, b: any) =>
              new Date(b.created_at || b.story_created_at).getTime() -
              new Date(a.created_at || a.story_created_at).getTime()
          );

          // Subset lists
          this.latestStories = this.allLatestStories.slice(0, 2);
          this.trendingStories = this.allLatestStories.slice(0, 6);
          this.stories = this.allLatestStories.slice(0, 6);

          this.calculateTopAuthors(decorated);
          this.loadFollowStatus();

          console.log(`Loaded ${decorated.length} stories for language: ${dbLanguage}`);
        }
      },
      error: (error) => {
        console.error('API call failed:', error);
      }
    });
  }
getStoriesForCategory(categoryStories: any[]): any[] {
    if (!categoryStories) return [];
    return categoryStories;
  }

getAllCategoryStories() {
    // Database ke liye language value use karein
    const dbLanguage = this.languageService.getCurrentLanguageForDB();
    const langParam = this.selectedLanguage !== 'en' ? `&language=${dbLanguage}` : '';
    
    console.log('Fetching category stories with language:', dbLanguage);
    
    this.http.get<any>(`https://infoways.in/funtelapi/category.php?with_stories=true${langParam}`, {
      withCredentials: true
    }).subscribe({
      next: (response) => {
        if (response.status === 'success') {
          const storyByCategory: { [key: string]: any[] } = {};
          const order: string[] = [];

          for (const cat of response.data) {
            const catName = cat.category_name?.trim();
            const catId = cat.category_id;

            if (!catName || !catId || !cat.stories?.length) continue;

            // Stories ko language ke hisaab se filter karein
            const filteredStories = cat.stories
              .map((s: any) => this.decorateStory(s))
              .filter((story: any) => {
                // Agar language set nahi hai to show karein (backward compatibility)
                if (!story.language) return true;
                // Current selected language ke stories show karein
                const storyLangCode = this.languageService.getCodeFromDBValue(story.language);
                return storyLangCode === this.selectedLanguage;
              });

            if (filteredStories.length > 0) {
              storyByCategory[catName] = filteredStories;
              order.push(catName);
            }
          }

          this.categoryWiseStories = storyByCategory;
          this.categoryOrder = order;
          console.log(`✅ Category-wise stories for ${dbLanguage}:`, this.categoryWiseStories);
        } else {
          console.error('❌ API responded with error:', response.message);
        }
      },
      error: (error) => {
        console.error('❌ Category-wise API call failed:', error);
      }
    });
  }

  // ---------------- categories ----------------
  getCategory() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      
    });
    this.http.get<any>('https://infoways.in/funtelapi/category.php', { headers, withCredentials: true })
      .subscribe({
        next: (res) => {
          if (res.status === 'success') {
            this.categoryColumns = res.data.flat();
            this.visibleCategories = this.categoryColumns.slice(0, 12);
          }
        },
        error: (err) => console.error('Failed to fetch categories:', err)
      });
  }
  toggleCategories() {
    this.showAllCategories = !this.showAllCategories;
    this.visibleCategories = this.showAllCategories
      ? this.categoryColumns
      : this.categoryColumns.slice(0, 12);
  }
loadOtherLanguageStories() {
    this.http.get<any>('https://infoways.in/funtelapi/allstory.php', {
      withCredentials: true
    }).subscribe({
      next: (response) => {
        if (response.status === 'success') {
          const allStories = response.data.map((s: any) => this.decorateStory(s));
          
          // Filter stories that are NOT in current language
          this.otherLanguageStories = allStories.filter((story: any) => {
            const storyLangCode = this.languageService.getCodeFromDBValue(story.language);
            return storyLangCode !== this.selectedLanguage;
          });

          // Sort by creation date (newest first)
          this.otherLanguageStories.sort((a: any, b: any) => 
            new Date(b.created_at || b.story_created_at).getTime() -
            new Date(a.created_at || a.story_created_at).getTime()
          );

          console.log(`Loaded ${this.otherLanguageStories.length} stories from other languages`);
        }
      },
      error: (error) => {
        console.error('Failed to load other language stories:', error);
      }
    });
  }

  // Add this method to get language name from code
  getLanguageName(languageCode: string): string {
    const languageNames: { [key: string]: string } = {
      'en': 'English',
      'hi': 'Hindi',
      'mr': 'Marathi', 
      'bn': 'Bengali',
      'ta': 'Tamil',
      'te': 'Telugu'
    };
    
    const code = this.languageService.getCodeFromDBValue(languageCode);
    return languageNames[code] || 'Unknown';
  }
  // ---------------- library / likes ----------------
  addToLibrary(storyId: number) {
    const userId = this.authService.getCurrentUserId();
    if (!userId) { this.router.navigate(['login']); return; }

    const alreadyLiked = this.likedStories.includes(storyId);
    const body = { user_id: userId, story_id: storyId, like_story: !alreadyLiked };

    this.http.post<any>('https://infoways.in/funtelapi/addstory.php', body,{
      headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
      withCredentials: true
    }).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          if (!alreadyLiked) {
            this.likedStories.push(storyId);
            this.libraryMessage = 'Story added to library';
          } else {
            this.likedStories = this.likedStories.filter(id => id !== storyId);
            this.libraryMessage = 'Story removed from library';
          }
        } else if (res.status === 'removed') {
          this.likedStories = this.likedStories.filter(id => id !== storyId);
          this.libraryMessage = 'Story removed from library';
        } else {
          this.libraryMessage = res.message || 'Unexpected response';
        }
        setTimeout(() => this.libraryMessage = '', 3000);
      },
      error: () => console.error('Library action failed')
    });
  }

  loadLikedStories() {
    const userId = this.authService.getCurrentUserId();
    if (!userId) return;
    this.http.get<any>(`https://infoways.in/funtelapi/allstory.php?action=library&user_id=${userId}`, { withCredentials: true })
      .subscribe({
        next: (res) => {
          if (res.status === 'success') {
            this.likedStories = res.data.map((item: any) => +item.id);
            console.log('Liked Stories:', this.likedStories);
          }
        },
        error: (err) => console.error('Failed to load liked stories:', err)
      });
  }

  // ---------------- top authors ----------------
  calculateTopAuthors(stories: any[]) {
    const authorMap: Record<string, {
      author_name: string;
      user_id: string;
      views: number;
      story_count: number;
      profileImg?: string;
    }> = {};

    for (const s of stories) {
      const uid   = s.user_id;
      const views = +s.views || 0;
      if (!authorMap[uid]) {
        authorMap[uid] = {
          user_id: uid,
          author_name: s.author_name || 'Unknown',
          views,
          story_count: 1,
          profileImg: s.authorProfileUrl || ''
        };
      } else {
        authorMap[uid].views += views;
        authorMap[uid].story_count += 1;
      }
    }
    this.topAuthors = Object.values(authorMap)
      .sort((a, b) => b.views - a.views)
      .slice(0, 10);
  }
viewProfile(authorId: string) {
  this.router.navigate(['/profile', authorId]);
}
  loadFollowStatus() {
    const userId = this.authService.getCurrentUserId();
    if (!userId) return;
    for (const author of this.topAuthors) {
      const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
      this.http.post<any>(
        'https://infoways.in/funtelapi/follow/check_follow.php',
        { follower_id: +userId, following_id: +author.user_id },
        { headers, withCredentials: true }
      ).subscribe({
        next: (res) => this.isFollowingMap[author.user_id] = !!res.isFollowing,
        error: (err) => console.error(`Error checking follow for ${author.user_id}:`, err)
      });
    }
  }

  toggleFollow(authorId: string) {
    const userId = this.authService.getCurrentUserId();
    if (!userId) { this.router.navigate(['login']); return; }

    const isFollowing = this.isFollowingMap[authorId];
    const apiUrl = isFollowing
      ? 'https://infoways.in/funtelapi/follow/unfollow.php'
      : 'https://infoways.in/funtelapi/follow/follow.php';
    const body   = { follower_id: +userId, following_id: +authorId };
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

    this.http.post(apiUrl, body, { headers, withCredentials: true }).subscribe({
      next: () => this.isFollowingMap[authorId] = !isFollowing,
      error: (err) => console.error('Follow/Unfollow failed:', err)
    });
  }

  // ---------------- progress ----------------
  loadUserStoryProgress() {
    const userId = this.authService.getCurrentUserId();
    if (!userId) return;
    const key = `story_progress_${userId}`;
    const data = localStorage.getItem(key);
    if (!data) return;

    const progress = JSON.parse(data);
    this.userProgress = [];

    for (const [storyId, entry] of Object.entries(progress) as any) {
      const percent = Math.round((entry.readParts.length / entry.totalParts) * 100);
      this.http.get<any>(`https://infoways.in/funtelapi/allstory.php?id=${storyId}`,{withCredentials:true}).subscribe({
        next: (res) => {
          if (res.status === 'success' && res.data?.length) {
            const storyData = res.data.find((s: any) => s.id == +storyId);
            this.userProgress.push({
              storyId,
              title: entry.lastPartTitle,
              lastReadPartId: entry.lastReadPartId,
              percent,
              part: entry.readParts.length,
              total: entry.totalParts,
              timestamp: entry.timestamp,
              image: this.fullAsset(storyData.story_image)
            });
            this.userProgress.sort((a, b) => b.timestamp - a.timestamp);
          }
        },
        error: (err) => console.error(`Failed to fetch story info for ${storyId}`, err)
      });
    }
  }

  // ---------------- misc helpers ----------------
  resumeReading(storyId: number, title: string) {
    const slug = this.slugify(title);
    this.router.navigate(['/series', `${storyId}-${slug}`]);
  }
  goToSeries(storyId: string, title: string) {
    const slug = this.slugify(title);
    this.router.navigate(['/story', `${storyId}-${slug}`]);
  }
  slugify(text: string): string {
    return translitSlug(text, { lowercase: true, separator: '-' });
    return text.toLowerCase().trim().replace(/[\s\W-]+/g, '-').replace(/^-+|-+$/g, '');
  }

  getProgress(storyId: number): number {
    const progress = this.userProgress.find(p => p.storyId == storyId);
    return progress ? progress.percent : 0;
  }

  getTotalReadingTime(): number {
    return this.stories.reduce((sum, s) => sum + (s.readTime || 0), 0);
  }
  formatTotalReadTime(minutes: number): string {
    if (minutes >= 10080) { const weeks = Math.floor(minutes / 10080); const rem = minutes % 10080; return `${weeks} week${weeks>1?'s':''}` + (rem?` ${this.formatTotalReadTime(rem)}`:''); }
    if (minutes >= 1440)  { const days  = Math.floor(minutes / 1440); const rem = minutes % 1440; return `${days} day${days>1?'s':''}` + (rem?` ${this.formatTotalReadTime(rem)}`:''); }
    if (minutes >= 60)    { const hrs   = Math.floor(minutes / 60);   const rem = minutes % 60;   return `${hrs} hr${hrs>1?'s':''}` + (rem?` ${rem} min`:''); }
    return `${minutes} min`;
  }
  getTotalViews(): number {
    return this.stories.reduce((sum, s) => sum + (s.views || 0), 0);
  }
  formatCount(num: number): string {
    if (num >= 1_000_000) return (num / 1_000_000).toFixed(1) + 'M';
    if (num >= 1_000)     return (num / 1_000).toFixed(1) + 'K';
    return num.toString();
  }
  toggleSeeMore() {
  this.showAllLatest = !this.showAllLatest;
  this.latestStories = this.showAllLatest
    ? this.allLatestStories
    : this.allLatestStories.slice(0, 6);
}
setupMouseDrag() {
    const carousel = this.carousel.nativeElement;
    
    // Prevent image drag
    const images = carousel.querySelectorAll('img');
    images.forEach((img: HTMLImageElement) => {
      img.addEventListener('dragstart', (e) => e.preventDefault());
    });
  }

  onMouseDown(event: MouseEvent) {
    const carousel = this.carousel.nativeElement;
    
    this.isMouseDown = true;
    carousel.classList.add('active:cursor-grabbing');
    this.startX = event.pageX - carousel.offsetLeft;
    this.scrollLeft = carousel.scrollLeft;
    this.velocity = 0;
    this.lastX = event.pageX;
    this.timestamp = Date.now();
    
    event.preventDefault();
  }

  onMouseMove(event: MouseEvent) {
    if (!this.isMouseDown) return;
    
    const carousel = this.carousel.nativeElement;
    const x = event.pageX - carousel.offsetLeft;
    const walk = (x - this.startX) * 2; // Scroll speed multiplier
    
    // Calculate velocity for momentum
    const now = Date.now();
    const deltaTime = now - this.timestamp;
    if (deltaTime > 0) {
      const deltaX = event.pageX - this.lastX;
      this.velocity = deltaX / deltaTime;
    }
    
    this.lastX = event.pageX;
    this.timestamp = now;
    
    carousel.scrollLeft = this.scrollLeft - walk;
    event.preventDefault();
  }

  onMouseUp() {
    this.isMouseDown = false;
    this.carousel.nativeElement.classList.remove('active:cursor-grabbing');
    
    // Apply momentum scrolling
    this.applyMomentum();
  }

  applyMomentum() {
    if (Math.abs(this.velocity) < 0.1) return;
    
    const carousel = this.carousel.nativeElement;
    const momentum = this.velocity * 1000; // Momentum multiplier
    
    const animate = () => {
      this.velocity *= 0.95; // Friction
      carousel.scrollLeft -= this.velocity * 16;
      
      if (Math.abs(this.velocity) > 0.1) {
        this.rafId = requestAnimationFrame(animate);
      } else {
        this.velocity = 0;
      }
    };
    
    this.rafId = requestAnimationFrame(animate);
  }

  onScroll() {
    // Reset velocity when user manually scrolls
    this.velocity = 0;
    if (this.rafId) {
      cancelAnimationFrame(this.rafId);
      this.rafId = null;
    }
  }

  // Update existing scroll methods


  // Cleanup
  ngOnDestroy() {
    if (this.rafId) {
      cancelAnimationFrame(this.rafId);
    }
  }
}
