import { Component, createSignal, onMount, For } from 'solid-js';
import { initAnalytics, trackPageView } from '../hooks/useAnalytics';
import WaitlistForm from '../components/WaitlistForm';
import Footer from '../components/Footer';

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

interface Pagination {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

const BlogPage: Component = () => {
  const [posts, setPosts] = createSignal<BlogPost[]>([]);
  const [pagination, setPagination] = createSignal<Pagination | null>(null);
  const [loading, setLoading] = createSignal(true);

  onMount(async () => {
    initAnalytics();
    trackPageView('/blog', 'Blog — Free Rights & Strategies');

    try {
      const res = await fetch('/api/blog?limit=10');
      if (res.ok) {
        const data = await res.json();
        setPosts(data.posts);
        setPagination(data.pagination);
      }
    } catch {
      // handle error silently
    } finally {
      setLoading(false);
    }
  });

  return (
    <main>
      <div class="blog-page-header">
        <div class="container">
          <a href="/" class="back-link">← Back to ShieldAI</a>
          <h1>Free Rights & Strategies</h1>
          <p>Educational guides to protect yourself and your family from AI-powered scams.</p>
        </div>
      </div>

      <section class="blog-page-content">
        <div class="container">
          {loading() ? (
            <p class="loading">Loading articles...</p>
          ) : posts().length === 0 ? (
            <div class="empty-state">
              <h2>Coming Soon</h2>
              <p>Our educational blog posts are being written. Join the waitlist to be notified when we publish.</p>
            </div>
          ) : (
            <>
              <div class="blog-list">
                <For each={posts()}>
                  {(post) => (
                    <a href={`/blog/${post.slug}`} class="blog-list-item">
                      {post.coverImageUrl && (
                        <div class="blog-list-image">
                          <img src={post.coverImageUrl} alt={post.title} loading="lazy" />
                        </div>
                      )}
                      <div class="blog-list-body">
                        <div class="blog-list-tags">
                          <For each={post.tags}>
                            {(tag) => <span class="tag">{tag}</span>}
                          </For>
                        </div>
                        <h2>{post.title}</h2>
                        {post.excerpt && <p>{post.excerpt}</p>}
                        <div class="blog-list-meta">
                          {post.authorName && <span>{post.authorName}</span>}
                          {post.publishedAt && (
                            <span>{new Date(post.publishedAt).toLocaleDateString()}</span>
                          )}
                          <span>{post.viewCount} views</span>
                        </div>
                      </div>
                    </a>
                  )}
                </For>
              </div>

              {pagination() && pagination()!.totalPages > 1 && (
                <div class="pagination">
                  <span>Page {pagination()!.page} of {pagination()!.totalPages}</span>
                </div>
              )}
            </>
          )}
        </div>
      </section>

      <section class="blog-waitlist-cta">
        <div class="container">
          <h2>Stay Protected</h2>
          <p>Get notified when we publish new guides and early access to ShieldAI.</p>
          <WaitlistForm variant="hero" buttonText="Get Notified" placeholder="your@email.com" />
        </div>
      </section>

      <Footer />
    </main>
  );
};

export default BlogPage;
