"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { getCategoryForPost } from "@/lib/getCategoryBySlug";
type Category = {
  id: string;
  name: string;
  slug: string;
};
export default function Breadcrumbs() {
  const pathname = usePathname(); // ✅ App Router API
  const pathParts = pathname.split("/").filter(Boolean);

  const [category, setCategory] = useState<Category | null>(null);

  // Detect last slug & fetch WP category
  useEffect(() => {
    const lastPart = pathParts[pathParts.length - 1];
    if (!lastPart) return;

    getCategoryForPost(lastPart).then((cat) => {
      if (cat) setCategory(cat);
    });
  }, [pathParts]);


  return (
    <nav
      className="text-lg md:text-2xl"
    >
      <ol className="flex flex-wrap items-center justify-center gap-1">

        {/* HOME */}
        <li>
          <Link
            href="/"
            className="text-white hover:text-white"
          >
            Home
          </Link>
        </li>

        {/* CATEGORY */}
        {category && (
          <li className="flex items-center gap-1">
            <span className="font-medium text-white">{">"}</span>
            <Link
              href={`/blog?category=${category.slug}`}
              className="text-white hover:text-white"
            >
              {category.name}
            </Link>
          </li>
        )}

        {/* PAGE TITLE */}
        {pathParts.length > 0 && (
          <li className="flex items-center gap-1">
            <span className="font-medium text-white">{">"}</span>
            <span className="text-white">
              {decodeURIComponent(pathParts[pathParts.length - 1])
                .replace(/-/g, " ")
                .replace(/\b\w/g, (l) => l.toUpperCase())}
            </span>
          </li>
        )}

      </ol>
    </nav>
  );
}
