import { CircleAlertIcon, SearchXIcon } from 'lucide-react' import Link from 'next/link' import { advisorEntriesFromIds, formatAdvisorNamesTooltip, MissingAdvisorBadge, MunicipalityAdvisorAvatarStack, } from '@/components/campaign/municipality/MunicipalityAdvisorAvatarStack' import { MunicipalityLevelBadge } from '@/components/campaign/municipality/MunicipalityLevelBadge' import { MunicipalityListAdvisorsControl } from '@/components/campaign/municipality/MunicipalityListAdvisorsControl' import { MunicipalityListExpectedVotesControl } from '@/components/campaign/municipality/MunicipalityListExpectedVotesControl' import { MunicipalityListGoalCoverageCell } from '@/components/campaign/municipality/MunicipalityListGoalCoverageCell' import { MunicipalityListLevelControl } from '@/components/campaign/municipality/MunicipalityListLevelControl' import { MunicipalityListSignalControl } from '@/components/campaign/municipality/MunicipalityListSignalControl' import { MunicipalityListTrendControl } from '@/components/campaign/municipality/MunicipalityListTrendControl' import { MunicipalitySortableHead } from '@/components/campaign/municipality/MunicipalitySortableHead' import { TerritoryLink } from '@/components/campaign/municipality/TerritoryLink' import { CampaignHoverTooltip } from '@/components/campaign/shared/CampaignHoverTooltip' import { CampaignTransitionAnchor } from '@/components/campaign/shared/CampaignListPending' import { CampaignTable, type CampaignTableColumn } from '@/components/campaign/shared/CampaignTable' import { Badge } from '@/components/ui/Badge' import { buttonVariants } from '@/components/ui/button' import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle, } from '@/components/ui/Empty' import { formatElectionNumber, formatPlacementOrdinal, formatVoteSharePercent, } from '@/lib/electionFormat' import { formatEngagementLevelLabel } from '@/lib/engagementLevel' import { cn } from '@/lib/utils' import type { CampaignFormActionState } from '@/utilities/campaignFormActionError' import { formatTerritorialClassWhy, municipalityColumnDescriptions, municipalityGeographyParts, municipalityKindLabels, municipalityPriorityLabels, territorialClassBadgeVariant, territorialClassLabels, } from '@/utilities/municipalityLabels' import { clearMunicipalityListFilters, type MunicipalityFilterOption, } from '@/utilities/municipalityListFilters' import { buildMunicipalityListHref, formatMunicipalityListSortSummary, resolveMunicipalityListSort, type MunicipalityListState, } from '@/utilities/municipalityListUrl' import { formatMunicipalitySignalAgeLabel, isMunicipalitySignalCold, MUNICIPALITY_COLD_SIGNAL_DAYS, municipalitySignalAgeInDays, } from '@/utilities/municipalitySignal' import type { EligibleAdvisorOption, MunicipalityAdvisorSummary, MunicipalityListViewModel, } from '@/utilities/municipalityViewModels' import { toMunicipalityPledgeCoverageView } from '@/utilities/votePledgeViews' const dateFormatter = new Intl.DateTimeFormat('pt-BR') type MunicipalityStaffFormAction = ( state: CampaignFormActionState, formData: FormData, ) => Promise type MunicipalityColumnFilterOptions = { /** Bare catalog slugs — labeled on the client (B16+ payload trim). */ name: readonly string[] region: MunicipalityFilterOption[] advisor: MunicipalityFilterOption[] } export type MunicipalityListProps = { municipalities: MunicipalityListViewModel[] advisorNamesById: ReadonlyMap isStaffView: boolean isCoordinator: boolean /** * E14 — moving the ladder is unrestricted staff (coordinator + candidate), * a wider set than `isCoordinator`, so it travels as its own prop instead of * quietly hiding the control from the candidate. */ canMoveEngagementLevel: boolean advisorOptions: EligibleAdvisorOption[] columnFilterOptions: MunicipalityColumnFilterOptions signalFormAction: MunicipalityStaffFormAction state: MunicipalityListState } const VotePositionReadout = ({ position, layout, }: { position: NonNullable layout: 'table' | 'card' }) => { const share = formatVoteSharePercent(position.share) const rank = formatPlacementOrdinal(position.rank) const metaLine = `${formatElectionNumber(position.votes)} · ${rank}` const ariaLabel = `${share} da votação estadual, ${formatElectionNumber(position.votes)} votos, ${rank} de ${formatElectionNumber(position.totalUnits)}` return (
{share} {metaLine}
) } /** * E10 classe. Only the pill is visible — spelling the factors out under it * bloats the dense row on desktop and, on the mobile card, was the tallest * block in a card the field asked us to shorten (B42). So the "por quê" is * `sr-only` text here, and both surfaces add a tap/hover/focus channel around * it: the column's `cellTooltip` in the table, an explicit `CampaignHoverTooltip` * on the card. Neither may be dropped — the class must never reach anyone, * sighted or not, as a bare verdict. */ const TerritorialClassReadout = ({ municipality }: { municipality: MunicipalityListViewModel }) => { const why = formatTerritorialClassWhy(municipality.territorialClassFactors) if (municipality.territorialClass === 'sem_base') { // Same idiom as the "2022" column: absent data is a dash, not a pill. return ( {why} ) } return ( <> {territorialClassLabels[municipality.territorialClass]} {why} ) } /** * E9 frescor: how long since anybody recorded anything here (staff update or * leadership pledge). * * Cold reads in the warning amber, NOT destructive: early in the campaign * most municípios are past the 21-day threshold, and painting them all red * would drown the one state that really is an error in this list — a priority * município with nobody answering for it. Same reason it stays text with an * icon instead of a third badge: the row already carries the priority pill and, * when it applies, the missing-advisor one. */ const SignalAgeReadout = ({ lastSignalAt, layout, }: { lastSignalAt: string | null layout: 'table' | 'card' }) => { const ageInDays = municipalitySignalAgeInDays(lastSignalAt) const isCold = isMunicipalitySignalCold(ageInDays) const ageLabel = formatMunicipalitySignalAgeLabel(ageInDays) const dateLabel = lastSignalAt ? dateFormatter.format(new Date(lastSignalAt)) : null return (
{isCold ? {dateLabel ? ( {dateLabel} ) : null}
) } /** Replaces only the rows: the filter header row and the overview stay put. */ const MunicipalityListEmptyState = ({ state }: { state: MunicipalityListState }) => ( Nenhum município encontrado Ajuste a busca ou os filtros. Você só vê municípios dentro do seu escopo. {/* Same contract as the filter bar's Limpar: drop filters, keep the sort. */} Limpar busca e filtros ) const advisorEntries = ( municipality: MunicipalityListViewModel, advisorNamesById: ReadonlyMap, ) => advisorEntriesFromIds(municipality.advisorIDs, advisorNamesById) const advisorNames = ( municipality: MunicipalityListViewModel, advisorNamesById: ReadonlyMap, ): string[] => advisorEntries(municipality, advisorNamesById).map((advisor) => advisor.name) /** The desktop table as column definitions (Pass 2 W1 list system). */ const municipalityListColumns = ({ state, isStaffView, isCoordinator, canMoveEngagementLevel, columnFilterOptions, advisorNamesById, advisorOptions, signalFormAction, }: MunicipalityListProps): Array> => [ { id: 'name', mandatory: true, head: ( Município ), cellClassName: 'sticky left-0 z-[5] min-w-56 whitespace-normal bg-background', cell: (municipality) => (
{municipality.name} {municipality.priority === 'alta' && isStaffView ? ( {municipalityPriorityLabels.alta} ) : null}
), }, { id: 'region', head: ( Território ), cellClassName: 'max-w-56 whitespace-normal text-muted-foreground', cell: (municipality) => , }, { id: 'kind', head: ( Tipo ), cell: (municipality) => municipalityKindLabels[municipality.kind], }, { id: 'votos', head: ( ), cellClassName: 'text-right', cell: (municipality) => municipality.votePosition2022 ? ( ) : ( — ), }, ...(isStaffView ? ([ { // Sits right after "2022": both read the same TSE artifact, and the // class is the one-word summary of the votes beside it. id: 'classe', head: ( Classe ), cell: (municipality) => , // The factors behind the label — the cell keeps them as `sr-only` // text, so this stays a redundant affordance (see `cellTooltip`). cellTooltip: (municipality) => municipality.territorialClass === 'sem_base' ? null : formatTerritorialClassWhy(municipality.territorialClassFactors), }, { // Right after "Classe": the pair reads diagnosis then decision. id: 'level', head: ( Nível ), cell: (municipality) => canMoveEngagementLevel ? ( ) : ( ), // The editable cell wraps its own trigger in a tooltip; declaring it // here too would double it up on the same gesture (as in `advisors`). cellTooltip: (municipality) => canMoveEngagementLevel || !municipality.engagementLevel ? null : [formatEngagementLevelLabel(municipality.engagementLevel), municipality.levelNote] .filter(Boolean) .join(' — '), }, { id: 'advisors', head: ( Assessores ), cell: (municipality) => isCoordinator ? ( ) : ( ), // The coordinator's cell already wraps its own Popover trigger in a // tooltip (see `MunicipalityListAdvisorsControl`) — declaring it // here too would double it up on the same gesture. cellTooltip: (municipality) => isCoordinator ? null : formatAdvisorNamesTooltip(advisorEntries(municipality, advisorNamesById)), }, { id: 'trend', head: ( Tendência ), cell: (municipality) => ( ), }, { id: 'expectedVotes', head: ( Votos estimados ), cellClassName: 'relative overflow-visible align-middle text-center', cell: (municipality) => (
), }, { id: 'lastSignal', head: ( Último sinal ), cell: (municipality) => ( ), }, { id: 'goalCoverage', head: ( Cobertura da meta ), cell: (municipality) => ( ), }, ] satisfies Array>) : ([ { id: 'lastUpdateAt', head: ( Última atualização ), cell: (municipality) => municipality.lastUpdateAt ? dateFormatter.format(new Date(municipality.lastUpdateAt)) : 'Sem atualização', }, ] satisfies Array>)), ] export const MunicipalityList = (props: MunicipalityListProps) => { const { municipalities, advisorNamesById, isStaffView, isCoordinator, advisorOptions, state } = props const { sort: activeSort, dir: activeDir } = resolveMunicipalityListSort(state) const sortSummary = formatMunicipalityListSortSummary(activeSort, activeDir) const columns = municipalityListColumns(props) return ( <>

{sortSummary}

{municipalities.length === 0 ? : null} {municipalities.map((municipality) => { const names = advisorNames(municipality, advisorNamesById) const position = municipality.votePosition2022 const isPriority = municipality.priority === 'alta' const { region, zoneSuffix } = municipalityGeographyParts(municipality) return (
{/* * The name's link stretches over the whole card, so tapping * anywhere that isn't a control opens the município — B42 * removed the "Abrir município" button that used to be the * only way in. Each control carries its own `relative`, * which paints it above this overlay and keeps its own tap; * nothing else in the card may be positioned, or it would * become a hole in the card's tap target. */}

{municipality.name}

{zoneSuffix ? ` ${zoneSuffix}` : null}

{position ? : null}
{isPriority && isStaffView ? ( {municipalityPriorityLabels.alta} ) : null}
{isStaffView ? (
Classe
{/* * The card has no hover, so the "por quê" the class must * never travel without gets the same tap-to-open channel * the desktop column gets through `cellTooltip` — the * `sr-only` copy inside the readout covers AT either way. */}
Cobertura da meta
Votos estimados
Nível
{props.canMoveEngagementLevel ? ( ) : ( )}
Tendência
Último sinal
Assessores
{isCoordinator ? ( ) : names.length ? ( names.join(', ') ) : ( )}
) : null}
) })}
{/* A sticky can't paint the row border, hence the inset shadow. */} {sortSummary}. Coluna 2022: {municipalityColumnDescriptions.votos} } columns={columns} rows={municipalities} rowKey={(municipality) => municipality.id} empty={} /> ) }