import Link from "next/link";

interface Story {
  id: string;
  title: string;
  summary: string;
  source: string;
  url: string;
  publishedAt: string;
  category: string;
  coverageCount: number;
}

interface NewsCardProps {
  story: Story;
}

export function NewsCard({ story }: NewsCardProps) {
  const timeAgo = getRelativeTime(story.publishedAt);

  return (
    <article className="card group flex flex-col transition-shadow hover:shadow-md">
      {/* Category & Time */}
      <div className="mb-2 flex items-center gap-2">
        <span className="badge-category">{story.category}</span>
        {story.coverageCount > 10 && (
          <span className="badge-trending">Trending</span>
        )}
        <span className="ml-auto text-2xs text-body-muted">{timeAgo}</span>
      </div>

      {/* Title */}
      <h3 className="mb-2 text-base font-semibold leading-snug">
        <Link
          href={story.url}
          target="_blank"
          rel="noopener noreferrer"
          className="text-heading no-underline group-hover:text-brand-600"
        >
          {story.title}
        </Link>
      </h3>

      {/* Summary */}
      <p className="mb-4 flex-1 text-sm text-body line-clamp-2">
        {story.summary}
      </p>

      {/* Meta */}
      <div className="flex items-center gap-2 text-2xs text-body-muted">
        <span className="font-medium">{story.source}</span>
        <span>·</span>
        <span>
          {story.coverageCount} {story.coverageCount === 1 ? "source" : "sources"}
        </span>
      </div>
    </article>
  );
}

function getRelativeTime(isoDate: string): string {
  const diff = Date.now() - new Date(isoDate).getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return "Just now";
  if (minutes < 60) return `${minutes}m ago`;
  if (hours < 24) return `${hours}h ago`;
  if (days < 7) return `${days}d ago`;
  return new Date(isoDate).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
  });
}
