import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Calendar, Clock } from "lucide-react";
import type { Metadata } from "next";
import { catalogApi } from "@/lib/api/catalog";
import { ApiException } from "@/lib/api/client";
import NewsImage from "@/components/news/NewsImage";
import { formatDate as formatLongDate } from "@/lib/utils";

type Props = { params: Promise<{ slug: string }> };

export const revalidate = 120;

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

function readingTime(minutes: number | undefined, html: string | null) {
  if (minutes) return `${minutes} min read`;
  if (!html) return "1 min read";
  const words = html.replace(/<[^>]+>/g, " ").split(/\s+/).filter(Boolean).length;
  return `${Math.max(1, Math.round(words / 200))} min read`;
}

/**
 * Prebuild the published articles. Fail-safe: an unreachable API during the
 * build just yields no prerendered paths, and each slug falls back to an
 * on-demand render that then caches per `revalidate`.
 */
export async function generateStaticParams(): Promise<{ slug: string }[]> {
  try {
    const res = await catalogApi.news({ per_page: 100 });
    return res.data
      .map((article) => article.slug)
      .filter((slug): slug is string => Boolean(slug))
      .map((slug) => ({ slug }));
  } catch {
    return [];
  }
}

async function loadArticle(slug: string) {
  try {
    return await catalogApi.newsBySlug(slug, { next: { revalidate: 120 } });
  } catch (err) {
    if (err instanceof ApiException && err.status === 404) return null;
    throw err;
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const article = await loadArticle(slug);
  if (!article) return { title: "Article Not Found – Biznie" };
  return {
    title: `${article.title} – Biznie News`,
    description: article.excerpt?.slice(0, 160) ?? (article.description || "").replace(/<[^>]+>/g, " ").slice(0, 160),
  };
}

export default async function NewsDetailPage({ params }: Props) {
  const { slug } = await params;
  const article = await loadArticle(slug);
  if (!article) notFound();

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <Link href="/news" className="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-[#CC1414] mb-8 transition-colors">
          <ArrowLeft size={16} /> Back to News
        </Link>

        <article className="bg-white rounded-2xl border border-gray-100 shadow-sm p-8 md:p-12">
          <div className="relative w-full aspect-[16/9] mb-6 rounded-xl overflow-hidden bg-gray-50">
            <NewsImage src={article.image} alt={article.title} sizes="(min-width: 768px) 800px, 100vw" />
          </div>

          <h1 className="text-2xl md:text-4xl font-black text-gray-900 mb-4 leading-tight">
            {article.title}
          </h1>

          <div className="flex flex-wrap items-center gap-4 text-xs text-gray-400 mb-8 pb-6 border-b border-gray-100">
            <span className="flex items-center gap-1.5"><Calendar size={13} /> {formatDate(article.published_at)}</span>
            <span className="flex items-center gap-1.5"><Clock size={13} /> {readingTime(article.reading_minutes, article.description)}</span>
          </div>

          {/* Sanitised on the server: formatting only, no scripts or handlers;
              "⸻" lines arrive as dividers (B19). */}
          {article.body_html ? (
            <div
              className="prose prose-sm max-w-none text-gray-700 [&_hr]:my-6"
              dangerouslySetInnerHTML={{ __html: article.body_html }}
            />
          ) : article.description && (
            article.description.includes("<")
              ? (
                <div
                  className="prose prose-sm max-w-none text-gray-700"
                  dangerouslySetInnerHTML={{ __html: article.description }}
                />
              )
              : (
                <div className="prose prose-sm max-w-none text-gray-700 whitespace-pre-line">
                  {article.description}
                </div>
              )
          )}

          {article.tags && (
            <div className="mt-8 pt-6 border-t border-gray-100 flex flex-wrap gap-2">
              {article.tags.split(",").map((t) => t.trim()).filter(Boolean).map((tag) => (
                <span key={tag} className="text-xs bg-gray-100 text-gray-600 px-3 py-1 rounded-full">
                  #{tag}
                </span>
              ))}
            </div>
          )}

          <div className="mt-10 pt-6 border-t border-gray-100">
            <Link
              href="/contact"
              className="inline-flex items-center gap-2 bg-[#CC1414] text-white font-bold px-6 py-3.5 rounded-xl hover:bg-[#A50E0E] transition-colors text-sm"
            >
              Get Market Insights &amp; Price Alerts →
            </Link>
          </div>
        </article>
      </div>
    </div>
  );
}
