// Locale-aware rendering of a persisted qaf_plausibility_issue.explanation
// value (KAR-906/P3.2). Small client component so a mostly-server-rendered
// parent (qaf-comparison-detail.tsx, qaf-g60-detail.tsx) does not itself need
// 'use client' just to read the UI locale — Next.js allows a Server
// Component to render a Client Component child.
//
// decodeBilingual is tolerant of legacy plain-German text with no bilingual
// marker (pre-KAR-906 rows) — those decode to { de: text, en: text }, so the
// EN branch below falls back to the same DE text automatically, matching the
// task's explicit "Bestands-Issues ohne EN tolerant" requirement.
//
// tdd-guard:skip — presentational primitive (locale pick + decode call),
// same category as qaf-section.tsx's Pill/PlaceholderSection; decodeBilingual
// itself is unit-tested in lib/qaf-differences/internal/__tests__/
// bilingual-message.test.ts.
'use client'

import { useI18n } from '@/lib/i18n/i18n-context'
import { decodeBilingual } from '@/lib/qaf-differences'

interface PlausibilityMessageProps {
  /** Raw qaf_plausibility_issue.explanation value (possibly bilingual-encoded
   * via encodeBilingual — the shape a DB-row read produces, e.g.
   * qaf-comparison-detail.tsx's persisted A4 plausibility list). */
  explanation: string | null
  /**
   * Live PlausibilityIssue.explanationEn (the shape a same-request, not-yet-
   * persisted computation produces, e.g. qaf-g60-detail.tsx's structure
   * issues, which are recomputed on every render rather than round-tripped
   * through qaf_plausibility_issue). When provided (including `undefined`
   * explicitly vs. simply omitted — both mean "not a live pair"), skips
   * decodeBilingual entirely and uses this value directly instead of trying
   * to decode `explanation` as an encoded envelope.
   */
  explanationEn?: string
  /** Fallback text shown when no explanation text is available at all (e.g. issue_type). */
  fallback: string
}

export function PlausibilityMessage({ explanation, explanationEn, fallback }: PlausibilityMessageProps) {
  const { locale } = useI18n()

  if (explanationEn !== undefined) {
    const text = locale === 'en' ? explanationEn || explanation : explanation
    return <>{text || fallback}</>
  }

  const { de, en } = decodeBilingual(explanation)
  if (!de && !en) return <>{fallback}</>
  const text = locale === 'en' ? en || de : de
  return <>{text}</>
}
