import { Component } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { CommonModule } from '@angular/common';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { slugify as translitSlug } from 'transliteration';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';

@Component({
  selector: 'app-story',
  standalone: true,
  imports: [HeaderComponent, CommonModule],
  templateUrl: './story.component.html',
  styleUrl: './story.component.css'
})
export class StoryComponent {
  // UI state
  libraryMessage = '';
  isLoading = true;
  errorMessage = '';

  // Story + chapters
  storyId: number | null = null;
  storyDetail: any = null;
  stories: any[] = [];

  // Author / follow
  isFollowing = false;
  followerUsers: any[] = [];
  followerCount = 0;

  // Logged‑in user
  userId: number | null = null;

  // Library data (stories liked by logged‑in user)
  likedStories: number[] = [];
  libraryStories: any[] = [];   // <-- full objects so we can use author assets

  // Rating stars
  starArray: string[] = [];

  // Author assets (resolved/full URLs)
  authorProfileUrl = '';
 
  authorCoverUrl = '';
  authorInitial = 'U';
  hideAuthorImage = false;
selectedLanguage: string = 'en';
  defaultProfileImage = 'default-profile.png';

  // Base API path
  storyImgPath = 'https://infoways.in/funtelapi/';

  constructor(
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute,
    private authService: AuthService,
    public translationService: TranslationService,
          private languageService: LanguageService 
  ) {}

  ngOnInit(): void {
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    // ✅ Language changes subscribe karein
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
  window.scrollTo(0, 0);

  this.authService.currentUser$.subscribe(user => {
    if (user?.id) {
      this.userId = +user.id;
    } else {
      console.log('⚠️ User not logged in or not yet loaded');
    }
  });

  // Wait for both story and library to finish
  this.route.paramMap.subscribe(async params => {
    const param = params.get('idAndTitle');
    if (!param) return;

    const id = param.split('-')[0];
    this.storyId = Number(id);

    // Load story detail
    await this.fetchStoryDetail();

    // Load chapters
    this.fetchStories();

    // Load library, then apply assets again
    await this.loadLibrary();
    this.applyAuthorAssetsFromLibrary();

    // Load followers after storyDetail is loaded
    this.getFollowingUsers();
  });
}
t(key: string): string {
    return this.translationService.translate(key);
  }
  /* ------------------------------------------------------------------
   * Helpers
   * ------------------------------------------------------------------ */
  private normPath(p: string | null | undefined): string {
    return p ? p.replace(/^\/+/, '') : '';
  }
  private fullAsset(rel?: string | null): string {
  if (!rel || rel.trim() === '' || rel === 'null') {
    return '';
  }
  const path = rel.replace(/^\/+/, '');
  return `${this.storyImgPath}${path}`;
}

  scrollToChapters(): void {
    const el = document.getElementById('chapters');
    if (el) el.scrollIntoView({ behavior: 'smooth' });
  }
  viewProfile(authorId: string) {
  this.router.navigate(['/profile', authorId]);
}

  /* ------------------------------------------------------------------
   * Story detail (single story header info)
   * ------------------------------------------------------------------ */
  fetchStoryDetail(): Promise<void> {
  return new Promise((resolve) => {
    if (!this.storyId) return resolve();

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

    this.http.post<{ status: string; data: any }>(
      `${this.storyImgPath}/getstorydetails.php?id=${this.storyId}`,
      {},
      { headers }
    ).subscribe({
      next: (response) => {
        if (response.status === 'success' && response.data) {
          this.storyDetail = response.data;
          console.log('Story detail response:', this.storyDetail);
          this.storyDetail.author_id = this.storyDetail.user_id;

          const rating = +this.storyDetail.average_rating || 0;
          this.starArray = this.getStarArray(rating);

          // Build from detail
          console.log('Story detail loaded:', this.storyDetail);
          this.buildAuthorAssetsFromDetail();
          console.log('Building assets from detail:', {
  name: this.storyDetail.author_name,
  profileRaw: this.storyDetail.profileimg_url,
  coverRaw: this.storyDetail.coverimage_url
});

          this.checkFollowStatus();
          resolve();
        } else {
          this.errorMessage = 'Story detail not found.';
          resolve();
        }
      },
      error: (error) => {
        console.error('❌ Error fetching story detail:', error);
        this.errorMessage = 'Failed to load story detail.';
        resolve();
      }
    });
  });
}

  private buildAuthorAssetsFromDetail(): void {
  if (!this.storyDetail) {
    this.authorProfileUrl = '';
    this.authorInitial = 'U';
    this.hideAuthorImage = true;
    return;
  }

  // Reset image visibility when loading new assets
  this.hideAuthorImage = false;

  // Set author initial
  const name = this.storyDetail.author_name || (this.storyDetail as any).name || '';
  this.authorInitial = name ? name.trim().charAt(0).toUpperCase() : 'U';

  // Get profile image URL
  const profRaw = this.storyDetail.profileimg_url ?? 
                 this.storyDetail.profileImg ?? 
                 this.storyDetail.profileimg ?? 
                 this.storyDetail.author_profile ??
                 '';

  this.authorProfileUrl = this.fullAsset(profRaw);
  console.log('Built author profile URL:', this.authorProfileUrl);
}

