import Link from "next/link";
import type { PostMeta } from "@/lib/posts";

type FieldNotesProps = {
  posts: PostMeta[];
};

function formatPostDate(date: string) {
  const parsed = new Date(date);

  if (Number.isNaN(parsed.getTime())) return date;

  return parsed.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "2-digit",
  });
}

export function FieldNotes({ posts }: FieldNotesProps) {
  const recentPosts = posts.slice(0, 4);

  return (
    <section
      id="notes"
      className="border-y border-blacksite-line bg-blacksite-bg2 px-6 py-28 text-blacksite-text sm:px-8 sm:py-36 lg:px-12"
    >
      <div className="mx-auto max-w-7xl">
        <div className="mb-12">
          <p className="section-label">FIELD NOTES /.06</p>
        </div>

        {recentPosts.length > 0 ? (
          <>
            <div className="divide-y divide-blacksite-line border-y border-blacksite-line">
              {recentPosts.map((post) => (
                <Link
                  key={post.slug}
                  href={`/blog/${post.slug}/`}
                  className="group grid gap-3 px-0 py-6 transition-colors hover:bg-blacksite-surface/55 focus-visible:outline-signal-cyan sm:grid-cols-[12rem_minmax(0,1fr)] sm:px-4"
                >
                  <time className="section-label pt-1" dateTime={post.date}>
                    {formatPostDate(post.date)}
                  </time>
                  <span className="min-w-0">
                    <span className="block font-display text-2xl font-medium tracking-[-0.03em] text-blacksite-text transition-colors group-hover:text-signal-cyan group-focus-visible:text-signal-cyan">
                      {post.title}
                    </span>
                    {post.excerpt && (
                      <span className="mt-2 block max-w-3xl text-sm leading-6 text-blacksite-muted">
                        {post.excerpt}
                      </span>
                    )}
                  </span>
                </Link>
              ))}
            </div>
            <div className="mt-8 flex justify-end">
              <Link
                href="/blog/"
                className="section-label rounded-md border border-blacksite-line px-4 py-3 !text-blacksite-text transition-colors hover:border-signal-cyan/70 hover:!text-signal-cyan focus-visible:outline-signal-cyan"
              >
                All field notes →
              </Link>
            </div>
          </>
        ) : (
          <div className="border border-dashed border-blacksite-line bg-blacksite-surface/45 p-8 sm:p-10">
            <p className="section-label !text-blacksite-text">ARCHIVE EMPTY</p>
          </div>
        )}
      </div>
    </section>
  );
}
