'use client'

// Drill-down source-cell chips for Multi-QAF findings (KAR-947, task
// requirement 5: "sourceRefs (Sheet/Zelle) je Befund anzeigen — wie
// bestehende Provenance-Komponente qaf-provenance.tsx"). Deliberately its
// own small component rather than reusing ProvenanceTooltip directly: that
// component's props (altCell/neuCell as single strings, parseConfidence,
// manual-override provenance) are shaped for the Standard-QAF per-field
// case; a Multi-QAF finding instead carries a variable-length
// `MultiQafCellRef[]` (0..n cells across one or more sheets — a shared
// material row alone can cite several). Same interaction pattern (Info icon
// + Tooltip, keyboard-reachable button) as ProvenanceTooltip/
// WorkbookSafetyBadges for visual consistency.
// tdd-guard:skip — presentational; formatCellRef below is pure and trivial
// enough that a dedicated unit test would just restate the implementation.

import { Info } from 'lucide-react'
import { useI18n } from '@/lib/i18n/i18n-context'
import { Tooltip } from '@/components/ui/tooltip'
import { pickLocaleText } from '@/components/qaf-differences/qaf-provenance'

export interface SourceRefLike {
  sheet: string
  cell: string | null
  row?: number | null
  column?: number | null
}

function formatCellRef(ref: SourceRefLike): string {
  if (ref.cell) return `${ref.sheet}!${ref.cell}`
  if (typeof ref.row === 'number') return `${ref.sheet} (Zeile ${ref.row})`
  return ref.sheet
}

/**
 * Compact hover/tap info icon listing every source cell a finding cites.
 * Renders nothing when `refs` is empty (nothing to drill into) — same "don't
 * render a dead affordance" discipline ProvenanceTooltip already follows.
 */
export function MultiQafSourceRefs({ refs, label }: { refs: readonly SourceRefLike[]; label?: string }) {
  const { locale } = useI18n()
  if (refs.length === 0) return null
  const btnLabel = pickLocaleText(locale, 'Quellzellen anzeigen', 'Show source cells')
  const content = (
    <span className="block space-y-0.5">
      {label && <span className="block font-medium">{label}</span>}
      {refs.map((r, i) => (
        <span key={i} className="block font-mono text-[11px]">
          {formatCellRef(r)}
        </span>
      ))}
    </span>
  )
  return (
    <Tooltip content={content}>
      <button type="button" aria-label={btnLabel} className="ml-1 inline-flex items-center align-middle text-muted-foreground hover:text-foreground">
        <Info size={12} />
      </button>
    </Tooltip>
  )
}
