import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router, ɵEmptyOutletComponent } from '@angular/router';
import { AllapiService } from '../allapi.service';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from '../header/header.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CommentSectionComponent } from '../comment-section/comment-section.component';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { normalizeStoryText } from '../utils/text-normalizer';
import { AuthService } from '../auth.service';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';


@Component({
  selector: 'app-series',
  standalone: true,
  imports: [HeaderComponent, CommonModule, CommentSectionComponent],
  templateUrl: './series.component.html',
  styleUrl: './series.component.css'
})
export class SeriesComponent implements OnInit {
  storyId: number | null = null;
  storyContent: any = null;
  storyDetail: any = {}; 
  currentUser: any = null; 
  allParts: any[] = [];
  isLoading = true;
  errorMessage = '';
  scrollProgress = '0%';
  partsLoaded = false;
  isSpeaking = false;
  isFullscreen = false;
  userId: number | null = null;
  selectedLanguage: string = 'en';
   hideAuthorImage = false;
    storyImgPath = 'https://infoways.in/funtelapi/';
  private followStatusChecked = true;
   
    followerCount: number = 0;
followerUsers: any[] = [];

  fontSize = 1;
  readerMode: 'light' | 'dark' | 'reading' = 'light';
  isFollowing: boolean = false;
  userRating: number = 0;
averageRating: number = 0;
totalRatings: number = 0;
videoUrl:string = 'https://funtel.b-cdn.net/';

