import { useEffect, useState } from 'react'; import { Link } from '@inertiajs/react'; import { portalRequest } from '@/lib/portal-api'; type Match = { id: string; slug: string; title: string; published_at?: string | null; }; function publicationDate(value?: string | null): string | null { if (typeof value !== 'string' || !value.trim()) return null; const date = new Date(value); return Number.isNaN(date.getTime()) ? null : date.toLocaleDateString('pt-MZ'); } type Classification = { target_type: string; target_id: string; label: string; purpose?: string; purpose_label?: string; source_reference?: string | null; }; const classificationKey = (row: Classification) => `${row.target_type}:${row.target_id}:${row.purpose ?? ''}`; type Props = { currentId: string; catalogueUrl: string; criteria: string[]; classifications?: Classification[]; }; export default function SimilarBusinesses({ currentId, catalogueUrl, criteria, classifications = [], }: Props) { const [attempt, setAttempt] = useState(0); const [selection, setSelection] = useState({ recordId: currentId, value: '', }); const selected = selection.recordId === currentId ? classifications.find( (row) => classificationKey(row) === selection.value, ) : undefined; const query = new URL(catalogueUrl, 'https://portal.invalid'); if (selected) { query.searchParams.set('association_type', selected.target_type); query.searchParams.set('association_target', selected.target_id); if (selected.purpose) query.searchParams.set('association_purpose', selected.purpose); } const effectiveCatalogueUrl = query.pathname + query.search; const key = JSON.stringify([currentId, effectiveCatalogueUrl, attempt]); const [result, setResult] = useState<{ key: string; rows: Match[]; error: boolean; } | null>(null); useEffect(() => { const controller = new AbortController(); const params = new URL(effectiveCatalogueUrl, 'https://portal.invalid') .searchParams; params.set('per_page', '7'); params.set('page', '1'); void portalRequest<{ data: Match[] }>( `/api/v1/business-opportunities?${params}`, { signal: controller.signal }, ) .then((response) => { if (controller.signal.aborted) return; if (!Array.isArray(response.data)) throw new Error('Invalid catalogue response'); const seen = new Set([currentId]); if ( response.data.some( (row) => !row || typeof row.id !== 'string' || !row.id.trim() || typeof row.slug !== 'string' || !row.slug.trim() || typeof row.title !== 'string' || !row.title.trim(), ) ) { throw new Error('Invalid catalogue record'); } const rows = response.data .filter((row) => { if ( !row || typeof row.id !== 'string' || typeof row.slug !== 'string' || typeof row.title !== 'string' || seen.has(row.id) ) return false; seen.add(row.id); return true; }) .slice(0, 6); setResult({ key, rows, error: false }); }) .catch(() => { if (!controller.signal.aborted) setResult({ key, rows: [], error: true }); }); return () => controller.abort(); }, [currentId, effectiveCatalogueUrl, key]); const current = result?.key === key ? result : null; return (

Explorar negócios semelhantes

Critérios:{' '} {[...criteria, ...(selected ? [selected.label] : [])].join( ' · ', )} . A consulta compara os dados publicados; não avalia rentabilidade nem proximidade geográfica.

{!current ? (

A consultar o catálogo…

) : current.error ? (

Não foi possível consultar os negócios semelhantes.

) : current.rows.length ? ( ) : (

Não foram encontrados outros negócios públicos com estes critérios. Isto não demonstra ausência de negócios no mercado.

)} {classifications.length > 0 && ( )} {selected && (

Fonte da classificação na ficha de origem:{' '} {selected.source_reference || 'não indicada'}. A relação documental não comprova implantação, propriedade ou capacidade.

)} Consultar o catálogo com estes critérios

São apresentados até seis resultados. Pode ajustar os filtros no catálogo. A data de publicação não indica a data dos dados de origem.

); }