import { Component, OnInit, inject, signal } from '@angular/core';
import { DatePipe } from '@angular/common';
import { RouterModule } from '@angular/router';
import { BlogService } from '@core/services/blog.service';
import { SeoService } from '@core/services/seo.service';
import { OpenPanelTrackDirective } from '@core/directives/openpanel.directive';
import { BlogPost } from '@core/models/blog-posts.model';
import { BlogNavComponent } from '../../components/blog-nav/blog-nav.component';

@Component({
  selector: 'app-blog-list',
  imports: [RouterModule, DatePipe, OpenPanelTrackDirective, BlogNavComponent],
  templateUrl: './blog-list.component.html',
  styleUrl: './blog-list.component.scss',
})
export class BlogListComponent implements OnInit {
  private readonly blogService = inject(BlogService);
  private readonly seo = inject(SeoService);

  posts = signal<BlogPost[]>([]);
  loading = signal(true);
  error = signal<string | null>(null);

  ngOnInit(): void {
    this.seo.updateMetadata({
      title: 'Blog – Webdesign-Tipps & Einblicke',
      description: 'Artikel rund um Webdesign, Performance und digitale Präsenz für Handwerk und Vereine.',
      type: 'website',
    });

    this.blogService.getPosts().subscribe({
      next: (posts) => {
        this.posts.set(posts);
        this.loading.set(false);
      },
      error: () => {
        this.error.set('Die Artikel konnten nicht geladen werden. Bitte versuche es später erneut.');
        this.loading.set(false);
      },
    });
  }

  getCoverUrl(post: BlogPost): string | null {
    if (!post.cover_image) return null;
    return this.blogService.getAssetUrl(post.cover_image, { width: 640, quality: 80 });
  }

  formatDate(dateStr: string): string {
    return dateStr;
  }
}