  @ViewChild('storyContentBox') storyContentDiv!: ElementRef;
  @ViewChild('audioPlayer') audioPlayer!: ElementRef<HTMLAudioElement>;
isPlaying = false;
progressBarWidth = '0%';
currentTimeDisplay = '0:00';
durationDisplay = '0:00';
audioLoaded = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private contentService: AllapiService,
    private http: HttpClient,
    private sanitizer: DomSanitizer,
    public translationService: TranslationService,
          private languageService: LanguageService ,
    private authService: AuthService
  ) {}
  ngAfterViewInit() {
  if (this.audioPlayer) {
    this.audioPlayer.nativeElement.addEventListener('loadedmetadata', () => {
      this.audioLoaded = true;
      this.updateDurationDisplay();
    });
  }
}

  ngOnInit(): void {
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    // ✅ Language changes subscribe karein
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
    window.scrollTo(0, 0);
    // const uid = sessionStorage.getItem('userId');
    // if (!uid) {
    //   this.router.navigate(['/login']);
    //   return;
    // }
    // this.userId = +uid;
    const userId = this.authService.getCurrentUserId();
    if (userId) {
      this.userId = +userId;
    }

    this.route.paramMap.subscribe(params => {
      const param = params.get('idAndTitle');
      if (param) {
        const id = Number(param.split('-')[0]);
        this.storyId = id;
        this.loadStory();
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    });
    this.loadRatings();
  }
  // Audio Player Methods

  toggleAudioPlayback() {
  if (!this.storyContent?.audio) return;

  if (this.isPlaying) {
    this.audioPlayer.nativeElement.pause();
  } else {
    this.audioPlayer.nativeElement.play().catch(error => {
      console.error('Audio playback failed:', error);
    });
  }
  this.isPlaying = !this.isPlaying;
}
t(key: string): string {
    return this.translationService.translate(key);
  }
updateProgressBar() {
  if (!this.audioPlayer) return;
  
  const audio = this.audioPlayer.nativeElement;
  const progress = (audio.currentTime / audio.duration) * 100;
  this.progressBarWidth = `${progress}%`;
  this.updateCurrentTimeDisplay();
}

seekAudio(event: MouseEvent) {
  if (!this.audioPlayer || !this.audioLoaded) return;
  
  const progressBar = event.currentTarget as HTMLElement;
  const rect = progressBar.getBoundingClientRect();
  const seekPosition = (event.clientX - rect.left) / rect.width;
  
  this.audioPlayer.nativeElement.currentTime = seekPosition * this.audioPlayer.nativeElement.duration;
}

updateCurrentTimeDisplay() {
  const currentTime = Math.floor(this.audioPlayer.nativeElement.currentTime);
  const minutes = Math.floor(currentTime / 60);
  const seconds = currentTime % 60;
  this.currentTimeDisplay = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
}

updateDurationDisplay() {
  const duration = Math.floor(this.audioPlayer.nativeElement.duration);
  const minutes = Math.floor(duration / 60);
  const seconds = duration % 60;
  this.durationDisplay = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
}

onAudioEnded() {
  this.isPlaying = false;
  this.progressBarWidth = '0%';
  this.currentTimeDisplay = '0:00';
}

  // End Audio Player Methods
loadRatings() {
  if (!this.storyId) return;
const headers = new HttpHeaders({
    'content-type': 'application/json',
  });
  this.http.post<any>(
    'https://infoways.in/funtelapi/get_rating.php',
    { story_id: this.storyId },
    { headers, withCredentials: true }
  ).subscribe({
    next: (res) => {
      this.userRating = res.user_rating || 0;
      this.averageRating = res.average_rating || 0;
      this.totalRatings = res.total_ratings || 0;
    },
    error: (err) => {
      console.error('Rating load failed', err);
    }
  });
}
submitRating(star: number) {
  // if (!this.userId || !this.storyId) return;
   const userId = this.authService.getCurrentUserId();
    if (!userId) { this.router.navigate(['login']); return; }
const headers = new HttpHeaders({
    'content-type': 'application/json',
  });
  this.http.post<any>(
  'https://infoways.in/funtelapi/save_rating.php',
  { story_id: this.storyId, rating: star },
  { headers, withCredentials: true }
  ).subscribe({
    next: (res) => {
      this.userRating = star;
      
      this.loadRatings(); // Refresh average & count
    },
    
    error: (err) => {
      console.error('Rating submit failed', err);
    }
  });
}
  toggleFullscreen(): void {
    this.isFullscreen = !this.isFullscreen;
    document.body.style.overflow = this.isFullscreen ? 'hidden' : '';
  }

  changeReaderMode(mode: 'light' | 'dark' | 'reading'): void {
    this.readerMode = mode;
  }

  getFollowingUsers() {
  if (!this.storyDetail?.author_id) return;

  const headers = new HttpHeaders({
    'content-type': 'application/json',
  });
  this.http.post<any>(
    'https://infoways.in/funtelapi/follow/check_follow.php',
    { following_id: this.storyDetail.author_id },
    { headers: headers, withCredentials: true }
  ).subscribe({
    next: (res) => {
      this.followerUsers = res.followersList || [];
      this.followerCount = res.followerCount || 0;
      console.log("followerCount", this.followerCount)
      console.log('Followers:', this.followerUsers);
    },
    error: (err) => {
      console.error('Failed to load followers', err);
    }
  });
}

  
fetchStoryDetail(storiesId: number) {
  const headers = new HttpHeaders({
    'content-type': 'application/json',
  });

  // 🔄 Refresh current userId here
  const userId = this.authService.getCurrentUserId();
  if (userId) {
    this.userId = +userId;
  }

  this.http.post<{ status: string; data: any }>(
    `https://infoways.in/funtelapi/getstorydetails.php?id=${storiesId}`,
    { headers, withCredentials: true }
  ).subscribe({
    next: (response) => {
      if (response.status === 'success' && response.data) {
        this.storyDetail = response.data;
        this.storyDetail.author_id = this.storyDetail.user_id;

        this.checkFollowStatus(); // ✅ now safe
        this.getFollowingUsers();
      } else {
        this.errorMessage = 'Story detail not found.';
      }
    },
    error: (error) => {
      console.error('Error fetching story detail:', error);
      this.errorMessage = 'Failed to load story detail.';
    }
  });
}
  loadStory(): void {
  if (!this.storyId) return;

  this.contentService.getStoryById(this.storyId).subscribe({
    next: (response: any) => {
      if (response.status === 'success' && response.data) {
        let content = response.data.content;
        content = normalizeStoryText(content);

        this.storyContent = {
          title: response.data.story_title,
          description: response.data.description,
          content: response.data.content,
          date: response.data.date || response.data.created_at || '',
          user_id: response.data.user_id,
          video_url: response.data.video_link 
    ? response.data.video_link.replace(/^\/+/, '') 
    : '',
          audio: response.data.audio 
        };

        const storiesId = response.data.stories_id;

        if (storiesId) {
          this.loadAllParts(storiesId);
          this.fetchStoryDetail(storiesId);
        }

        // ✅ Load the rating AFTER setting storyId
        this.loadRatings(); // 👈 Add this line here
      } else {
        this.errorMessage = 'Story not found';
      }
      this.isLoading = false;
    },
    error: (err) => {
      console.error('❌ Error loading story:', err);
      this.errorMessage = 'Error loading story.';
      this.isLoading = false;
    }
  });
}


getSafeVideoUrl(url: string): SafeResourceUrl | null {
  if (!url) return null;

  // YouTube long format
  if (url.includes('youtube.com/watch')) {
    const videoId = url.split('v=')[1]?.split('&')[0];
    return this.sanitizer.bypassSecurityTrustResourceUrl(`https://www.youtube.com/embed/${videoId}`);
  }

  // YouTube short format
  if (url.includes('youtu.be/')) {
    const videoId = url.split('youtu.be/')[1];
    return this.sanitizer.bypassSecurityTrustResourceUrl(`https://www.youtube.com/embed/${videoId}`);
  }

  // Vimeo
  if (url.includes('vimeo.com/')) {
    const videoId = url.split('vimeo.com/')[1];
    return this.sanitizer.bypassSecurityTrustResourceUrl(`https://player.vimeo.com/video/${videoId}`);
  }

  // fallback (assume it's already embed-safe)
  return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}


  loadAllParts(storiesId: number): void {
  const apiUrl = `https://infoways.in/funtelapi/get_user_ep.php?stories_id=${storiesId}`;
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    

  });

  this.http.post<{ status: string, data: any[] }>(
    apiUrl,
    { user_id: sessionStorage.getItem('userId') },
    { headers }
  ).subscribe({
    next: (res) => {
      if (res.status === 'success' && res.data) {
        this.allParts = res.data.filter(p => p.status == 1).sort((a, b) => a.id - b.id);
        this.partsLoaded = true;

        // ✅ Check if current part is last part
        const currentIndex = this.allParts.findIndex(p => p.id == this.storyId);
        const currentPart = this.allParts[currentIndex];

        if (currentPart) {
          const isLastPart = currentIndex === this.allParts.length - 1;

          // ✅ Update read progress if it's the last part
          this.storeReadProgress(
            storiesId,
            currentPart.id,
            this.allParts.length,
            currentPart.story_title
          );
        }
      }
    },
    error: (err) => {
      console.error('❌ Error loading parts:', err);
      this.allParts = [];
      this.partsLoaded = true;
    }
  });
}
checkFollowStatus(): void {
  const authorId = this.storyDetail?.author_id;
  if (!this.userId || !authorId || this.userId === authorId) {
    console.log('🟡 checkFollowStatus: invalid userId or authorId or same user');
    return;
  }

  console.log('🔄 Sending follow check:', this.userId, '→', authorId);

  const headers = new HttpHeaders({
    'content-type': 'application/json',
  });

  this.http.post<any>(
    'https://infoways.in/funtelapi/follow/check_follow.php',
    {
      follower_id: this.userId,
      following_id: authorId
    },
    { headers, withCredentials: true }
  ).subscribe({
    next: (res) => {
      this.isFollowing = res.isFollowing;
      console.log('✅ Follow check result:', res);
    },
    error: (err) => {
      console.error('❌ Follow check failed:', err);
    }
  });
}

  toggleFollow(): void {
    const authorId = this.storyDetail?.author_id;
    // if (!this.userId || !authorId) return;

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

    const apiUrl = this.isFollowing
      ? 'https://infoways.in/funtelapi/follow/unfollow.php'
      : 'https://infoways.in/funtelapi/follow/follow.php';

    const headers = new HttpHeaders({
   'content-type': 'application/json',
  });
    const body = {
      follower_id: this.userId,
      following_id: authorId
    };

    this.http.post<any>(apiUrl, body, { headers, withCredentials: true }).subscribe({
      next: (res) => {
        console.log('✅ Follow/Unfollow response:', res);
        this.isFollowing = !this.isFollowing;
      },
      error: (err) => {
        console.error('❌ Follow/Unfollow failed:', err);
      }
    });
  }
  continueToNextPart(): void {
  const currentIndex = this.allParts.findIndex(part => part.id == this.storyId);
  if (currentIndex !== -1 && currentIndex < this.allParts.length - 1) {
    const userId = this.authService.getCurrentUserId();

    // ✅ Check login
    if (!userId) {
      this.router.navigate(['/login']);
      return;
    }

    const nextPart = this.allParts[currentIndex + 1];

    // ✅ Save progress
    this.storeReadProgress(
      this.storyDetail.id,
      nextPart.id,
      this.allParts.length,
      nextPart.story_title
    );

    // ✅ Update internal state instead of reload
    this.storyId = nextPart.id;
    this.isLoading = true;
    this.storyContent = null;

    // ✅ Scroll to top before loading new content
    window.scrollTo({ top: 0, behavior: 'smooth' });

    // ✅ Load new story
    this.loadStory();

    // ✅ Update route URL without reload
    const slug = this.slugify(nextPart.story_title || 'story');
    this.router.navigate(['/series', `${nextPart.id}-${slug}`], { replaceUrl: true });

  } else {
    alert('✅ You are already on the last part.');
  }
}

  isLastPart(): boolean {
    if (!this.partsLoaded || !this.storyId || !this.allParts.length) return true;
    const currentIndex = this.allParts.findIndex(part => part.id == this.storyId);
    return currentIndex === -1 || currentIndex === this.allParts.length - 1;
  }

  isButtonDisabled(): boolean {
    return !this.partsLoaded || this.isLastPart();
  }

  slugify(text: string): string {
    return text.toLowerCase().trim().replace(/[\s\W-]+/g, '-').replace(/^-+|-+$/g, '');
  }
