"use client"

import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { ChevronRight, Home } from 'lucide-react';

const pathMap = {
  'schedules': 'Train Schedules',
  'about': 'About Us',
  'blogs': 'Travel Blogs',
  'contact': 'Contact Us',
  'station': 'Station Gallery',
  'train': 'Train Details',
};

// Helper to format dynamic segments (e.g., "dhaka-to-rajbari" -> "Dhaka To Rajbari")
const formatSegment = (segment) => {
  if (pathMap[segment]) return pathMap[segment];
  return segment
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

export function Breadcrumbs() {
  const pathname = usePathname();
  const pathnames = pathname.split('/').filter((x) => x);

  // Don't show on home page
  if (pathnames.length === 0) return null;

  const breadcrumbList = [
    { name: 'Home', path: '/' },
    ...pathnames.map((value, index) => {
      const to = `/${pathnames.slice(0, index + 1).join('/')}`;
      return {
        name: formatSegment(value),
        path: to,
        isLast: index === pathnames.length - 1,
      };
    }),
  ];

  // Schema.org BreadcrumbList JSON-LD
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": breadcrumbList.map((item, index) => ({
      "@type": "ListItem",
      "position": index + 1,
      "name": item.name,
      "item": `https://trainsofrajbari.com${item.path}`
    }))
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />

      <nav aria-label="Breadcrumb" className="container mx-auto px-4 py-3 text-sm text-muted-foreground">
        <ol className="flex items-center space-x-2">
          {breadcrumbList.map((item, index) => {
            const isLast = index === breadcrumbList.length - 1;

            return (
              <li key={item.path} className="flex items-center">
                {index > 0 && <ChevronRight className="h-4 w-4 mx-1" />}
                
                {isLast ? (
                  <span className="font-medium text-foreground" aria-current="page">
                    {item.name}
                  </span>
                ) : (
                  <Link 
                    href={item.path} 
                    className="hover:text-primary transition-colors flex items-center gap-1"
                  >
                    {index === 0 && <Home className="h-4 w-4" />}
                    <span>{item.name}</span>
                  </Link>
                )}
              </li>
            );
          })}
        </ol>
      </nav>
    </>
  );
}
