import { useMemo, useState } from 'react' import type { Finding, FindingZone, LateralSide, Observation, ReportZone, } from '@faunosteo/core-wasm/types' import { AnimatePresence, motion } from 'motion/react' import Card from '@/components/ui/Card' import Badge from '@/components/ui/Badge' import Button from '@/components/ui/Button' import Label from '@/components/ui/Label' import Textarea from '@/components/ui/Textarea' import FindingsTreePicker from './FindingsTreePicker' import FreeTextFindingInput from './FreeTextFindingInput' import SeveritySelector from './SeveritySelector' import { isObservable, type SheetIndex } from '@/services/sheetIndex' import { pickLabel } from '@/i18n/pickLocaleLabel' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' import type { Locale } from '@/i18n/types' import { coreFailureMessage } from '@/core/failure' export interface ObservationCardProps { observation: Observation index: number expanded: boolean onToggle: () => void onDelete: () => void onMoveUp: () => void onMoveDown: () => void canMoveUp: boolean canMoveDown: boolean // Editor body props (used only when expanded) sheet: SheetIndex onChange: (next: Observation) => void onOpenVertebraPicker: (zoneIndex: number) => void onRemoveZone: (zoneIndex: number) => void } /** Zone label: the sheet's current name, else the snapshot, else the id. */ export function zoneLabel( z: ReportZone, sheet: SheetIndex, locale: Locale, ): string { const annotation = sheet.annotation(z.annotationId) if (annotation) return pickLabel(sheet.name(annotation), locale) const snapshot = locale === 'en' ? z.labelEnSnapshot || z.labelFrSnapshot : z.labelFrSnapshot || z.labelEnSnapshot return snapshot || z.annotationId } function describeZone( z: ReportZone, sheet: SheetIndex, locale: Locale, t: (key: string) => string, ): string { const label = zoneLabel(z, sheet, locale) if (z.vertebrae?.length) { return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})` } if (z.side) { return `${label} (${t(z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})` } return label } interface ZoneTree { zone: FindingZone side?: LateralSide } /** One picker per (finding zone, side) the observation's zones resolve to. */ function zoneTrees(observation: Observation, sheet: SheetIndex): ZoneTree[] { const seen = new Set() const out: ZoneTree[] = [] for (const z of observation.zones) { const annotation = sheet.annotation(z.annotationId) if (!isObservable(annotation) || !annotation.finding_zone_id) continue const zone = sheet.findingZone(annotation.finding_zone_id) if (!zone) continue const key = z.side ? `${zone.id}:${z.side}` : zone.id if (seen.has(key)) continue seen.add(key) out.push({ zone, side: z.side }) } return out } /** Findings the sheet no longer holds at their path (migrated data, kept verbatim). */ function unresolvedFindings( observation: Observation, sheet: SheetIndex, ): Finding[] { return observation.findings.filter( (f) => !sheet.hasNode(f.findingZoneId, f.path), ) } export default function ObservationCard({ observation, index, expanded, onToggle, onDelete, onMoveUp, onMoveDown, canMoveUp, canMoveDown, sheet, onChange, onOpenVertebraPicker, onRemoveZone, }: ObservationCardProps) { const t = useT() const locale = useLocaleStore((s) => s.locale) const [expandedZoneId, setExpandedZoneId] = useState(null) const zoneCount = observation.zones.length const findingCount = observation.findings.length + observation.freeTextFindings.length const zoneCountLabel = t( zoneCount > 1 ? 'observation.zone_label_plural' : 'observation.zone_label_singular', ) const findingCountLabel = t( findingCount > 1 ? 'observation.finding_label_plural' : 'observation.finding_label_singular', ) const trees = useMemo( () => zoneTrees(observation, sheet), [observation, sheet], ) const unresolved = useMemo( () => unresolvedFindings(observation, sheet), [observation, sheet], ) function onHeaderKey(event: React.KeyboardEvent) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault() onToggle() } } const stop = (fn: () => void) => (event: React.MouseEvent) => { event.stopPropagation() fn() } /** The core builds or removes the finding of the clicked leaf (R2). */ function toggleFinding( findingZoneId: string, side: LateralSide | undefined, path: string[], leafPosition: number, ) { const outcome = sheet.ops.toggleFinding({ observation, findingZoneId, path, leafPosition, ...(side ? { side } : {}), }) if (outcome.ok) onChange(outcome.value) else window.alert(coreFailureMessage(t)) } const removeFinding = (target: Finding) => onChange({ ...observation, findings: observation.findings.filter((f) => f !== target), }) return (
{t('observation.badge_n')} {index + 1} {observation.severity && ( {t(`severity.${observation.severity}`)} )}
{zoneCount} {zoneCountLabel} ยท {findingCount} {findingCountLabel}
{!expanded && observation.comment && (

{observation.comment}

)}
event.stopPropagation()} >
{expanded && (
{observation.zones.length === 0 ? (

{t('observation.zones_empty')}

) : (
    {observation.zones.map((z, i) => (
  • {describeZone(z, sheet, locale, t)} {z.unresolved && !sheet.annotation(z.annotationId) && ( {t('observation.unresolved_short')} )} {sheet.isSpine(z.annotationId) && ( )}
  • ))}
)}
{trees.length === 0 ? (

{observation.zones.length === 0 ? t('observation.findings_pick_zone_first') : t('observation.findings_no_catalog')}

) : (
    {trees.map(({ zone, side }) => { const pickerKey = side ? `${zone.id}:${side}` : zone.id const open = expandedZoneId === pickerKey const selectedCount = observation.findings.filter( (f) => f.findingZoneId === zone.id && f.side === side, ).length const selectedAria = `${selectedCount} ${selectedCount > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}` return (
  • {open && (
    toggleFinding(zone.id, side, path, leafPosition) } />
    )}
  • ) })}
)}
{unresolved.length > 0 && (

{t('observation.findings_unresolved_help')}

    {unresolved.map((f, i) => (
  • {f.requiresVetReferral ? 'โš  ' : ''} {locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot} {f.side && ` (${t(f.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`}
  • ))}
)}
onChange({ ...observation, freeTextFindings: items }) } />
onChange({ ...observation, severity: s })} />