  /* ------------------------------------------------------------------
   * Chapters list for story
   * ------------------------------------------------------------------ */
  fetchStories(): void {
    if (!this.storyId) return;

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

    this.http.post<{ status: string; data: any[] }>(
      `${this.storyImgPath}/get_user_ep.php?stories_id=${this.storyId}`,
      { headers }
    ).subscribe({
      next: (response) => {
        if (response.status === 'success' && response.data) {
          this.stories = response.data.map(story => {
            const content = story.content || '';
            const wordCount = content.split(/\s+/).length;
            const readTime = Math.ceil(wordCount / 200); // 200 wpm
            return { ...story, wordCount, readTime };
          });
        } else {
          this.errorMessage = 'Story not found.';
        }
        this.isLoading = false;
      },
      error: (error) => {
        console.error('Error fetching story:', error);
        this.errorMessage = 'Failed to load story.';
        this.isLoading = false;
      }
    });
  }

  /* ------------------------------------------------------------------
   * Library (liked stories)  **IMPORTANT**
   * We use this to fetch author profileImg / coverImg.
   * ------------------------------------------------------------------ */
  loadLibrary(): Promise<void> {
  return new Promise((resolve, reject) => {
    const userId = this.authService.getCurrentUserId();
    if (!userId) return resolve();

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

    this.http.get<any>(`${this.storyImgPath}/allstory.php?action=library&user_id=${userId}`,
      { headers:headers, withCredentials: true }

    )
      .subscribe({
        next: (res) => {
          if (res.status === 'success') {
            this.libraryStories = res.data || [];
            this.likedStories = this.libraryStories.map((s: any) => +s.id);
            this.applyAuthorAssetsFromLibrary();
            
          }
          resolve();
        },
        error: (err) => {
          console.error('Failed to load library:', err);
          reject(err);
        }
      });
  });
}

 
  private applyAuthorAssetsFromLibrary(): void {
  if (!this.storyId || !this.libraryStories?.length) return;

  const rec = this.libraryStories.find(s => 
    +s.id === this.storyId || +s.story_id === this.storyId
  );

  if (!rec) {
    console.log('No matching story found in library');
    return;
  }


  const authorName = rec.author_name || rec.name || '';
  const authorImg = rec.profileImg ;
  this.authorInitial = authorName.trim().charAt(0).toUpperCase() || 'U';
  console.log('Author name:', authorName, 'Initial:', this.authorInitial);
  this.authorProfileUrl = this.fullAsset(authorImg);
  console.log('Author profile image:', this.authorProfileUrl);
  
  const profileRaw = rec.profileImg || rec.profileimg || rec.profileimg_url || '';
  
 
  const profileUrl = this.fullAsset(profileRaw);
  console.log('Constructed profile URL:', profileUrl);

 
  if (profileUrl && !profileUrl.includes('null') && !profileUrl.endsWith('/')) {
    this.authorProfileUrl = profileUrl;
    console.log('✅ Using library profile image:', this.authorProfileUrl);
  } else {
    console.log('⚠️ Invalid profile URL, using default');
    this.authorProfileUrl = this.defaultProfileImage;
  }

  
  const coverRaw = rec.coverImg || rec.coverimg || rec.coverimage_url || '';
  this.authorCoverUrl = this.fullAsset(coverRaw);
}

  /* ------------------------------------------------------------------
   * Follow / Followers
   * ------------------------------------------------------------------ */
 getFollowingUsers(): void {
  if (!this.storyDetail?.author_id) return;

  const body: any = { following_id: this.storyDetail.author_id };
  if (this.userId) body.follower_id = this.userId; // ✅ include logged-in user

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

  this.http.post<any>(
    `${this.storyImgPath}/follow/check_follow.php`,
    body,
    { headers, withCredentials: true }
  ).subscribe({
    next: (res) => {
      this.followerUsers = res.followersList || [];
      this.followerCount = res.followerCount || 0;
      console.log("followerCount", this.followerCount)

      // ✅ use returned isFollowing if available
      if (typeof res.isFollowing !== 'undefined') {
        this.isFollowing = !!res.isFollowing;
      }

      console.log("followerCount", this.followerCount, "isFollowing", this.isFollowing);
    },
    error: (err) => {
      console.error('Failed to load followers', err);
    }
  });
}



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

