'use client'

import { ChevronRight, Home } from 'lucide-react'

const LABEL_MAP: Record<string, string> = {
  posts: 'Posts',
  pages: 'Pages',
  media: 'Media Library',
  forms: 'Forms',
  seo: 'SEO',
  redirects: 'Redirects',
  canonicals: 'Canonicalization',
  links: 'Link Health',
  users: 'Users',
  'script-tags': 'Script Tags',
  settings: 'Settings',
  profile: 'Your Profile',
  collections: 'Collections',
  submissions: 'Submissions',
  new: 'New',
  edit: 'Edit',
}

function labelFor(segment: string): string {
  return (
    LABEL_MAP[segment] ?? segment.replace(/[-_]/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
  )
}

export function isId(segment: string): boolean {
  return (
    // numeric id
    /^\d+$/.test(segment) ||
    // hex id (e.g. ObjectId / md5-style)
    /^[0-9a-f]{8,}$/i.test(segment) ||
    // cuid (Prisma's @default(cuid())): leading "c" + base36, ~25 chars
    /^c[a-z0-9]{20,}$/i.test(segment) ||
    // cuid2 / other long base36 token ids (24+ chars, no separators)
    /^[a-z0-9]{24,}$/i.test(segment)
  )
}

export interface BreadcrumbsProps {
  currentPath: string
  onNavigate: (path: string) => void
}

export function Breadcrumbs({ currentPath, onNavigate }: BreadcrumbsProps) {
  // Strip query string + hash so tab-driven routes (e.g. `/settings?tab=users`,
  // `/seo?tab=audit`) don't leak the raw query into a crumb label.
  const cleanPath = currentPath.split('?')[0]!.split('#')[0]!
  const segments = cleanPath.split('/').filter(Boolean)

  if (segments.length === 0) return null

  const crumbs: { label: string; path: string }[] = []
  let accumulated = ''

  for (let i = 0; i < segments.length; i++) {
    const seg = segments[i]!
    accumulated += `/${seg}`

    let label: string
    if (isId(seg)) {
      const parentLabel = i > 0 ? labelFor(segments[i - 1]!) : ''
      label = parentLabel ? `Edit ${parentLabel.replace(/s$/, '')}` : `#${seg}`
    } else {
      label = labelFor(seg)
    }

    crumbs.push({ label, path: accumulated })
  }

  return (
    <nav
      aria-label="Breadcrumb"
      className="flex items-center gap-1 overflow-x-auto border-b border-gray-200 bg-white px-4 py-2.5 text-sm"
    >
      <button
        type="button"
        onClick={() => onNavigate('/')}
        className="flex shrink-0 items-center gap-1 text-gray-500 transition-colors hover:text-blue-600"
      >
        <Home className="h-3.5 w-3.5" />
        <span className="hidden sm:inline">Dashboard</span>
      </button>

      {crumbs.map((crumb, i) => {
        const isLast = i === crumbs.length - 1
        return (
          <span key={crumb.path} className="flex shrink-0 items-center gap-1">
            <ChevronRight className="h-3.5 w-3.5 text-gray-400" />
            {isLast ? (
              <span className="font-medium text-gray-900">{crumb.label}</span>
            ) : (
              <button
                type="button"
                onClick={() => onNavigate(crumb.path)}
                className="text-gray-500 transition-colors hover:text-blue-600"
              >
                {crumb.label}
              </button>
            )}
          </span>
        )
      })}
    </nav>
  )
}
