import { Component, inject, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { HttpClient } from '@angular/common/http';

interface Article {
  id: number;
  title: string;
  excerpt: string;
  date: string;
  image: string | null;
}

@Component({
  selector: 'app-home',
  imports: [RouterLink],
  templateUrl: './home.html',
  styleUrl: './home.css'
})
export class Home {
  private http = inject(HttpClient);
  articles = signal<Article[]>([]);

  constructor() {
    this.http.get<Article[]>('/api/v3/blue/blog/articles/all.json').subscribe({
      next: (data) => {
        // Sort by date descending (newest first)
        const sorted = data.sort((a, b) => {
          const dateA = this.parseDate(a.date);
          const dateB = this.parseDate(b.date);
          return dateB.getTime() - dateA.getTime();
        });
        this.articles.set(sorted);
      },
      error: (err) => {
        console.error('Failed to load articles:', err);
      }
    });
  }

  private parseDate(dateStr: string): Date {
    // Parse MM/DD/YYYY format
    const [month, day, year] = dateStr.split('/').map(Number);
    return new Date(year, month - 1, day);
  }
}
