"use client"

import { Fragment } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"

import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb"

// Per-segment display labels. Deliberately separate from Header.tsx's
// titleFromPath (which resolves one *full* path to a page title) — a
// breadcrumb needs a label per *segment*, including grouping segments that
// have no page of their own (e.g. "receiving", "grn").
const SEGMENT_LABELS: Record<string, string> = {
  dashboard: "Dashboard",
  products: "Items",
  uoms: "UOMs",
  categories: "Categories",
  new: "New",
  edit: "Edit",
  vendors: "Vendors",
  warehouse: "Warehouses",
  receiving: "Receiving",
  grn: "Goods Receipt Notes",
  stock: "Stock",
  enquiry: "Enquiry",
  ledger: "Ledger",
  valuation: "Valuation",
  transfers: "Transfers",
  adjustments: "Adjustments",
  counts: "Counts",
  "reorder-alerts": "Reorder Alerts",
  wastage: "Wastage",
  procurement: "Procurement",
  requisitions: "Requisitions",
  rfqs: "RFQs",
  "purchase-orders": "Purchase Orders",
  "purchase-returns": "Purchase Returns",
  production: "Production",
  templates: "Templates",
  runs: "Runs",
}

function labelFor(segment: string): string {
  if (SEGMENT_LABELS[segment]) return SEGMENT_LABELS[segment]
  if (/^[0-9]+$/.test(segment)) return `#${segment}`
  return segment.charAt(0).toUpperCase() + segment.slice(1)
}

const linkClass =
  "truncate transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm"

export function Breadcrumbs() {
  const pathname = usePathname() || "/dashboard"
  const segments = pathname.split("/").filter(Boolean)

  // Nothing to show above the dashboard root itself.
  if (segments.length <= 1) return null

  const crumbs = segments.map((segment, i) => ({
    href: "/" + segments.slice(0, i + 1).join("/"),
    label: labelFor(segment),
  }))

  return (
    <Breadcrumb className="mb-4">
      <BreadcrumbList>
        {crumbs.map((crumb, i) => {
          const isLast = i === crumbs.length - 1
          return (
            <Fragment key={crumb.href}>
              <BreadcrumbItem>
                {isLast ? (
                  <BreadcrumbPage>{crumb.label}</BreadcrumbPage>
                ) : (
                  <Link href={crumb.href} className={linkClass}>
                    {crumb.label}
                  </Link>
                )}
              </BreadcrumbItem>
              {!isLast && <BreadcrumbSeparator />}
            </Fragment>
          )
        })}
      </BreadcrumbList>
    </Breadcrumb>
  )
}
