'use client';

import Image from 'next/image';
import Link from 'next/link';
import { useState } from 'react';
import type { PlazaPost } from '@/types/plaza';
import { categoryAccent, formatCount, formatRelativeTime } from '@/lib/format';
import { plazaPath } from '@/lib/site';

export function PostCard({ post, priority = false }: { post: PlazaPost; priority?: boolean }) {
  const [coverFailed, setCoverFailed] = useState(false);
  const showFallback = !post.cover_url || coverFailed;
  const accent = categoryAccent(post.category.slug);
  const initial = post.title.trim().charAt(0) || '页';

  return (
    <Link
      href={plazaPath(`p/${post.id}`)}
      className="group flex flex-col overflow-hidden rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] shadow-sm transition hover:-translate-y-0.5 hover:shadow-md"
    >
      <div className="relative aspect-[16/10] overflow-hidden bg-[#ebe4d6]">
        {showFallback ? (
          <div
            className={`flex h-full w-full items-center justify-center bg-gradient-to-br ${accent} text-5xl font-bold text-white/90`}
          >
            {initial}
          </div>
        ) : (
          <Image
            src={post.cover_url}
            alt={post.title}
            fill
            priority={priority}
            loading={priority ? undefined : 'lazy'}
            className="object-cover transition group-hover:scale-[1.02]"
            sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
            onError={() => setCoverFailed(true)}
          />
        )}
      </div>
      <div className="flex flex-1 flex-col gap-2 p-4">
        <h3 className="line-clamp-2 text-base font-semibold leading-snug text-[#17221d]">
          {post.title}
        </h3>
        {post.summary ? (
          <p className="line-clamp-2 text-sm leading-relaxed text-[#68716c]">{post.summary}</p>
        ) : null}
        <div className="mt-auto flex items-center justify-between gap-2 pt-2 text-xs text-[#8a928c]">
          <span className="truncate">{post.author.display_name}</span>
          <span>{formatRelativeTime(post.published_at)}</span>
        </div>
        <div className="flex gap-3 text-xs text-[#4a5751]">
          <span>👍 {formatCount(post.stats.like_count)}</span>
          <span>💬 {formatCount(post.stats.comment_count)}</span>
        </div>
      </div>
    </Link>
  );
}
