import SearchState from '@/components/search-state'; import { useInterestDraft } from '@/hooks/use-interest-draft'; import { createContext, useContext, useRef, useState } from 'react'; import { router } from '@inertiajs/react'; import { PortalMenu } from '@/layouts/portal-navigation'; import { ProvinceSelect } from '@/components/investment-territory'; import { MATURITY_LEVELS } from '@/lib/investment-maturity'; import CountrySelect, { type Country } from '@/components/country-select'; import type { Dispatch, FormEvent, ReactNode, SetStateAction } from 'react'; import type { LucideIcon } from 'lucide-react'; import { usePortalQuery } from '@/hooks/use-portal-query'; import { PortalApiError, fieldErrors, interestPayload, money, portalRequest, searchUrl, toFeaturedOpportunity, toOpportunity, } from '@/lib/portal-api'; import type { Filters, FormErrors, HomeResponse, InterestFormData, Opportunity, OpportunityRecord, SearchResponse, Sector, } from '@/lib/portal-api'; import { Search, Leaf, Zap, Hotel, Truck, Waves, Banknote, ArrowRight, ArrowLeft, MapPin, CheckCircle2, } from 'lucide-react'; type View = 'home' | 'opportunities' | 'detail' | 'interest'; type OpportunityAction = (opportunity: Opportunity) => void; const SectorContext = createContext([]); const SECTOR_ICONS: Record = { agronegocio: Leaf, energia: Zap, turismo: Hotel, infraestruturas: Truck, 'economia-azul': Waves, 'mercado-financeiro': Banknote, }; function QueryStatus({ loading, error, retry, }: { loading: boolean; error?: string; retry: () => void; }) { if (loading) return (

A carregar dados...

); if (!error) return null; return (

{error}

); } /* ------------------------------------------------------------------ */ /* Componentes */ /* ------------------------------------------------------------------ */ function TopBar({ onNavigate, requestCount, }: { onNavigate: (view: View) => void; requestCount: number; }) { return ( ); } function Hero({ query, setQuery, onSearch, onNavigate, stats, }: { query: string; setQuery: (value: string) => void; onSearch: (event: FormEvent) => void; onNavigate: (view: View) => void; stats?: HomeResponse['data']['stats']; }) { return (

INVISTA EM MOÇAMBIQUE

Transforme informação em decisões {' '} e ideias em negócios reais.

Oportunidades reais de investimento em Moçambique, organizadas por sector.

Consulte projectos por província e estágio de maturidade, compreenda os requisitos legais e fiscais, e manifeste interesse directamente junto da entidade promotora.

Planear finanças
setQuery(e.target.value)} placeholder="Ex.: agronegócio, Nampula, energia..." className="w-full rounded-lg bg-white px-3 py-2.5 text-sm text-slate-900 ring-2 ring-transparent outline-none placeholder:text-slate-500 focus:ring-amber-400" />

{stats?.opportunities ?? '—'}

oportunidades

{stats?.sectors ?? '—'}

sectores

{stats?.provinces ?? '—'}

províncias
); } function SectorGrid({ onSelectSector, }: { onSelectSector: (slug: string) => void; }) { const sectors = useContext(SectorContext); return (

Sectores estratégicos

Explore as áreas prioritárias do programa de investimento nacional.

{sectors.map((sector) => { const Icon = SECTOR_ICONS[sector.slug] ?? Banknote; const count = sector.opportunitiesCount; return ( ); })}
); } function OpportunityCard({ opportunity, onView, onInterest, }: { opportunity: Opportunity; onView: OpportunityAction; onInterest: OpportunityAction; }) { return (
{opportunity.featured && ( Destaque )} {opportunity.sectorName}

{opportunity.reference}

{opportunity.title}

{' '} {opportunity.province ?? 'Localização por indicar'}

Investimento
{money(opportunity.amount, opportunity.currency)}
Maturidade
{opportunity.maturity ?? 'Por indicar'}
); } function OpportunitiesView({ filters, setFilters, onView, onInterest, }: { filters: Filters; setFilters: Dispatch>; onView: OpportunityAction; onInterest: OpportunityAction; }) { const sectors = useContext(SectorContext); const [page, setPage] = useState(1); const query = usePortalQuery(searchUrl(filters, page), 250); const results = query.data?.data.map(toOpportunity) ?? []; const total = query.data?.total ?? 0; function changeFilters(next: Filters) { setFilters(next); setPage(1); } return (

Oportunidades de investimento

{query.loading ? ( 'A pesquisar oportunidades...' ) : query.error ? ( 'Pesquisa indisponível.' ) : ( <> {total} oportunidade{total === 1 ? '' : 's'} encontrada {total === 1 ? '' : 's'}. )}

changeFilters({ ...filters, query: e.target.value }) } placeholder="Pesquisar..." className="rounded-lg border border-slate-200 px-3 py-2 text-sm" /> changeFilters({ ...filters, province }) } placeholder="Todas as províncias" className="rounded-lg border border-slate-200 px-3 py-2 text-sm" />
{!query.loading && !query.error && (results.length === 0 ? (
Nenhuma oportunidade corresponde aos filtros seleccionados.
) : (
{results.map((o) => ( ))}
))} {query.data && query.data.last_page > 1 && ( )}
); } function OpportunityDetail({ opportunity: selected, onBack, onInterest, }: { opportunity: Opportunity; onBack: () => void; onInterest: OpportunityAction; }) { const query = usePortalQuery<{ success: boolean; data: OpportunityRecord }>( '/api/v1/opportunities/' + encodeURIComponent(selected.slug), ); if (!query.data) return (
); const opportunity = toOpportunity(query.data.data); return (

{opportunity.reference}

{opportunity.title}

{' '} {opportunity.province ?? 'Localização por indicar'} ·{' '} {opportunity.sectorName}

{opportunity.description ?? opportunity.summary ?? 'Descrição por indicar'}

Investimento estimado
{money(opportunity.amount, opportunity.currency)}
Maturidade
{opportunity.maturity ?? 'Por indicar'}
Financiamento pretendido
{opportunity.financing ?? 'Por indicar'}
Impacto esperado
{opportunity.impact ?? 'Por indicar'}
A informação legal, fiscal e financeira apresentada é orientadora e deve ser confirmada junto das entidades competentes antes da tomada de decisão.
); } function InterestForm({ preselected, onSubmitted, countries, }: { preselected: Opportunity | null; onSubmitted: () => void; countries: Country[]; }) { const sectors = useContext(SectorContext); const [submitting, setSubmitting] = useState(false); const pending = useRef(false); const submission = useRef<{ body: string; key: string } | null>(null); const [submitError, setSubmitError] = useState(null); const draft = useInterestDraft('opportunity:' + (preselected?.reference ?? 'general'), { name: '', email: '', phone: '', investorType: '', country: '', declared_origin_country_code: '', sectorInterest: preselected?.sectorName ?? '', opportunityReference: preselected ? preselected.reference : '', investmentRange: '', message: '', privacyConsent: false, }); const { form, setForm } = draft; const [errors, setErrors] = useState({}); const [result, setResult] = useState<{ reference: string } | null>(null); function update( field: K, value: InterestFormData[K], ) { setForm((prev) => ({ ...prev, [field]: value })); } function validate() { const next: FormErrors = {}; if (form.name.trim().length < 3) next.name = 'Indique o nome completo.'; if (!/^\S+@\S+\.\S+$/.test(form.email)) next.email = 'Indique um email válido.'; if (!form.country.trim()) next.country = 'Indique o país.'; if (!form.investorType) next.investorType = 'Seleccione o tipo de investidor.'; if (!form.sectorInterest.trim()) next.sectorInterest = 'Indique o sector de interesse.'; if (form.message.trim().length < 20) next.message = 'A mensagem deve ter pelo menos 20 caracteres.'; if (!form.privacyConsent) next.privacyConsent = 'É necessário aceitar a política de privacidade.'; setErrors(next); return Object.keys(next).length === 0; } async function handleSubmit(event: FormEvent) { event.preventDefault(); if (pending.current || !validate()) return; pending.current = true; setSubmitting(true); setSubmitError(null); try { const body = JSON.stringify(interestPayload(form)); if (submission.current?.body !== body) { submission.current = { body, key: draft.key }; } const response = await portalRequest<{ success: boolean; data: { reference: string }; }>('/api/v1/interest-requests', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submission.current.key, }, body, }); if ( !response.success || typeof response.data?.reference !== 'string' ) throw new Error('Invalid confirmation'); draft.clear(); setResult({ reference: response.data.reference }); onSubmitted(); } catch (error: unknown) { if (error instanceof PortalApiError && error.status === 401) { draft.authenticate(); return; } if (error instanceof PortalApiError) { setErrors(fieldErrors(error)); setSubmitError(error.message); } else { setSubmitError( 'Não foi possível confirmar o envio. Verifique a ligação antes de tentar novamente.', ); } } finally { pending.current = false; setSubmitting(false); } } if (result) { return (

Manifestação de interesse registada

A sua referência é {result.reference}. A equipa do portal irá analisar o pedido e poderá solicitar informação adicional.

Acompanhar manifestações
); } return (

Manifestar interesse

Preencha os dados abaixo para que a equipa do portal possa analisar o seu interesse e entrar em contacto.

{preselected && (
Oportunidade seleccionada:{' '} {preselected.title} ( {preselected.reference})
)}
{submitError && (

{submitError}

)}
update('name', e.target.value)} /> update('email', e.target.value)} /> update('phone', e.target.value)} /> update('country', value)} required allowLegacyValue /> update('declared_origin_country_code', value) } />

Origem opcional; não é deduzida do país acima nem do IP.