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

@Component({
  selector: 'app-episode',
  standalone: true,
  imports: [HeaderComponent, CommonModule],
  templateUrl: './episode.component.html',
  styleUrl: './episode.component.css'
})
export class EpisodeComponent {
stories: any[] = [];
  isLoading = true;
  errorMessage = '';
    selectedLanguage: string = 'en';
  messageMap: { [key: number]: string } = {};
  storyImgPath = 'https://infoways.in/funtelapi/';
  storyId: number | null = null;
  deleteMessage = '';
  isOwnProfile: boolean = false;
viewingUserId: string = '';
userId: string = '';
  constructor(private http: HttpClient, 
    public translationService: TranslationService, 
            private languageService: LanguageService ,
            private router:Router, private route: ActivatedRoute, private authService: AuthService) { }

  ngOnInit(): void {
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
    
  const userId = this.authService.getCurrentUserId();
  if (!userId) {
    this.router.navigate(['login']);
    return;
  }
  
  
const param = this.route.snapshot.paramMap.get('idAndTitle');

  if (param) {
    const id = param.split('-')[0];
    this.storyId = Number(id);
    
    console.log ('storyId', this.storyId);
  }
  this.fetchStories();
  
}

t(key: string): string {
    return this.translationService.translate(key);
  }
 fetchStories() {
  const userId = this.authService.getCurrentUserId();
  if (!userId) {
    this.errorMessage = 'Please login to view your stories';
    this.isLoading = false;
    this.router.navigate(['/login']);
    return;
  }

  this.userId = userId.toString();

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

  this.http.post<{ status: string, data: any[] }>(
    `https://infoways.in/funtelapi/draft_get_ep.php?stories_id=${this.storyId}`,
    { user_id: userId },
    { headers, withCredentials: true }
  ).subscribe({
    next: (response) => {
      if (response.status === 'success' && response.data) {
        this.stories = response.data;

        // Get the user_id from the first story in the array
        const storyUserId = response.data[0]?.user_id?.toString();
        this.viewingUserId = storyUserId || '';
        
        // Compare the IDs
        this.isOwnProfile = (this.viewingUserId === this.userId);
        
        console.log('Current User ID:', this.userId);
        console.log('Story User ID:', this.viewingUserId);
        console.log('Is own profile?', this.isOwnProfile);
      } else {
        this.errorMessage = 'Story not found.';
      }
      this.isLoading = false;
    },
    error: (error) => {
      console.error('Error fetching story:', error);
      this.errorMessage = 'Failed to load story. Please try again later.';
      this.isLoading = false;
    }
  });
}


// goToEdit(story: any) {
//   this.messageMap = {};
//   // if (story.status === '1') {
//   //   this.messageMap[story.id]  = 'This story has already been published and cannot be edited.';
//   //   return;
//   // }
//   const slug = this.slugify(story.story_title);
//   const partId = story.id;
//   this.router.navigate(['/story-write', `${partId}-${slug}`]);
// }

goToEdit(story: any) {
  // Make sure we have the episode ID (use story.episode_id or fallback to this.storyId)
  const episodeId = story.episode_id || this.storyId;
  
  if (!episodeId) {
    console.error('No episode ID available');
    alert('Cannot edit - missing episode reference');
    return;
  }

  const slug = this.slugify(story.story_title);
  const partId = story.id;
  
  this.router.navigate(
    ['/story-write', `${partId}-${slug}`],
    { 
      queryParams: { episodeId: episodeId },
      queryParamsHandling: 'merge'
    }
  );
}

goToCreate() {
  if (this.storyId) {
    console.log('Navigating to create page with storyId:', this.storyId);
    this.router.navigate(['/creat', this.storyId]); // Match your router path exactly
  } else {
    console.error('No story ID available');
    // Optionally navigate to a fallback route or show an error
    this.router.navigate(['/stories']); // Example fallback
  }
  
}
slugify(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[\s\W-]+/g, '-')     // replace spaces and non-word chars with -
    .replace(/^-+|-+$/g, '');       // remove leading/trailing dashes
}
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 || '';
}
deleteStory(contentId: number) {
  if (!confirm('Are you sure you want to delete this episode?')) {
    return;
  }

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

  this.http.post<{ status: string, message: string }>(
    'https://infoways.in/funtelapi/allstory.php?action=deleteContent',
    { id: contentId },  // ✅ Must use 'id' to match PHP
    { headers, withCredentials: true }
  ).subscribe({
    next: (response) => {
      if (response.status === 'success') {
        this.stories = this.stories.filter(s => s.id !== contentId);
        console.log('Deleted:', response.message);
      } else {
        console.warn('Delete failed:', response.message);
      }
    },
    error: (err) => {
      console.error('Error deleting episode:', err);
    }
  });
}
editStory(storyData: any) {
  // Get these values from your story data
  const episodeId = storyData.episode_id; // e.g. 107 (from your API)
  const editStoryId = storyData.story_id; // e.g. 1099176 (from your API)
  const title = storyData.story_title; // e.g. 'fsfsdds'
  
  this.router.navigate(
    ['/story-write', `${editStoryId}-${this.slugify(title)}`],
    { queryParams: { episodeId: episodeId } }
  );
}
}
