// src/app/components/blog-post/blog-post.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { BlogService } from '../services/blog.service';
import { FooterComponent } from './footer.component';
import { HeaderComponent } from './header.component';

@Component({
  selector: 'app-blog-post',
  standalone: true,
  imports: [CommonModule, HeaderComponent, FooterComponent],
  template: `
    <app-header></app-header>
    @if(safeContent){
    <section class="py-20 bg-gray-200 m-auto" data-aos="fade-up">
      <div class="container mx-auto px-6 max-w-[1024px]">
        <button (click)="goBack()" class="text-blue-600 hover:underline mb-4">← Back to Latest Insights</button>
        <h2 class="text-3xl font-bold mb-4">{{ post?.title }}</h2>
        <img [src]="post?.image" [alt]="post?.title" class="rounded-lg mb-6 shadow-lg w-full h-auto object-cover" />
        <div class="text-gray-700" [innerHTML]="safeContent"></div>
      </div>
    </section>
    }
    <app-footer></app-footer>
  `
})
export class BlogPostComponent implements OnInit {
  post: any;
  safeContent: SafeHtml | null = null;

  constructor(
    private route: ActivatedRoute, 
    private router: Router,
    private blogService: BlogService,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    const postId = this.route.snapshot.paramMap.get('id');
    this.post = this.blogService.getPost(postId);

    if (this.post && this.post.content) {
      this.safeContent = this.sanitizer.bypassSecurityTrustHtml(this.post.content);
    } else {
      // Redirect to a 404 page or display an error message
      this.router.navigate(['**']);
    }
  }
  ngAfterViewInit(){
    
  }
  goBack() {
    this.router.navigate(['']);
  }
}
