import { PhotoWithFallback } from '../elements';
import type { BlogPost } from '../../types/api/blog-post';

interface BlogHomeProps {
  blogPosts?: BlogPost[] | null;
  title?: string;
}

export const BlogHome = ({
  blogPosts: postsData,
  title = "",
}: BlogHomeProps) => {
  const posts = Array.isArray(postsData) ? postsData : [];

  return (
    <section>
      <div className="mx-auto max-w-container px-4 md:px-8">
        <div className="mb-12 text-center">
          <h2 className="font-display text-4xl font-normal text-fg-primary md:text-5xl">
            {title}
          </h2>
        </div>

        {posts.length > 0 ? (
          <div className="grid grid-cols-1 gap-12 md:grid-cols-2 lg:grid-cols-3">
            {posts.map((post) => {
              const excerpt = post.excerpt_markdown?.replace(/[#*\[\]()]/g, '').trim() || post.content_markdown?.replace(/[#*\[\]()]/g, '').trim().substring(0, 150) || '';
              
              return (
                <div key={post.id} className="flex flex-col">
                  <div className="w-full h-64 mb-6 overflow-hidden">
                    <PhotoWithFallback
                      item={post}
                      fallbackId={post.id}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  
                  <p className="text-xs font-body font-normal uppercase tracking-widest mb-2" style={{ color: 'var(--color-text-brand-secondary)' }}>
                    {post.published_at ? new Date(post.published_at).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : ''}
                  </p>
                  
                  <h3 className="font-display text-2xl font-normal text-fg-primary mb-4">
                    {post.title}
                  </h3>
                  
                  {excerpt && (
                    <p className="font-body text-base leading-relaxed text-tertiary mb-6 flex-grow">
                      {excerpt}
                    </p>
                  )}
                  
                  <a
                    href={`/blog/${post.slug}`}
                    className="font-body text-base underline underline-offset-4 hover:no-underline transition-colors"
                    style={{ color: 'var(--color-text-brand-accent)' }}
                  >
                    Read more
                  </a>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="font-body text-base text-tertiary">No posts available</p>
          </div>
        )}
      </div>
    </section>
  );
};

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('blog-home', 'aman', BlogHome);
