import { useState } from 'react' import type { Vertebra, VertebralRegion } from '@faunosteo/domain' import Dialog from '@/components/ui/Dialog' import Button from '@/components/ui/Button' import Chip from '@/components/ui/Chip' import { pickLabel } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' export interface VertebraPickerProps { open: boolean onClose: () => void onConfirm: (vertebrae: Vertebra[]) => void initial: Vertebra[] /** Ordered regions of the sheet (`vertebral_config.regions`). */ regions: readonly VertebralRegion[] title: string /** Tab to open on. Takes priority so a click always lands on its own zone. */ initialRegion?: string } const sameVertebra = (a: Vertebra, r: string, i: number) => a.region === r && a.index === i /** * Picks vertebrae across every region of the sheet. A region shows its * usual count; when the sheet documents a wider range (D6), one control * extends the grid to the documented maximum. Nothing horse-specific here. */ export default function VertebraPicker({ open, onClose, onConfirm, initial, regions, title, initialRegion, }: VertebraPickerProps) { const t = useT() const locale = useLocaleStore((s) => s.locale) const [selected, setSelected] = useState(initial) const [activeCode, setActiveCode] = useState( () => initialRegion ?? initial[0]?.region ?? regions[0]?.code ?? '', ) const [extended, setExtended] = useState>(() => new Set()) const active = regions.find((r) => r.code === activeCode) ?? regions[0] if (!active) return null const maxCount = active.count_range?.max ?? active.count const highestPicked = Math.max( 0, ...selected.filter((v) => v.region === active.code).map((v) => v.index), ) const canExtend = maxCount > active.count const showExtended = extended.has(active.code) || highestPicked > active.count const count = showExtended ? maxCount : active.count const has = (r: string, i: number) => selected.some((v) => sameVertebra(v, r, i)) const toggle = (r: string, i: number) => setSelected((cur) => has(r, i) ? cur.filter((v) => !sameVertebra(v, r, i)) : [...cur, { region: r, index: i }], ) const all = (r: string, n: number) => setSelected((cur) => [ ...cur.filter((v) => v.region !== r), ...Array.from({ length: n }, (_, k) => ({ region: r, index: k + 1 })), ]) const none = (r: string) => setSelected((cur) => cur.filter((v) => v.region !== r)) return (
{regions.map((r) => ( ))}
{Array.from({ length: count }, (_, k) => k + 1).map((i) => ( toggle(active.code, i)} > {active.code} {i} ))}
{canExtend && !showExtended && ( )} {canExtend && showExtended && ( {t('vertebra.range_note') .replace('{usual}', String(active.count)) .replace('{min}', String(active.count_range?.min ?? active.count)) .replace('{max}', String(maxCount))} )}
) }