import { useTranslations } from "next-intl";
import { ArrowRight, ArrowLeft } from "lucide-react";
import { Link } from "@/lib/i18n/navigation";
import { SectionHeader } from "@/components/shared/SectionHeader";
import { Badge } from "@/components/ui/badge";
import { getLatestPosts, estimateReadTime } from "@/lib/db/posts";
import { formatDate } from "@/lib/types";

// Server component — fetches fresh posts from DB
export async function LatestWriting({ locale }: { locale: string }) {
  const posts = await getLatestPosts(locale, 5);

  return <LatestWritingUI posts={posts} locale={locale} />;
}

function LatestWritingUI({
  posts,
  locale,
}: {
  posts: Awaited<ReturnType<typeof getLatestPosts>>;
  locale: string;
}) {
  const t = useTranslations("sections");
  const tCommon = useTranslations("common");

  if (posts.length === 0) return null;

  return (
    <section className="relative z-10 px-6 py-16">
      <div className="mx-auto max-w-6xl">
        <div className="flex items-end justify-between mb-8">
          <SectionHeader label={t("latest_writing")} className="mb-0" />
          <Link
            href="/writing"
            className="hidden items-center gap-1 text-sm text-text-secondary hover:text-accent transition-colors md:flex"
          >
            {tCommon("read_more")} <ArrowRight size={14} />
          </Link>
        </div>

        <div className="divide-y divide-border">
          {posts.map((post) => {
            const readTime = post.body ? estimateReadTime(post.body) : null;
            return (
              <Link
                key={post.id}
                href={`/writing/${post.slug}`}
                className="group flex items-start justify-between gap-4 py-5 hover:text-text-primary transition-colors"
              >
                <div className="flex-1">
                  <div className="mb-2 flex items-center gap-2">
                    <Badge variant="secondary" className="text-xs">
                      {post.category}
                    </Badge>
                    <span className="font-mono text-xs text-text-secondary">
                      {formatDate(post.publishedAt, locale)}
                    </span>
                  </div>
                  <h3 className="text-base font-medium text-text-primary group-hover:text-accent transition-colors">
                    {post.title}
                  </h3>
                </div>
                <div className="flex items-center gap-2 mt-1 shrink-0">
                  {readTime && (
                    <span className="font-mono text-xs text-text-secondary">{readTime} دقیقه</span>
                  )}
                  <ArrowLeft
                    size={14}
                    className="text-text-secondary opacity-0 transition-opacity group-hover:opacity-100 rtl:rotate-180"
                  />
                </div>
              </Link>
            );
          })}
        </div>
      </div>
    </section>
  );
}
