import { Component, createSignal, onMount, For } from 'solid-js';

interface BlogPost {
  slug: string;
  title: string;
  excerpt: string;
  authorName: string | null;
  coverImageUrl: string | null;
  tags: string[];
  publishedAt: string;
}

const BlogPreview: Component = () => {
  const [posts, setPosts] = createSignal<BlogPost[]>([]);

  onMount(async () => {
    try {
      const res = await fetch('/api/blog?limit=3');
      if (res.ok) {
        const data = await res.json();
        setPosts(data.posts);
      }
    } catch {
      // Blog may not be populated yet
    }
  });

  return (
    <section class="blog-preview" id="blog">
      <div class="container">
        <h2 class="section-title">Free Rights & Strategies</h2>
        <p class="section-subtitle">
          Educational guides to help you understand and protect against AI-powered threats.
        </p>

        {posts().length === 0 ? (
          <div class="blog-placeholder">
            <p>Blog posts coming soon. Sign up for the waitlist to get notified when we publish.</p>
          </div>
        ) : (
          <div class="blog-grid">
            <For each={posts()}>
              {(post) => (
                <a href={`/blog/${post.slug}`} class="blog-card">
                  {post.coverImageUrl && (
                    <div class="blog-card-image">
                      <img src={post.coverImageUrl} alt={post.title} loading="lazy" />
                    </div>
                  )}
                  <div class="blog-card-body">
                    <div class="blog-card-tags">
                      <For each={post.tags.slice(0, 2)}>
                        {(tag) => <span class="tag">{tag}</span>}
                      </For>
                    </div>
                    <h3>{post.title}</h3>
                    {post.excerpt && <p>{post.excerpt}</p>}
                    <div class="blog-card-meta">
                      {post.authorName && <span>{post.authorName}</span>}
                      {post.publishedAt && (
                        <span>{new Date(post.publishedAt).toLocaleDateString()}</span>
                      )}
                    </div>
                  </div>
                </a>
              )}
            </For>
          </div>
        )}

        <div class="blog-cta">
          <a href="/blog" class="btn-secondary">View All Articles</a>
        </div>
      </div>
    </section>
  );
};

export default BlogPreview;
