'use client' import { ArrowRightIcon, LocateFixedIcon } from 'lucide-react' import Link from 'next/link' import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react' import { Button } from '@/components/ui/button' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Spinner } from '@/components/ui/Spinner' import { loadMunicipalityGeometryModule, loadMunicipalityZoneGeometryModule, } from '@/lib/bahiaGeometries' import { formatDistanceKm, resolveNearbyMunicipality, type AccessibleMunicipality, type NearbyMunicipalityResolution, } from '@/lib/municipalityProximity' import { COARSE_ACCURACY_M, hasPromptedThisSession, markPromptedThisSession, readGeolocationPermissionState, requestCurrentPosition, type GeolocationFailureReason, } from '@/utilities/campaignGeolocation' /** Everything except `unsupported`, which is a state of its own — the card hides. */ type ActionableFailureReason = Exclude type CardState = /** * Mounted, permission not read yet. Renders the explanation without the CTA: * showing a button that turns into a spinner milliseconds later invites a tap * that fires a second position request. */ | { status: 'starting' } /** Waiting for the user: either the session already prompted, or permission was refused before. */ | { status: 'ready' } | { status: 'locating' } | { status: 'resolved'; resolution: NearbyMunicipalityResolution; coarse: boolean } | { status: 'failed'; reason: ActionableFailureReason } /** No geolocation in this browser: nothing to act on, so the card takes no space. */ | { status: 'unsupported' } /** The states that render — `unsupported` never reaches the body. */ type VisibleCardState = Exclude const failureCopy: Record = { denied: { title: 'Localização bloqueada neste navegador', hint: 'Libere o acesso à localização nas permissões do site e tente de novo.', }, // Also the copy for a geometry chunk that failed to load, hence the reload nudge: // the module promise memoizes its rejection, so only a reload can recover. unavailable: { title: 'Não foi possível obter sua localização', hint: 'Tente de novo — em outro ponto, ou recarregando a página.', }, timeout: { title: 'A localização demorou para responder', hint: 'Sinal fraco costuma ser a causa. Tente de novo.', }, } /** * B14 — "abrir a ficha do município onde estou" no Início staff. * * A posição fica no navegador: o casamento usa a malha municipal que o mapa já * carrega e, em Salvador multi-zona, a malha das 19 ZE (B8 F2). Falha no chunk * de zonas degrada para a lista filtrada — sem action, sem `Consent`. * * `leader` nunca chega aqui: a página `/campanha` roteia liderança para o * `LeaderContactsPanel` antes do dashboard. */ /** * Filtered-list href per multi-zone city, keyed by IBGE code — only the cities * that have several zone municipalities, hence `Partial`: most codes are absent * and the lookup must be guarded. Ready-made on the server on purpose: importing * the canonical list-URL builder here costs 21 KB of the dashboard's First Load * JS (see `buildZoneCityHrefs` in `CampaignDashboard`). */ type ZoneCityHrefs = Readonly>> export const NearestMunicipalityCard = ({ accessible, zoneCityHrefs, }: { accessible: readonly AccessibleMunicipality[] zoneCityHrefs: ZoneCityHrefs }) => { const [state, setState] = useState({ status: 'starting' }) const autoStartedRef = useRef(false) const locate = useCallback(async () => { setState({ status: 'locating' }) /* * The geometry chunk is shared with the dashboard map, so this is usually * already resolved by the time the fix arrives. `requestCurrentPosition` * cannot reject, but the dynamic import can (ChunkLoadError on a weak field * connection) — and `loadMunicipalityGeometryModule` memoizes the rejection, * so without this catch the card would spin forever with a retry button that * can never succeed. */ const loaded = await Promise.all([ requestCurrentPosition(), loadMunicipalityGeometryModule(), ]).catch(() => null) if (!loaded) { setState({ status: 'failed', reason: 'unavailable' }) return } const [result, geometry] = loaded if (!result.ok) { setState( result.reason === 'unsupported' ? { status: 'unsupported' } : { status: 'failed', reason: result.reason }, ) return } const zoneModule = await loadMunicipalityZoneGeometryModule().catch(() => null) setState({ status: 'resolved', coarse: result.fix.accuracyM > COARSE_ACCURACY_M, resolution: resolveNearbyMunicipality({ point: result.fix, geometry, zoneGeometry: zoneModule ?? undefined, accessible, }), }) }, [accessible]) useEffect(() => { /* * One automatic attempt per mount: a re-render with a fresh `accessible` * array must never fire a second position request. The guard is a ref * rather than a cancellation flag on purpose — Strict Mode re-runs this * effect on the same instance, and cancelling the first run while the ref * blocks the second one would leave the card idle forever. */ if (autoStartedRef.current || accessible.length === 0) return autoStartedRef.current = true const start = async () => { const permission = await readGeolocationPermissionState() if (permission === 'granted') { void locate() return } // Product decision (2026-07-24): ask automatically, but at most once per // tab session — never on every navigation back to the dashboard. if (permission !== 'denied' && !hasPromptedThisSession()) { markPromptedThisSession() void locate() return } setState( permission === 'denied' ? { status: 'failed', reason: 'denied' } : { status: 'ready' }, ) } void start() }, [accessible.length, locate]) if (accessible.length === 0 || state.status === 'unsupported') return null return ( {/* Mounted from the start so the state change is actually announced. */}

{statusAnnouncement(state)}

{renderBody(state, locate, zoneCityHrefs)}
) } /** * The multi-second wait and its outcome must reach a screen reader, and the * visible copy is spread over paragraph and button — hence one sentence here. */ const statusAnnouncement = (state: VisibleCardState): string => { if (state.status === 'locating') return 'Localizando…' if (state.status === 'failed') return failureCopy[state.reason].title if (state.status !== 'resolved') return '' return headlineSentence(locationHeadline(state.resolution)) } /** * Where the actor is, in parts: the announcement joins them into a sentence and * the visible headline emphasizes the place, so the copy exists in one place and * the two cannot drift apart. */ type LocationHeadline = { lead: string; place: string | null; tail: string } const PLACE_LEAD = 'Você está em ' const locationHeadline = (resolution: NearbyMunicipalityResolution): LocationHeadline => { switch (resolution.kind) { case 'inScope': return { lead: PLACE_LEAD, place: resolution.municipality.name, tail: '.' } case 'zoneCity': return { lead: PLACE_LEAD, place: resolution.city, tail: ', dividida por zona eleitoral.' } case 'outOfScope': return { lead: PLACE_LEAD, place: resolution.city, tail: ', fora da sua carteira.' } case 'outsideBahia': // What to do about it is the detail's job, so the headline states only the // fact — the same sentence whether or not there is a município to offer. return { lead: 'Você está fora da Bahia.', place: null, tail: '' } } } const headlineSentence = ({ lead, place, tail }: LocationHeadline): string => `${lead}${place ?? ''}${tail}` const Headline = ({ headline: { lead, place, tail } }: { headline: LocationHeadline }) => (

{lead} {place ? {place} : null} {tail}

) const LocateButton = ({ label, onClick }: { label: string; onClick: () => void }) => ( ) const OpenMunicipalityButton = ({ slug, name }: { slug: string; name: string }) => ( ) const Explanation = ({ children }: { children: ReactNode }) => (

{children}

) const CoarseFixCaveat = () => ( Localização aproximada (o navegador não usou o GPS) — confira o município antes de agir. ) const NothingNearby = () => Nenhum município da sua carteira por perto. const renderBody = ( state: VisibleCardState, locate: () => void, zoneCityHrefs: ZoneCityHrefs, ): ReactNode => { if (state.status === 'starting' || state.status === 'ready') { return ( <> Abra a ficha do município em que você está. {/* No CTA while permission is unread: it would become a spinner under the finger. */} {state.status === 'ready' ? ( ) : null} ) } if (state.status === 'locating') { return (

{/* The live region above announces the wait; Spinner's own role="status" would repeat it. */}

) } if (state.status === 'failed') { const copy = failureCopy[state.reason] return ( <>

{copy.title}

{copy.hint} ) } return ( <> {/* Between "where you are" and what to do about it — a hedge after the CTA is a footnote. */} {state.coarse ? : null} {resolutionDetail(state.resolution, locate, zoneCityHrefs)} ) } /** What to do about where you are — the headline itself comes from `locationHeadline`. */ const resolutionDetail = ( resolution: NearbyMunicipalityResolution, locate: () => void, zoneCityHrefs: ZoneCityHrefs, ): ReactNode => { const nearest = 'nearestInScope' in resolution ? resolution.nearestInScope : null const nearestDetail = nearest ? ( <> Mais próximo na sua carteira: {nearest.municipality.name}, a{' '} {formatDistanceKm(nearest.distanceKm)}. ) : null switch (resolution.kind) { case 'inScope': { const nearestZone = resolution.match === 'nearestZone' && resolution.distanceKm !== undefined ? ( Zona eleitoral mais próxima na sua carteira, a {formatDistanceKm(resolution.distanceKm)}{' '} — confira antes de agir. ) : null return ( <> {nearestZone} ) } case 'zoneCity': { // Server and client read the same `accessible` set, so the href is there — // but a button labeled "Ver zonas de X" that opened the unfiltered list // would be worse than no button. const zonesHref = zoneCityHrefs[resolution.ibgeCode] return ( <> Escolha entre as {resolution.zoneCount} zonas — a localização não distingue a zona. {zonesHref ? ( ) : null} ) } case 'outOfScope': return nearestDetail ?? case 'outsideBahia': return ( nearestDetail ?? ( <> {/* Out of state with nothing to offer is also what a bad fix looks like. */} ) ) } }