shareOnFacebook(event: Event): void {
  event.preventDefault();
  if (!this.storyContent || !this.storyDetail) {
    alert('Story data not loaded yet.');
    return;
  }

  const storyUrl = `https://infoways.in/funtelapi/${this.storyId}-${this.slugify(this.storyContent.title)}`;
  const imageUrl = this.storyDetail.story_image 
    ? `https://infoways.in/funtelapi/${this.storyDetail.user_id}/${this.storyDetail.story_image}`
    : 'https://infoways.in/funtelapi/default-story-image.jpg';

  const fbShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(storyUrl)}&picture=${encodeURIComponent(imageUrl)}&title=${encodeURIComponent(this.storyContent.title)}&description=${encodeURIComponent(this.storyContent.description)}`;
  
  window.open(fbShareUrl, '_blank', 'width=600,height=400');
}

shareOnTwitter(): void {
  if (!this.storyContent || !this.storyDetail) return;

  const storyUrl = `https://infoways.in/funtelapi/${this.storyId}-${this.slugify(this.storyContent.title)}`;
  const imageUrl = this.storyDetail.story_image 
    ? `https://infoways.in/funtelapi/${this.storyDetail.user_id}/${this.storyDetail.story_image}`
    : 'https://infoways.in/funtelapi/default-story-image.jpg';

  const text = `Check out this story: ${this.storyContent.title}`;
  const twitterUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(storyUrl)}&text=${encodeURIComponent(text)}&hashtags=Stories&via=YourAppName`;
  
  window.open(twitterUrl, '_blank', 'width=600,height=400');
}

shareOnWhatsApp(event: Event): void {
  event.preventDefault();
  if (!this.storyContent) return;

  const storyUrl = `https://infoways.in/funtelapi/${this.storyId}-${this.slugify(this.storyContent.title)}`;
  const text = `Check out this story: ${this.storyContent.title} - ${storyUrl}`;
  const whatsappUrl = `https://wa.me/?text=${encodeURIComponent(text)}`;
  
  window.open(whatsappUrl, '_blank', 'width=600,height=400');
}
adjustFontSize(action: 'increase' | 'decrease'): void {
  if (action === 'increase' && this.fontSize < 1.5) {
    this.fontSize += 0.1;
  } else if (action === 'decrease' && this.fontSize > 0.8) {
    this.fontSize -= 0.1;
  }
}

  @HostListener('window:scroll', [])
  onWindowScroll(): void {
    const scrollTop = window.scrollY || document.documentElement.scrollTop;
    const docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    const scrolled = (scrollTop / docHeight) * 100;
    this.scrollProgress = `${scrolled}%`;
  }
  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();
}
storeReadProgress(storyId: number, partId: number, totalParts: number, partTitle: string): void {
  console.log('📌 Storing progress for:', { storyId, partId, totalParts, partTitle }); 
  const userId = this.authService.getCurrentUserId();
  if (!userId) return;

  const key = `story_progress_${userId}`;
  const progressData = JSON.parse(localStorage.getItem(key) || '{}');

  if (!progressData[storyId]) {
    progressData[storyId] = {
      lastReadPartId: partId,
      readParts: [partId],
      totalParts: totalParts,
      lastPartTitle: partTitle,
      timestamp: Date.now()
    };
  } else {
    const entry = progressData[storyId];
    entry.lastReadPartId = partId;
    entry.lastPartTitle = partTitle;
    entry.timestamp = Date.now();
    if (!entry.readParts.includes(partId)) {
      entry.readParts.push(partId);
    }
  }

  localStorage.setItem(key, JSON.stringify(progressData));
}
onImageError(): void {
  this.hideAuthorImage = true;
}
}