    const headers = new HttpHeaders({
    'content-type': 'application/json',
  });
    this.http.post<any>(
      `${this.storyImgPath}/follow/check_follow.php`,
      { follower_id: this.userId, following_id: authorId },
      { headers, withCredentials: true }
    ).subscribe({
      next: (res) => {
        this.isFollowing = !!res.isFollowing;
      },
      error: (err) => {
        console.error('Follow check failed:', err);
      }
    });
  }

  toggleFollow(): void {
    const authorId = this.storyDetail?.author_id;
    const uid = this.userId;
    if (!uid) {
      this.router.navigate(['login']);
      return;
    }
    const apiUrl = this.isFollowing
      ? `${this.storyImgPath}/follow/unfollow.php`
      : `${this.storyImgPath}/follow/follow.php`;

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

    this.http.post<any>(apiUrl, body, { headers, withCredentials: true })
      .subscribe({
        next: () => {
          this.isFollowing = !this.isFollowing;
          this.getFollowingUsers(); // refresh counts
        },
        error: (err) => {
          console.error('Follow/Unfollow failed:', err);
        }
      });
  }

  /* ------------------------------------------------------------------
   * Library add/remove (like a story)
   * ------------------------------------------------------------------ */
  addToLibrary(storyId: number): void {
    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
    };
const headers = new HttpHeaders({
    'content-type': 'application/json',
  });
    this.http.post<any>(`${this.storyImgPath}/addstory.php`, body,{
      headers,
      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');
        }
      });
  }

  /* ------------------------------------------------------------------
   * Misc UI helpers
   * ------------------------------------------------------------------ */
  getStarArray(rating: number): string[] {
    const stars: string[] = [];
    const fullStars = Math.floor(rating);
    const frac = rating - fullStars;
    const hasHalfStar = frac >= 0.25 && frac < 0.75;

    for (let i = 0; i < fullStars; i++) stars.push('full');
    if (hasHalfStar) stars.push('half');
    while (stars.length < 5) stars.push('empty');
    return stars;
  }

  getTotalReadingTime(): number {
    return this.stories.reduce((sum, s) => sum + (s.readTime || 0), 0);
  }
  formatTotalReadTime(minutes: number): string {
    if (minutes >= 10080) { // 7d
      const weeks = Math.floor(minutes / 10080);
      const rem = minutes % 10080;
      return `${weeks} week${weeks > 1 ? 's' : ''}` + (rem ? ` ${this.formatTotalReadTime(rem)}` : '');
    } else if (minutes >= 1440) {
      const days = Math.floor(minutes / 1440);
      const rem = minutes % 1440;
      return `${days} day${days > 1 ? 's' : ''}` + (rem ? ` ${this.formatTotalReadTime(rem)}` : '');
    } else if (minutes >= 60) {
      const hrs = Math.floor(minutes / 60);
      const rem = minutes % 60;
      return `${hrs} hr${hrs > 1 ? 's' : ''}` + (rem ? ` ${rem} min` : '');
    } else {
      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();
  }

  slugify(text: string): string {
    return text.toLowerCase().trim()
      .replace(/[\s\W-]+/g, '-')
      .replace(/^-+|-+$/g, '');
      return translitSlug(text, { lowercase: true, separator: '-' });
  }


  /* Navigation */
  goToEdit(story: any): void {
    const slug = this.slugify(story.story_title);
    const partId = story.id;
    this.router.navigate(['/story-write', `${partId}-${slug}`]);
  }
  goToCreate(): void {
    if (!this.stories.length) return;
    const storyId = this.stories[0].stories_id;
    this.router.navigate(['/creat', storyId]);
  }
  goToSeries(story: any): void {
    this.incrementView(story.id).then(() => {
      const id = story.id;
      const slug = this.slugify(story.story_title || '');
      this.router.navigate(['/series', `${id}-${slug}`]);
    });
  }
  incrementView(contentId: number): Promise<void> {
    const headers = new HttpHeaders({
    'content-type': 'application/json',
  });
    return new Promise((resolve, reject) => {
      this.http.post(
        `${this.storyImgPath}increment_view.php`,
        { content_id: contentId },
        { headers }
      ).subscribe({
        next: () => resolve(),
        error: err => {
          console.error('Failed to increment view count', err);
          reject();
        }
      });
    });
  }
  handleChapterClick(index: number, story: any): void {
    if (index >= 1) {
     if (!this.userId) {
  this.router.navigate(['/login']);
  return;
}
    }
    this.goToSeries(story);
  }
onImageError(): void {
  this.hideAuthorImage = true;
}
getTimeAgo(dateString: string): string {
  if (!dateString) return '';

  // Convert to ISO format
  const parsedDate = new Date(dateString.replace(' ', 'T'));

  if (isNaN(parsedDate.getTime())) return 'Invalid date';

  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - parsedDate.getTime()) / 1000);

  if (diffInSeconds < 0) return 'Just now';

  const intervals = [
    { label: 'year', seconds: 31536000 },
    { label: 'month', seconds: 2592000 },
    { label: 'week', seconds: 604800 },
    { label: 'day', seconds: 86400 },
    { label: 'hour', seconds: 3600 },
    { label: 'minute', seconds: 60 },
    { label: 'second', seconds: 1 }
  ];

  for (const interval of intervals) {
    const count = Math.floor(diffInSeconds / interval.seconds);
    if (count >= 1) {
      return `${count} ${interval.label}${count > 1 ? 's' : ''} ago`;
    }
  }

  return 'Just now';
}
getValidDate(story: any): string {
  return story.updated_at || story.updated || story.updated_at || story.author_created_at || '';
}
}
