import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { listPosts, BLOG_CATEGORIES, type BlogPostSummary } from "@/lib/blog.functions";
import { keywordMeta } from "@/lib/seo-keywords";

export const Route = createFileRoute("/blog/")({
  loader: () => listPosts(),
  head: ({ loaderData }) => ({
    meta: [
      { title: "Blog — AI, Mobile, Blockchain & Social Impact | Gatavase" },
      {
        name: "description",
        content:
          "Articles from Gatavase Corporation engineers on AI automation, mobile apps, blockchain and technology for social impact in Africa and the Gulf.",
      },
      keywordMeta(["ai", "mobile", "blockchain", "impact"]),
      { property: "og:title", content: "Gatavase Blog — Engineering Notes from Africa" },
      {
        property: "og:description",
        content:
          "AI automation, mobile apps, blockchain and social impact — written by the people building the systems.",
      },
      { property: "og:url", content: "/blog" },
    ],
    links: [{ rel: "canonical", href: "/blog" }],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Blog",
          name: "The Gatavase Blog",
          url: "/blog",
          inLanguage: "en",
          publisher: { "@type": "Organization", name: "Gatavase Corporation" },
          blogPost: ((loaderData ?? []) as BlogPostSummary[]).slice(0, 20).map((p) => ({
            "@type": "BlogPosting",
            headline: p.title,
            description: p.excerpt,
            url: `/blog/${p.slug}`,
            datePublished: p.published_at ?? undefined,
            articleSection: p.category,
            author: { "@type": "Organization", name: p.author },
          })),
        }),
      },
    ],
  }),
  component: BlogIndex,
});


function BlogIndex() {
  const posts = Route.useLoaderData() as BlogPostSummary[];
  const [category, setCategory] = useState<string>("All");

  const filtered = category === "All" ? posts : posts.filter((p) => p.category === category);

  return (
    <>
      <section className="hero-surface border-b border-border">
        <div className="mx-auto max-w-6xl px-5 py-20">
          <p className="font-mono text-xs tracking-[0.2em] text-primary uppercase">Insights</p>
          <h1 className="mt-4 text-4xl font-bold md:text-5xl">The Gatavase Blog</h1>
          <p className="mt-5 max-w-2xl text-lg text-muted-foreground">
            Engineering notes on AI automation, mobile apps, blockchain and technology built for
            social impact — written by the teams doing the work.
          </p>
        </div>
      </section>

      <section className="mx-auto max-w-6xl px-5 py-14">
        <div className="flex flex-wrap gap-2">
          {["All", ...BLOG_CATEGORIES].map((c) => (
            <button
              key={c}
              onClick={() => setCategory(c)}
              className={`rounded-full border px-4 py-1.5 text-sm transition-colors ${
                category === c
                  ? "border-primary bg-primary/15 text-primary"
                  : "border-border text-muted-foreground hover:text-foreground"
              }`}
            >
              {c}
            </button>
          ))}
        </div>

        {filtered.length === 0 ? (
          <p className="mt-12 text-sm text-muted-foreground">
            No articles in this category yet — check back soon.
          </p>
        ) : (
          <div className="mt-10 grid gap-5 md:grid-cols-2">
            {filtered.map((post) => (
              <Link
                key={post.id}
                to="/blog/$slug"
                params={{ slug: post.slug }}
                className="panel block p-8"
              >
                <p className="font-mono text-xs tracking-wide text-primary uppercase">
                  {post.category}
                </p>
                <h2 className="mt-3 text-xl font-semibold">{post.title}</h2>
                <p className="mt-3 text-sm leading-relaxed text-muted-foreground">{post.excerpt}</p>
                <p className="mt-6 text-xs text-muted-foreground">
                  {post.author}
                  {post.published_at
                    ? ` · ${new Date(post.published_at).toLocaleDateString("en-GB", {
                        day: "numeric",
                        month: "long",
                        year: "numeric",
                      })}`
                    : ""}
                </p>
              </Link>
            ))}
          </div>
        )}
      </section>
    </>
  );
}
