import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { FadeIn } from "@/components/motion/FadeIn";
import { fetchPost, type BlogPost } from "@/lib/api";
import { SITE_URL } from "@/lib/site";

export const Route = createFileRoute("/_site/blog/$slug")({
  head: ({ params }) => ({
    meta: [
      { title: `${params.slug.replace(/-/g, " ")} — Komal Star Blog` },
      { name: "description", content: "Read the latest from Komal Star Electricals." },
      { property: "og:url", content: `${SITE_URL}/blog/${params.slug}` },
    ],
    links: [{ rel: "canonical", href: `${SITE_URL}/blog/${params.slug}` }],
  }),
  component: BlogDetail,
  errorComponent: () => <p className="p-12 text-center">Something went wrong.</p>,
  notFoundComponent: () => (
    <div className="p-24 text-center">
      <h1 className="font-display text-4xl">Post not found</h1>
      <Link to="/blog" className="mt-6 inline-block text-primary underline">Back to blog</Link>
    </div>
  ),
});

function BlogDetail() {
  const { slug } = Route.useParams();
  const [post, setPost] = useState<BlogPost | null>(null);
  const [state, setState] = useState<"loading" | "ok" | "missing">("loading");
  useEffect(() => {
    fetchPost(slug).then((p) => {
      if (!p) { setState("missing"); return; }
      setPost(p); setState("ok");
    });
  }, [slug]);

  if (state === "loading") return <p className="p-24 text-center text-muted-foreground">Loading…</p>;
  if (state === "missing" || !post) throw notFound();

  return (
    <article className="mx-auto max-w-3xl px-6 py-16">
      <FadeIn>
        <p className="text-xs uppercase tracking-widest text-primary">
          {post.published_at ? new Date(post.published_at).toLocaleDateString() : ""}
        </p>
        <h1 className="mt-3 font-display text-3xl font-bold sm:text-4xl md:text-5xl">{post.title}</h1>
        {post.cover_image_url && (
          <img src={post.cover_image_url} alt={post.title} className="mt-8 w-full rounded-2xl" />
        )}
        <div className="prose prose-lg mt-8 max-w-none whitespace-pre-wrap leading-relaxed text-foreground/90">
          {post.body_md}
        </div>
        <Link to="/blog" className="mt-12 inline-block text-primary hover:underline">← All posts</Link>
      </FadeIn>
    </article>
  );
}
