"use client";
import { useEffect, useState } from "react";
import { api } from "@/lib/api";

interface NewsItem {
  id: string;
  title: string;
  slug: string;
  excerpt: string | null;
  createdAt: string;
}

export default function NewsPage() {
  const [items, setItems] = useState<NewsItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get<NewsItem[]>("/news?publishedOnly=true")
      .then((res) => setItems(res.data || []))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="mx-auto max-w-5xl px-4 py-14">
      <h1 className="text-3xl font-bold text-[var(--brand-blue)] mb-8">Latest News</h1>
      {loading ? (
        <p className="text-gray-500 text-sm">Loading...</p>
      ) : items.length === 0 ? (
        <p className="text-gray-500 text-sm">No news articles published yet.</p>
      ) : (
        <div className="grid sm:grid-cols-2 gap-6">
          {items.map((n) => (
            <article key={n.id} className="rounded-2xl border border-[var(--brand-border)] p-6">
              <h2 className="font-semibold text-[var(--brand-blue)]">{n.title}</h2>
              <p className="text-sm text-gray-600 mt-2">{n.excerpt}</p>
              <p className="text-xs text-gray-400 mt-3">{new Date(n.createdAt).toLocaleDateString()}</p>
            </article>
          ))}
        </div>
      )}
    </div>
  );
}
