import { Suspense } from "react";
import Link from "next/link";
import { Calendar, ArrowRight, TrendingUp, Star } from "lucide-react";
import { catalogApi } from "@/lib/api/catalog";
import type { ApiNews } from "@/lib/api/types";
import NewsImage from "@/components/news/NewsImage";
import { CardGridSkeleton } from "@/components/ui/Skeleton";
import { formatDate as formatLongDate } from "@/lib/utils";

export const metadata = {
  title: "Industry News & Market Updates – Biznie",
  description: "Stay updated with latest raw material prices, industry news and market insights from Biznie.",
};

export const revalidate = 120;

type PageProps = { searchParams: Promise<{ search?: string }> };

function formatDate(iso: string | null) {
  if (!iso) return "—";
  try {
    return formatLongDate(iso);
  } catch {
    return iso;
  }
}

function readingTime(article: ApiNews) {
  if (article.reading_minutes) return `${article.reading_minutes} min read`;
  const words = (article.description ?? "").replace(/<[^>]+>/g, " ").split(/\s+/).filter(Boolean).length;
  return `${Math.max(1, Math.round(words / 200))} min read`;
}

/** Card text: the API's clean excerpt (no emoji or "⸻"), else stripped tags. */
function excerpt(article: ApiNews, limit: number) {
  return article.excerpt ?? (article.description || "").replace(/<[^>]+>/g, " ").slice(0, limit);
}

async function safeFetch(search?: string) {
  try {
    return await catalogApi.news({ search, per_page: 12 }, { next: { revalidate: 120 } });
  } catch {
    return { data: [] as ApiNews[], meta: undefined as { last_published_at?: string | null } | undefined };
  }
}

/**
 * Kept synchronous so the banner streams ahead of the news fetch. The route is
 * still dynamic — reading `searchParams` guarantees that — but the shell no
 * longer waits on the upstream call before reaching the browser.
 */
export default function NewsPage({ searchParams }: PageProps) {
  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-gradient-to-r from-[#CC1414] to-[#8B0000] text-white py-14">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <h1 className="text-3xl md:text-4xl font-black mb-3">Industry News &amp; Insights</h1>
          {/* No "daily" promise the archive cannot keep (B19); the list below
              says when the latest update went up. */}
          <p className="text-red-100 max-w-2xl">
            Raw material news, price trends and market insights from ground-level industry experts.
          </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <Suspense fallback={<CardGridSkeleton count={6} />}>
          <NewsList searchParams={searchParams} />
        </Suspense>
      </div>
    </div>
  );
}

async function NewsList({ searchParams }: PageProps) {
  const sp = await searchParams;
  const { data: articles, meta } = await safeFetch(sp.search?.trim() || undefined);
  const lastUpdate = meta?.last_published_at ?? articles[0]?.published_at ?? null;
  const featured = articles.slice(0, 2);
  const regular = articles.slice(2);

  return (
    <>
      {lastUpdate && articles.length > 0 && (
        <p className="mb-6 text-xs text-gray-500">Last update: {formatDate(lastUpdate)}</p>
      )}
      {articles.length === 0 ? (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-12 text-center">
          <p className="text-gray-500 text-sm">No news articles published yet.</p>
        </div>
      ) : (
        <>
          {featured.length > 0 && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
              {featured.map((article) => (
                <Link
                  key={article.id}
                  href={`/news/${article.slug || article.id}`}
                  className="bg-white rounded-2xl border border-gray-100 shadow-sm card-hover p-6 group"
                >
                  <div className="relative mb-5 aspect-[16/9] overflow-hidden rounded-xl bg-gray-50">
                    <NewsImage src={article.image} alt={article.title} sizes="(max-width: 768px) 100vw, 50vw" />
                  </div>
                  <div className="flex items-center gap-3 mb-4">
                    <span className="inline-flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-full bg-red-50 text-[#CC1414]">
                      <Star size={11} className="fill-current" aria-hidden /> Featured
                    </span>
                  </div>
                  <h2 className="text-xl font-black text-gray-900 mb-3 group-hover:text-[#CC1414] transition-colors leading-tight">
                    {article.title}
                  </h2>
                  <p className="text-gray-500 text-sm leading-relaxed mb-4 line-clamp-3">
                    {excerpt(article, 220)}
                  </p>
                  <div className="flex items-center gap-4 text-xs text-gray-400">
                    <span className="flex items-center gap-1"><Calendar size={12} /> {formatDate(article.published_at)}</span>
                    <span>{readingTime(article)}</span>
                  </div>
                </Link>
              ))}
            </div>
          )}

          {regular.length > 0 && (
            <>
              <h2 className="text-xl font-bold text-gray-900 mb-5 flex items-center gap-2">
                <TrendingUp size={20} className="text-[#CC1414]" /> Latest News
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                {regular.map((article) => (
                  <Link
                    key={article.id}
                    href={`/news/${article.slug || article.id}`}
                    className="bg-white rounded-2xl border border-gray-100 shadow-sm card-hover p-5 group"
                  >
                    <div className="relative mb-4 aspect-[16/9] overflow-hidden rounded-xl bg-gray-50">
                      <NewsImage src={article.image} alt={article.title} sizes="(max-width: 1024px) 50vw, 33vw" />
                    </div>
                    <h3 className="font-bold text-gray-900 mb-2 group-hover:text-[#CC1414] transition-colors leading-snug">
                      {article.title}
                    </h3>
                    <p className="text-gray-500 text-sm leading-relaxed mb-4 line-clamp-2">
                      {excerpt(article, 160)}
                    </p>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3 text-xs text-gray-400">
                        <span className="flex items-center gap-1"><Calendar size={11} /> {formatDate(article.published_at)}</span>
                      </div>
                      <span className="text-xs text-[#CC1414] font-semibold flex items-center gap-1">
                        Read <ArrowRight size={11} />
                      </span>
                    </div>
                  </Link>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </>
  );
}
