import { Component, inject, signal } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

interface ArticleData {
  id: number;
  title: string;
  content: string;
  author: string;
  date: string;
  image: string | null;
}

@Component({
  selector: 'app-article',
  imports: [RouterLink],
  templateUrl: './article.html',
  styleUrl: './article.css'
})
export class Article {
  private route = inject(ActivatedRoute);
  private http = inject(HttpClient);
  private sanitizer = inject(DomSanitizer);

  article = signal<ArticleData | null>(null);
  loading = signal<boolean>(true);
  error = signal<string | null>(null);

  trustHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }

  constructor() {
    this.route.params.subscribe(params => {
      const id = params['id'];
      this.fetchArticle(id);
    });
  }

  private fetchArticle(id: string): void {
    this.loading.set(true);
    this.error.set(null);

    this.http.get<ArticleData>(`/api/v3/blue/blog/articles/${id}.json`).subscribe({
      next: (data) => {
        this.article.set(data);
        this.loading.set(false);
      },
      error: (err) => {
        this.error.set('Failed to load article');
        this.loading.set(false);
        console.error('Error fetching article:', err);
      }
    });
  }
}
