'use client';

import Link from 'next/link';
import type { Route } from 'next';
import { ChevronLeft } from 'lucide-react';

import { cn } from '@/lib/utils';
import { useSmartBack } from '@/hooks/use-smart-back';

interface BackButtonProps {
  /** Visual treatment. Desktop shows chevron + "Back to X" label;
   *  mobile shows chevron only with the destination in aria-label so
   *  the 44px tap target stays uncluttered in the narrow topbar. */
  variant: 'desktop' | 'mobile';
}

/**
 * Contextual back button. Replaces the legacy breadcrumb chain that
 * lived in the desktop topbar and the unconditional `router.back()`
 * affordance on mobile. Returns nothing on top-level pages where the
 * sidebar is the natural way out.
 *
 * Resolves its target via `useSmartBack()` - prefers a registered
 * detail-page hint, falls back to URL-derived parent route.
 */
export function BackButton({ variant }: BackButtonProps) {
  const target = useSmartBack();
  if (!target) return null;

  // Next typed-routes can't know that hint.href / URL-derived parents
  // resolve to a registered route at compile time, so cast.

  const href = target.href as Route;

  if (variant === 'mobile') {
    return (
      <Link
        href={href}
        aria-label={`Back to ${target.label}`}
        className={cn(
          'size-11 inline-flex items-center justify-center rounded-full -ml-1',
          'text-white/95 active:bg-white/10 transition-colors',
        )}
      >
        <ChevronLeft className="size-[22px] stroke-[2.25]" aria-hidden />
      </Link>
    );
  }

  return (
    <Link
      href={href}
      aria-label={`Back to ${target.label}`}
      className={cn(
        'inline-flex h-8 items-center gap-1 rounded-md px-2 -ml-2 min-w-0',
        'text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-accent',
        'transition-colors',
      )}
      title={`Back to ${target.label}`}
    >
      <ChevronLeft className="h-4 w-4 shrink-0" aria-hidden />
      {/* Label-only (iOS-style "< Settings"). The chevron already
          communicates "back"; doubling up with a "Back to" prefix wastes
          horizontal space in a topbar that's already crowded by the
          centered search bar. Full intent is preserved in the tooltip
          + aria-label. */}
      <span className="truncate max-w-[160px]">{target.label}</span>
    </Link>
  );
}
