'use client' import Link from 'next/link' import { useCallback, useEffect, useRef, useState } from 'react' import { loadMunicipalityGeometryModule, loadMunicipalityZoneGeometryModule, loadTerritoryGeometryModule, } from '@/lib/bahiaGeometries' import { buildContentPieceCatalogHref } from '@/lib/contentPieceCatalog' import { resolveContentPieceHomeVisitor, selectContentPieceHomeItems, type ContentPieceHomeItem, type ContentPieceHomeVisitor, } from '@/lib/contentPieceHomeSelection' import { slugify } from '@/lib/slug' import { cn } from '@/lib/utils' import { COARSE_ACCURACY_M, readGeolocationPermissionState, requestCurrentPosition, type GeolocationPermissionState, } from '@/utilities/campaignGeolocation' import { ContentPieceTagChevron } from './ContentPieceCardParts' import { ContentPieceHomeCard } from './ContentPieceHomeCard' import { ContentPieceHomeFilterRow, type ContentPieceHomeFacets } from './ContentPieceHomeFilterRow' import { ContentPieceShareSheet } from './ContentPieceShareSheet' import { CONTENT_PIECE_FOCUS, CONTENT_PIECE_HOME_TAG, CONTENT_PIECE_LOCAL_TAG_LINK, CONTENT_PIECE_PRIMARY_BUTTON, } from './contentPieceClasses' /** * S39 — the Central sample board (artefato: cenas 01–05). The server renders * the recent selection; this island only upgrades it in silence when the * visitor's location is already available: permission `granted` resolves * without a dialog on mount, anything else needs the explicit "Usar minha * localização" affordance. Nothing is persisted, logged or sent anywhere — the * fix is matched against the committed meshes in the browser and dies here. * * No auto-prompt (unlike the staff B14 card): a surprise dialog on the home * burns trust, and the recent selection is already useful without it. * * S42 — the board also owns the one share sheet of the section (same S27 * mechanism as the catalogue) and the explore row that opens `/conteudos` * already filtered; the row never filters the sample. */ const COPY = { local: { desktop: 'Comece pelo material do seu território e mande para quem você conhece.', mobile: 'Material do seu território para compartilhar.', }, recent: { desktop: 'Veja as peças mais recentes e escolha uma para compartilhar.', mobile: 'Veja as peças mais recentes.', }, single: { desktop: 'Uma peça oficial já está pronta para você compartilhar.', mobile: 'Uma peça oficial já está pronta.', }, } as const const LOCATE_BUTTON = cn( 'inline-flex min-h-9 items-center gap-1.5 rounded-lg px-2 text-xs font-extrabold text-(--pt-red) underline underline-offset-4', CONTENT_PIECE_FOCUS, ) export const ContentPieceHomeBoard = ({ items, facets, }: { items: readonly ContentPieceHomeItem[] facets: ContentPieceHomeFacets }) => { const [permission, setPermission] = useState(null) const [visitor, setVisitor] = useState(null) const [locating, setLocating] = useState(false) const [attempted, setAttempted] = useState(false) const [playingId, setPlayingId] = useState(null) const [sharingItem, setSharingItem] = useState(null) const autoStartedRef = useRef(false) const locate = useCallback(async () => { setLocating(true) setAttempted(true) /* * The geometry chunks are shared with the staff map, so they are usually * cached; the dynamic imports can still fail on a weak connection, and the * loader memoizes the rejection — without the catch the section would keep * the recent selection silently, which is exactly the honest fallback. */ const loaded = await Promise.all([ requestCurrentPosition(), loadMunicipalityGeometryModule(), ]).catch(() => null) if (!loaded || !loaded[0].ok) { setLocating(false) return } const [result, municipalityGeometry] = loaded const [zoneGeometry, territoryGeometry] = await Promise.all([ loadMunicipalityZoneGeometryModule().catch(() => null), loadTerritoryGeometryModule().catch(() => null), ]) setVisitor( resolveContentPieceHomeVisitor({ point: result.fix, coarse: result.fix.accuracyM > COARSE_ACCURACY_M, municipalityGeometry, zoneGeometry, territoryGeometry, }), ) setLocating(false) }, []) useEffect(() => { /* * One automatic attempt per mount (the B14 guard): a re-render must never * fire a second position request, and Strict Mode re-runs this effect on * the same instance — cancelling the first run while the ref blocks the * second would leave the board idle forever. */ if (autoStartedRef.current) return autoStartedRef.current = true const start = async () => { const state = await readGeolocationPermissionState() setPermission(state) if (state === 'granted') void locate() } void start() }, [locate]) const selection = selectContentPieceHomeItems(items, visitor) const hasMunicipalityMatch = selection.some((entry) => entry.match === 'municipality') const isSingle = selection.length === 1 const showLocateButton = (permission === 'prompt' || permission === 'unknown') && visitor === null && selection.length > 1 && // The button stays mounted (disabled) while the fix is in flight, so the // tap does not drop the keyboard focus; after the attempt it is gone. (!attempted || locating) const copy = isSingle ? COPY.single : hasMunicipalityMatch ? COPY.local : COPY.recent const municipalityHref = visitor?.municipalityName ? buildContentPieceCatalogHref({ cidade: slugify(visitor.municipalityName) }) : null return ( <>

{locating ? 'Localizando…' : visitor !== null ? hasMunicipalityMatch ? 'Peças do seu município' : 'Peças recentes' : ''}

Central de Conteúdos

Peça voto pra
Solla 1313

{copy.mobile} {copy.desktop}

{hasMunicipalityMatch && municipalityHref ? ( // S42 — the sampled territory tag is itself a shortcut to the // catalogue filtered by the visitor's município (artefato cena 01). Para seu município ) : ( Seleção recente )} {hasMunicipalityMatch ? ( Localização usada só nesta visita ) : null}
{isSingle ? ( Ver todas as peças → ) : null}
{selection.map(({ item, match }) => ( setPlayingId((current) => (current === item.id ? null : item.id))} onEnded={() => setPlayingId((current) => (current === item.id ? null : current))} onShare={setSharingItem} /> ))}
{isSingle ? ( Ver todas as peças → ) : (
Ver todas as peças →
)}
{/* Cena 05 — with a single published piece the section ends on the CTA. */} {isSingle ? null : (
{showLocateButton ? ( <>

Opcional. Sem prompt no carregamento. Opcional e secundário. A seção já funciona sem isso.

) : (

A localização não é guardada. Cards personalizáveis ficam na seção anterior. Nenhum card personalizável entra nesta amostra.

)}
)} {sharingItem ? ( setSharingItem(null)} /> ) : null} ) }