import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { getPost, type BlogPost } from "@/lib/blog.functions";

export const Route = createFileRoute("/blog/$slug")({
  loader: async ({ params }) => {
    const post = await getPost({ data: params.slug });
    if (!post) throw notFound();
    return post;
  },
  head: ({ params, loaderData }) => {
    const post = loaderData as BlogPost | undefined;
    if (!post) {
      return {
        meta: [{ title: "Article unavailable — Gatavase" }, { name: "robots", content: "noindex" }],
      };
    }
    return {
      meta: [
        { title: `${post.title} — Gatavase Corporation` },
        { name: "description", content: post.excerpt },
        { property: "og:title", content: post.title },
        { property: "og:description", content: post.excerpt },
        { property: "og:type", content: "article" },
        { property: "og:url", content: `/blog/${params.slug}` },
        { name: "twitter:card", content: post.cover_image ? "summary_large_image" : "summary" },
        { name: "twitter:title", content: post.title },
        { name: "twitter:description", content: post.excerpt },
        ...(post.cover_image?.startsWith("https://")
          ? [
              { property: "og:image", content: post.cover_image },
              { name: "twitter:image", content: post.cover_image },
            ]
          : []),
      ],
      links: [{ rel: "canonical", href: `/blog/${params.slug}` }],
      scripts: [
        {
          type: "application/ld+json",
          children: JSON.stringify({
            "@context": "https://schema.org",
            "@type": "Article",
            headline: post.title,
            description: post.excerpt,
            articleSection: post.category,
            inLanguage: "en",
            url: `/blog/${params.slug}`,
            mainEntityOfPage: { "@type": "WebPage", "@id": `/blog/${params.slug}` },
            ...(post.cover_image ? { image: [post.cover_image] } : {}),
            author: { "@type": "Organization", name: post.author },
            publisher: { "@type": "Organization", name: "Gatavase Corporation" },
            datePublished: post.published_at,
            dateModified: post.published_at,
          }),
        },
      ],
    };
  },
  component: BlogPostPage,
  notFoundComponent: () => (
    <div className="mx-auto max-w-2xl px-5 py-28 text-center">
      <h1 className="text-3xl font-bold">Article not found</h1>
      <p className="mt-3 text-muted-foreground">
        This article may have been moved or unpublished.
      </p>
      <Link to="/blog" className="mt-6 inline-block text-primary underline">
        Back to the blog
      </Link>
    </div>
  ),
});

function BlogPostPage() {
  const post = Route.useLoaderData() as BlogPost;

  return (
    <article className="mx-auto max-w-3xl px-5 py-20">
      <Link to="/blog" className="text-xs text-primary hover:underline">
        ← All articles
      </Link>
      <p className="mt-6 font-mono text-xs tracking-[0.2em] text-primary uppercase">
        {post.category}
      </p>
      <h1 className="mt-3 text-3xl font-bold md:text-4xl">{post.title}</h1>
      <p className="mt-4 text-sm text-muted-foreground">
        {post.author}
        {post.published_at
          ? ` · ${new Date(post.published_at).toLocaleDateString("en-GB", {
              day: "numeric",
              month: "long",
              year: "numeric",
            })}`
          : ""}
      </p>
      <p className="mt-8 text-lg leading-relaxed text-muted-foreground">{post.excerpt}</p>

      <div className="mt-10 space-y-5">
        {post.content.split("\n").map((line, i) => {
          const text = line.trim();
          if (!text) return null;
          if (text.startsWith("## ")) {
            return (
              <h2 key={i} className="pt-4 text-xl font-semibold">
                {text.replace("## ", "")}
              </h2>
            );
          }
          return (
            <p key={i} className="leading-relaxed text-muted-foreground">
              {text}
            </p>
          );
        })}
      </div>

      <div className="panel mt-16 p-8">
        <h2 className="text-xl font-semibold">Working on something similar?</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          Our engineers are happy to look at your problem and tell you plainly what it would take.
        </p>
        <Link
          to="/contact"
          className="mt-5 inline-flex rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
        >
          Start a Project
        </Link>
      </div>
    </article>
  );
}
