'use client' import Link from 'next/link' import { useEffect, useId, useRef, useState, useTransition } from 'react' import { toast } from 'sonner' import { Badge } from '@/components/ui/Badge' import { Button } from '@/components/ui/button' import { FieldLabel, FieldLegend, FieldSet } from '@/components/ui/field' import { Spinner } from '@/components/ui/Spinner' import { Textarea } from '@/components/ui/textarea' import { getSuggestionPattern, SUGGESTION_TEXT_MAX_LENGTH, suggestionPostponeDays, suggestionTriageLabels, type SuggestionPatternId, type SuggestionTriageLevel, } from '@/lib/suggestionCatalog' import type { CampaignFormActionState } from '@/utilities/campaignFormActionError' import { firstFormActionMessage } from '@/utilities/campaignFormFields' /** The slice of the evaluator's view model the card renders — texts come from the catalog. */ export type SuggestionCardData = { municipalityID: number municipalityName: string municipalitySlug: string patternId: SuggestionPatternId triageLevel: SuggestionTriageLevel factors: string[] } type SuggestionResolveAction = ( state: CampaignFormActionState, formData: FormData, ) => Promise const GENERIC_ERROR_MESSAGE = 'Não foi possível registrar a decisão. Tente novamente.' /** * E11 — one triggered pattern as a decision card: the reading, the observed * facts, the ordered action menu, and the three ways a human answers it. * Accept and dismiss are EXPLICIT submits (they carry a choice or a reading — * the `campanha-edit-where-you-see` exception for confirmation flows, same as * E14); postpone is a single labeled tap. Nothing here auto-decides. */ export const SuggestionCard = ({ suggestion, showMunicipality = false, resolveAction, readOnly = false, }: { suggestion: SuggestionCardData /** Dashboard names the município; the detail card is already inside it. */ showMunicipality?: boolean resolveAction: SuggestionResolveAction /** C142 — read-only presentation (advisor with Edição `somente_leitura`): the card renders the reading with no decision actions. */ readOnly?: boolean }) => { const pattern = getSuggestionPattern(suggestion.patternId) const postponeDays = suggestionPostponeDays(suggestion.triageLevel) const baseId = useId() const titleId = `${baseId}-title` const [mode, setMode] = useState<'aceitar' | 'descartar' | null>(null) // The first menu action is the cheap 48h check — the recommended next step, // so it starts selected and one tap away under field pressure. const [chosenActionId, setChosenActionId] = useState(pattern.menu[0]?.id ?? '') const [note, setNote] = useState('') const [alternativeReading, setAlternativeReading] = useState('') const [errorMessage, setErrorMessage] = useState(null) const [isPending, startTransition] = useTransition() // Opening a form UNMOUNTS the trigger row (and vice versa), which would drop // keyboard focus on : send it to the first field on open, back to the // matching trigger on cancel. On success the whole card leaves the queue — // the toast's live region is the announcement then. const formRef = useRef(null) const triggersRef = useRef(null) const previousModeRef = useRef(null) useEffect(() => { const previous = previousModeRef.current previousModeRef.current = mode if (mode !== null) { formRef.current?.querySelector('input, textarea, button')?.focus() return } if (previous !== null) triggersRef.current?.querySelector('button')?.focus() }, [mode]) const submit = (fields: Record) => { setErrorMessage(null) const formData = new FormData() formData.set('municipality', String(suggestion.municipalityID)) formData.set('patternId', suggestion.patternId) for (const [key, value] of Object.entries(fields)) { if (value) formData.set(key, value) } startTransition(async () => { const result = await resolveAction({}, formData) if (result.status === 'success') { // The card leaves the queue when the revalidated RSC lands — the same // transition — so the toast is the persistent copy of what happened. toast.success(result.message) setMode(null) return } // One channel only: the card never unmounts on failure, so the inline // `role="alert"` line is the announcement — a toast would say it twice. setErrorMessage(firstFormActionMessage(result) ?? GENERIC_ERROR_MESSAGE) }) } return (
Nível {suggestion.triageLevel}

{pattern.title}

{showMunicipality ? ( {suggestion.municipalityName} ) : null}

{pattern.probableReading}

{suggestion.factors.length ? (
    {suggestion.factors.map((factor) => (
  • {factor}
  • ))}
) : null} {/* The menu IS a sequence — cheap before expensive — so the numbering carries information, it is not scaffolding. */}
    {pattern.menu.map((action, index) => (
  1. {index + 1}º {action.label}
  2. ))}

Contraindicação: {pattern.contraindication}

{readOnly ? null : mode === null ? (
) : null} {mode === 'aceitar' ? (
{ event.preventDefault() submit({ outcome: 'aceita', chosenActionId, note }) }} >
Qual ação do menu foi tomada? {pattern.menu.map((action) => ( ))}
Nota (opcional)