/**
 * Blog listing page — fetches published posts from the Brainerce blog API.
 *
 * Merchants manage posts in the Brainerce dashboard under Sell → Blog.
 * The storefront renders them here. Each post links to /blog/[slug].
 *
 * Posts are only visible when status=PUBLISHED and publishedAt <= NOW().
 * Category and tag filtering available via query params.
 */
import * as React from 'react';
import type { Metadata } from 'next';
import Link from 'next/link';
import { CdnImage as Image } from '@/ui/shared/cdn-image';

import { getServerClient } from '@/core/lib/brainerce.server';

<% if (i18nEnabled) { %>
type PageProps = {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ category?: string; tag?: string; page?: string }>;
};

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { locale } = await params;
  return {
    title: locale === 'he' ? 'בלוג' : 'Blog',
    description: locale === 'he' ? 'מאמרים וסיפורים מהחנות' : 'Articles and stories from our store',
  };
}

export default async function BlogListPage({ params, searchParams }: PageProps) {
  const { locale } = await params;
  const { category, tag, page: pageParam } = await searchParams;
  const page = Number(pageParam ?? '1') || 1;

  const client = await getServerClient(locale);
  const { data: posts, meta } = await client.blog
    .getPosts({ category, tag, page, limit: 12 })
    .catch(() => ({ data: [], meta: { page: 1, limit: 12, total: 0, totalPages: 1 } }));

  const isHe = locale === 'he';
  const dir = isHe ? 'rtl' : 'ltr';
  const emptyLabel = isHe ? 'עדיין אין פוסטים.' : 'No posts yet.';
  const blogLabel = isHe ? 'בלוג' : 'Blog';
  const readMoreLabel = isHe ? 'קרא עוד' : 'Read more';
  const prevLabel = isHe ? 'הקודם' : 'Previous';
  const nextLabel = isHe ? 'הבא' : 'Next';

  return (
    <main dir={dir} className="mx-auto max-w-6xl px-4 py-10 sm:px-6 lg:px-8">
      <h1 className="mb-8 text-3xl font-bold tracking-tight text-foreground sm:text-4xl">
        {blogLabel}
      </h1>

      {posts.length === 0 ? (
        <p className="text-muted-foreground">{emptyLabel}</p>
      ) : (
        <>
          <div className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
            {posts.map((post) => (
              <article
                key={post.id}
                className="group flex flex-col overflow-hidden rounded-xl border border-border/60 bg-card shadow-sm transition-shadow hover:shadow-md"
              >
                {post.coverImageUrl && (
                  <Link href={`/blog/${encodeURIComponent(post.slug)}`} tabIndex={-1}>
                    <div className="relative aspect-[16/9] overflow-hidden">
                      <Image
                        src={post.coverImageUrl}
                        alt={post.coverImageAlt ?? post.title}
                        fill
                        className="object-cover transition-transform duration-300 group-hover:scale-105"
                        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                      />
                    </div>
                  </Link>
                )}

                <div className="flex flex-1 flex-col gap-3 p-5">
                  {/* Category badge */}
                  {post.category && (
                    <span className="w-fit rounded-full bg-primary/10 px-2.5 py-0.5 text-xs font-medium text-primary">
                      {post.category}
                    </span>
                  )}

                  {/* Title */}
                  <Link href={`/blog/${encodeURIComponent(post.slug)}`}>
                    <h2 className="line-clamp-2 text-lg font-semibold leading-snug text-foreground hover:text-primary transition-colors">
                      {post.title}
                    </h2>
                  </Link>

                  {/* Excerpt */}
                  {post.excerpt && (
                    <p className="line-clamp-3 text-sm text-muted-foreground leading-relaxed">
                      {post.excerpt}
                    </p>
                  )}

                  {/* Meta: author + date */}
                  <div className="mt-auto flex items-center gap-2 pt-2 text-xs text-muted-foreground">
                    {post.author && <span>{post.author}</span>}
                    {post.author && post.publishedAt && <span>·</span>}
                    {post.publishedAt && (
                      <time dateTime={post.publishedAt}>
                        {new Date(post.publishedAt).toLocaleDateString(isHe ? 'he-IL' : 'en-US', {
                          year: 'numeric',
                          month: 'short',
                          day: 'numeric',
                        })}
                      </time>
                    )}
                  </div>

                  <Link
                    href={`/blog/${encodeURIComponent(post.slug)}`}
                    className="mt-1 text-sm font-medium text-primary hover:underline"
                  >
                    {readMoreLabel} →
                  </Link>
                </div>
              </article>
            ))}
          </div>

          {/* Pagination */}
          {meta.totalPages > 1 && (
            <nav className="mt-10 flex items-center justify-center gap-4">
              {page > 1 && (
                <Link
                  href={`/blog?page=${page - 1}${category ? `&category=${category}` : ''}${tag ? `&tag=${tag}` : ''}`}
                  className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted transition-colors"
                >
                  {prevLabel}
                </Link>
              )}
              <span className="text-sm text-muted-foreground">
                {page} / {meta.totalPages}
              </span>
              {page < meta.totalPages && (
                <Link
                  href={`/blog?page=${page + 1}${category ? `&category=${category}` : ''}${tag ? `&tag=${tag}` : ''}`}
                  className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted transition-colors"
                >
                  {nextLabel}
                </Link>
              )}
            </nav>
          )}
        </>
      )}
    </main>
  );
}
<% } else { %>
type PageProps = {
  searchParams: Promise<{ category?: string; tag?: string; page?: string }>;
};

export const metadata: Metadata = {
  title: 'Blog',
  description: 'Articles and stories from our store',
};

export default async function BlogListPage({ searchParams }: PageProps) {
  const { category, tag, page: pageParam } = await searchParams;
  const page = Number(pageParam ?? '1') || 1;

  const client = await getServerClient();
  const { data: posts, meta } = await client.blog
    .getPosts({ category, tag, page, limit: 12 })
    .catch(() => ({ data: [], meta: { page: 1, limit: 12, total: 0, totalPages: 1 } }));

  return (
    <main className="mx-auto max-w-6xl px-4 py-10 sm:px-6 lg:px-8">
      <h1 className="mb-8 text-3xl font-bold tracking-tight text-foreground sm:text-4xl">
        Blog
      </h1>

      {posts.length === 0 ? (
        <p className="text-muted-foreground">No posts yet.</p>
      ) : (
        <>
          <div className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
            {posts.map((post) => (
              <article
                key={post.id}
                className="group flex flex-col overflow-hidden rounded-xl border border-border/60 bg-card shadow-sm transition-shadow hover:shadow-md"
              >
                {post.coverImageUrl && (
                  <Link href={`/blog/${encodeURIComponent(post.slug)}`} tabIndex={-1}>
                    <div className="relative aspect-[16/9] overflow-hidden">
                      <Image
                        src={post.coverImageUrl}
                        alt={post.coverImageAlt ?? post.title}
                        fill
                        className="object-cover transition-transform duration-300 group-hover:scale-105"
                        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                      />
                    </div>
                  </Link>
                )}

                <div className="flex flex-1 flex-col gap-3 p-5">
                  {post.category && (
                    <span className="w-fit rounded-full bg-primary/10 px-2.5 py-0.5 text-xs font-medium text-primary">
                      {post.category}
                    </span>
                  )}

                  <Link href={`/blog/${encodeURIComponent(post.slug)}`}>
                    <h2 className="line-clamp-2 text-lg font-semibold leading-snug text-foreground hover:text-primary transition-colors">
                      {post.title}
                    </h2>
                  </Link>

                  {post.excerpt && (
                    <p className="line-clamp-3 text-sm text-muted-foreground leading-relaxed">
                      {post.excerpt}
                    </p>
                  )}

                  <div className="mt-auto flex items-center gap-2 pt-2 text-xs text-muted-foreground">
                    {post.author && <span>{post.author}</span>}
                    {post.author && post.publishedAt && <span>·</span>}
                    {post.publishedAt && (
                      <time dateTime={post.publishedAt}>
                        {new Date(post.publishedAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'short',
                          day: 'numeric',
                        })}
                      </time>
                    )}
                  </div>

                  <Link
                    href={`/blog/${encodeURIComponent(post.slug)}`}
                    className="mt-1 text-sm font-medium text-primary hover:underline"
                  >
                    Read more →
                  </Link>
                </div>
              </article>
            ))}
          </div>

          {meta.totalPages > 1 && (
            <nav className="mt-10 flex items-center justify-center gap-4">
              {page > 1 && (
                <Link
                  href={`/blog?page=${page - 1}${category ? `&category=${category}` : ''}${tag ? `&tag=${tag}` : ''}`}
                  className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted transition-colors"
                >
                  Previous
                </Link>
              )}
              <span className="text-sm text-muted-foreground">
                {page} / {meta.totalPages}
              </span>
              {page < meta.totalPages && (
                <Link
                  href={`/blog?page=${page + 1}${category ? `&category=${category}` : ''}${tag ? `&tag=${tag}` : ''}`}
                  className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted transition-colors"
                >
                  Next
                </Link>
              )}
            </nav>
          )}
        </>
      )}
    </main>
  );
}
<% } %>
