import { memo } from 'react';

import { cn } from '@/lib/utils';
import type { ActionQueueDataHealth } from '@/types/action-queue';

/**
 * Compact data-health pill for an Action Queue row (and the recommendation
 * "Why this rewrite" explanation). Communicates whether the data behind a row
 * is trustworthy BEFORE the operator spends an AI credit on a draft.
 *
 * Render contract:
 *  - `fresh` (or unknown) → renders nothing. A green "all good" badge would add
 *    noise to the happy path; absence IS the signal.
 *  - `stale` / `partial`  → soft amber warning tokens.
 *  - `missing`            → soft red destructive tokens.
 *
 * Colors use semantic role tokens ONLY (never raw `*-amber-*`/`*-red-*`) so dark
 * mode and the design-token guard both hold. `reasons` is surfaced via the native
 * `title` tooltip (and read by assistive tech) — kept lightweight on purpose so
 * the badge can sit inline in a dense card header.
 */

const HEALTH_LABELS: Record<Exclude<ActionQueueDataHealth, 'fresh'>, string> = {
  stale: 'Stale',
  partial: 'Partial',
  missing: 'Missing data',
};

const HEALTH_TOKENS: Record<Exclude<ActionQueueDataHealth, 'fresh'>, string> = {
  // -strong text shade on a -soft tinted background → WCAG AA on the tint.
  stale: 'bg-warning-soft text-warning-strong',
  partial: 'bg-warning-soft text-warning-strong',
  missing: 'bg-destructive-soft text-destructive-strong',
};

interface DataHealthBadgeProps {
  dataHealth?: ActionQueueDataHealth | null;
  reasons?: string[];
  className?: string;
}

function DataHealthBadge({ dataHealth, reasons, className }: DataHealthBadgeProps) {
  // `fresh` and any unknown/absent value render nothing — absence is the
  // "healthy" signal; we only ever draw attention to a problem.
  if (dataHealth == null || dataHealth === 'fresh') {
    return null;
  }

  const label = HEALTH_LABELS[dataHealth];
  const tokens = HEALTH_TOKENS[dataHealth];

  // Defensive: an unknown health string (contract drift) renders nothing rather
  // than an untokenized/blank pill.
  if (!label || !tokens) {
    return null;
  }

  const title = reasons && reasons.length > 0 ? reasons.join(' · ') : undefined;

  return (
    <span
      className={cn(
        'inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium',
        tokens,
        className,
      )}
      title={title}
      data-testid="data-health-badge"
    >
      {label}
    </span>
  );
}

export default memo(DataHealthBadge);
