'use client'

import { useRouter } from 'next/navigation'
import { ChevronLeft } from 'lucide-react'

/**
 * Back button that pops browser history when available, falling back to a
 * known route (e.g. `/locations`) when the user landed here via a direct
 * URL with no in-app history.
 */
export function BackButton({ fallbackHref }: { fallbackHref: string }) {
  const router = useRouter()
  const go = () => {
    if (typeof window !== 'undefined' && window.history.length > 1) {
      router.back()
    } else {
      router.push(fallbackHref)
    }
  }
  return (
    <button
      type="button"
      onClick={go}
      aria-label="Back"
      className="-ml-2 p-2 rounded-md text-muted-foreground hover:text-foreground"
    >
      <ChevronLeft className="size-5" />
    </button>
  )
}
