import { useEffect, useMemo, useState } from "react";
import SEO from "../lib/seo";
import PageHero from "../components/PageHero";
import Reveal from "../components/Reveal";
import BlogCard from "../components/BlogCard";
import CTASection from "../components/CTASection";
import { fetchBlog } from "../lib/api";
import type { BlogPost } from "../types";

export default function Blog() {
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [category, setCategory] = useState("All");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchBlog().then((d) => setPosts(d.posts || [])).catch(() => {}).finally(() => setLoading(false));
  }, []);

  const categories = useMemo(() => ["All", ...Array.from(new Set(posts.map((p) => p.category)))], [posts]);
  const visible = category === "All" ? posts : posts.filter((p) => p.category === category);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Blog",
    name: "Aviokan Technology Insights",
    description: "Technology insights on cybersecurity, networking, cloud, data centre, digital workplace, AI, digital engineering, IoT and managed services.",
  };

  return (
    <div data-testid="blog-page" className="bg-[#0B0C10]">
      <SEO title="Technology Insights — Blog" description="Insights on cybersecurity, networking, cloud, data centre, digital workplace, AI, digital engineering, IoT and managed services from Aviokan Technologies." path="/about/blog" jsonLd={jsonLd} />

      <PageHero
        eyebrow="TECHNOLOGY INSIGHTS"
        title={"Field notes from the\nintegrated enterprise."}
        desc="Perspectives on security, networks, cloud, data and engineering — written by practitioners, not marketers."
        breadcrumb={[{ label: "Home", to: "/" }, { label: "About", to: "/about" }, { label: "Blog" }]}
        image="/images/blog/unique/blog-hero.svg"
      />

      {/* Signal intelligence feed */}
      <section className="bg-[#0B0C10] py-20" data-testid="blog-list">
        <div className="grain" aria-hidden="true" />
        <div className="mx-auto max-w-[1320px] px-5 md:px-10 relative">
          <div className="flex items-center gap-4 mb-10" aria-hidden="true">
            <span className="text-[10px] font-tech tracking-[0.3em] text-white/40">FEED</span>
            <span className="h-px flex-1 bg-gradient-to-r from-cy/40 to-transparent" />
            <span className="h-1.5 w-1.5 rotate-45 bg-ember animate-pulse" />
          </div>
          <div className="flex flex-wrap gap-2 mb-12" data-testid="blog-category-filters">
            {categories.map((c) => (
              <button
                key={c}
                onClick={() => setCategory(c)}
                className={`text-[11px] font-tech tracking-[0.14em] uppercase px-4 py-2 border transition-colors duration-300 ${
                  category === c ? "border-cy text-cy bg-cy/10" : "border-white/15 text-white/55 hover:text-cy hover:border-cy/50"
                }`}
                data-testid={`blog-filter-${c.toLowerCase().replace(/\s+/g, "-")}`}
              >
                {c}
              </button>
            ))}
          </div>
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" data-testid="blog-skeleton">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="border border-white/10 bg-[#14151A]">
                  <div className="skeleton aspect-[16/9]" />
                  <div className="p-7 space-y-4">
                    <div className="skeleton h-3 w-24" />
                    <div className="skeleton h-5 w-5/6" />
                    <div className="skeleton h-3 w-full" />
                    <div className="skeleton h-3 w-2/3" />
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {visible.map((p, i) => <BlogCard key={p.slug} post={p} index={i} dark />)}
            </div>
          )}
          {!loading && visible.length === 0 && (
            <p className="text-white/45 text-sm" data-testid="blog-empty">No articles in this category yet.</p>
          )}
        </div>
      </section>

      <CTASection />
    </div>
  );
}