'use client';

import Link from 'next/link';
import { m, useReducedMotion } from 'motion/react';
import type { PostMeta } from '@/lib/posts';
import { tagToSlug } from '@/lib/tags';

export function PostCard({ slug, title, date, excerpt, tags = [], author, readingTime, index = 0, coverImage }: PostMeta & { index?: number }) {
  const shouldReduceMotion = useReducedMotion();

  return (
    <m.article
      initial={shouldReduceMotion ? false : { opacity: 0, y: 14 }}
      whileInView={shouldReduceMotion ? undefined : { opacity: 1, y: 0 }}
      whileHover={shouldReduceMotion ? undefined : { y: -2 }}
      transition={{ duration: 0.35, delay: shouldReduceMotion ? 0 : Math.min(index * 0.04, 0.18), ease: [0.22, 1, 0.36, 1] }}
      viewport={{ once: true, amount: 0.2 }}
      className="group relative scroll-mt-20 rounded-2xl border border-border/90 bg-canvas p-5 shadow-card transition-[background-color,border-color,box-shadow] duration-200 ease-out hover:border-ink/25 hover:bg-surface/40 hover:shadow-card-hover dark:hover:border-ink/35 sm:p-7"
    >
      <Link href={`/blog/${slug}/`} className="block">
        {coverImage && (
          <div className="mb-5 overflow-hidden rounded-xl border border-border/80 bg-surface">
            <img
              src={coverImage}
              alt={`Cover image for ${title}`}
              className="h-44 w-full object-cover transition-transform duration-300 ease-out group-hover:scale-[1.015] sm:h-52"
              loading="lazy"
            />
          </div>
        )}
        <div className="mb-4 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-soft">
          <time className="font-mono" dateTime={date}>{new Date(date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })}</time>
          {author && <span className="text-ink-soft/70">·</span>}
          {author && <span>{author}</span>}
          {readingTime && <span className="text-ink-soft/70">·</span>}
          {readingTime && <span className="font-mono">{readingTime} min read</span>}
        </div>
        <h3 className="heading-md mb-3 mt-0 text-ink transition-colors duration-200 group-hover:text-accent">
          {title}
        </h3>
        {excerpt && (
          <p className="mt-3 max-w-3xl text-sm leading-7 text-ink-soft">{excerpt}</p>
        )}
      </Link>
      {tags && tags.length > 0 && (
        <div className="mt-5 flex flex-wrap gap-2">
          {tags.slice(0, 3).map((tag) => (
            <Link key={tag} href={`/blog/tags/${tagToSlug(tag)}/`} className="rounded-full border border-border bg-surface/70 px-3 py-1 text-xs text-ink-soft transition-colors duration-200 hover:border-accent/60 hover:text-accent focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent">
              {tag}
            </Link>
          ))}
        </div>
      )}
    </m.article>
  );
}
