import{r as e}from"./rolldown-runtime-hePW80VL.js";import{a as t,c as n,f as r,i,n as a,t as o,u as s}from"./jsx-runtime-CjMHhaqg.js";import{t as c}from"./app-Do4TnQRG.js";import{n as l}from"./investment-territory-CmmURhIW.js";import{a as u}from"./portal-api-CVJ60qfl.js";var d=e(r(),1),f=a();function p(e){let t=String(e??``),n=/^[\u0000-\u0020\uFEFF]*[=+\-@]/.test(t),r=/^-?\d+(?:\.\d+)?$/.test(t),i=n&&!r?`'${t}`:t;return/[",\r\n]/.test(i)?`"${i.replaceAll(`"`,`""`)}"`:i}var m=[{id:`purpose`,title:`Finalidade`},{id:`promoter`,title:`Perfil do promotor`},{id:`identity`,title:`Identificação e contactos`},{id:`project`,title:`Projecto ou negócio`},{id:`location`,title:`Localização`},{id:`financial`,title:`Estrutura financeira`},{id:`impact`,title:`Emprego e impacto`},{id:`tax`,title:`Operação fiscal`},{id:`opportunity`,title:`Necessidade de negócio`},{id:`documents`,title:`Documentos`},{id:`review`,title:`Revisão`}];function h(e){if(e.purpose===`simulate_only`)return m.filter(e=>[`purpose`,`tax`,`review`].includes(e.id));let t={personal:[`purpose`,`financial`,`tax`,`review`],small_business:[`purpose`,`promoter`,`project`,`financial`,`tax`,`impact`,`review`],company:m.map(e=>e.id),investor:[`purpose`,`promoter`,`identity`,`project`,`location`,`financial`,`opportunity`,`documents`,`review`]};return e.journey_type&&t[String(e.journey_type)]?m.filter(n=>t[String(e.journey_type)].includes(n.id)):m}var g=new Set(`legal_form.nuit.registration_number.representative_name.representative_capacity.address.existing_project_id.expected_start_date.project_duration_years.latitude.longitude.area_required.area_unit.special_zone_id.infrastructure_needs.secured_amount.sought_amount.annual_revenue.annual_operating_costs.expected_profit.financing_term_months.funds_origin_countries.direct_jobs.indirect_jobs.national_jobs.foreign_jobs.skills_needed.local_content_percentage.exports_value.import_substitution_value.environmental_category.community_benefits.sales_taxable.sales_exempt.sales_zero_rate.exports.deductible_costs.non_deductible_costs.carried_losses.payroll.outbound_payments.imports.claimed_benefits.required_documents`.split(`.`)),_={journey_type:[`personal`,`small_business`,`company`,`investor`],detail_level:[`simple`,`advanced`],purpose:[`simulate_only`,`own_investment`,`seek_investor`,`seek_partner`,`present_opportunity`,`request_facilitation`],manifestation_type:[`investment`,`business`],person_type:[`singular`,`collective`,`sole_trader`,`consortium`],investor_origin:[`national`,`foreign`,`mixed`],entity_stage:[`existing`,`being_formed`],preferred_language:[`pt-MZ`,`en`],preferred_channel:[`portal`,`email`,`phone`],project_type:[`new`,`expansion`,`acquisition`,`partnership`,`concession`,`supplier`,`buyer`,`other`],maturity_stage:[`idea`,`concept`,`pre_feasibility`,`feasibility`,`financing`,`implementation`,`operation`],land_status:[`owned`,`duat`,`leased`,`requested`,`unknown`],environmental_category:[`A`,`B`,`C`,`por_determinar`],offer_or_demand:[`offer`,`demand`,`both`],opportunity_type:[`capital`,`partner`,`buyer`,`supplier`,`land`,`technology`,`licence`,`services`,`other`],confidentiality:[`public`,`registered_users`,`restricted`,`confidential`],preferred_publication:[`yes`,`no`],residency_status:[`resident`,`non_resident`],tax_calculation:[`yes`,`no`],fiscal_period:Array.from({length:new Date().getFullYear()-1999+2},(e,t)=>String(2e3+t)),fiscal_periodicity:[`monthly`,`quarterly`,`annual`,`one_off`,`unknown`],irps_salary_view:[`monthly_net_estimate`,`monthly_withholding`,`annual_assessment`],fiscal_component:[`irpc`,`iva`,`ispc`,`irps`,`inss`,`withholding`,`customs_ice`],fiscal_income_category:[`employment`,`rental`,`digital`,`capital_gain`,`business`,`other`,`unknown`],fiscal_residency_assessment:[`self_reported_resident`,`self_reported_non_resident`,`unknown`],fiscal_operation:[`domestic`,`non_resident`,`import`,`export`,`refund`,`other`,`unknown`],fiscal_documentation:[`documented`,`partly_documented`,`not_documented`,`unknown`],fiscal_refund_state:[`estimate_only`,`request_filed`,`recognized`,`received`,`unknown`],document_types:[`identity_document`,`company_registration`,`nuit_certificate`,`company_profile`,`business_plan`,`feasibility_study`,`proof_of_funds`,`special_zone_certificate`,`licence`,`site_map`],area_unit:[`m2`,`ha`,`km2`]};function v(e,t,n){return!Number.isSafeInteger(n)||n<=0?-1:!Number.isSafeInteger(e)||e<0?t>0?0:n-1:Math.max(0,Math.min(n-1,e+t))}var y={purpose:[{key:`journey_type`,label:`O que pretende calcular ou planear? Escolha o percurso`,options:`journey_type`,required:!0},{key:`detail_level`,label:`Nível de detalhe`,options:`detail_level`,required:!0},{key:`purpose`,label:`O que pretende fazer?`,options:`purpose`,required:!0},{key:`manifestation_type`,label:`Tipo de manifestação`,options:`manifestation_type`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`preferred_language`,label:`Idioma preferido`,options:`preferred_language`,required:!0}],promoter:[{key:`person_type`,label:`Tipo de pessoa`,options:`person_type`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`investor_origin`,label:`Origem do investidor`,options:`investor_origin`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`entity_stage`,label:`Situação da entidade`,options:`entity_stage`,required:!0,showWhen:e=>e.purpose!==`simulate_only`&&[`collective`,`consortium`].includes(String(e.person_type))},{key:`legal_form`,label:`Forma jurídica (conforme o registo)`,required:!0,showWhen:e=>e.purpose!==`simulate_only`&&e.entity_stage===`existing`},{key:`nuit`,label:`NUIT`,showWhen:e=>e.purpose!==`simulate_only`}],identity:[{key:`legal_name`,label:`Nome / denominação`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`commercial_name`,label:`Nome comercial`,showWhen:e=>e.purpose!==`simulate_only`},{key:`registration_number`,label:`Número de registo`,required:!0,showWhen:e=>e.entity_stage===`existing`&&e.purpose!==`simulate_only`},{key:`representative_name`,label:`Nome do representante`,required:!0,showWhen:e=>[`collective`,`consortium`].includes(String(e.person_type))&&e.purpose!==`simulate_only`},{key:`email`,label:`Correio electrónico`,type:`email`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`phone`,label:`Telefone`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`address`,label:`Endereço`,type:`textarea`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`preferred_channel`,label:`Canal de contacto`,options:`preferred_channel`,required:!0,showWhen:e=>e.purpose!==`simulate_only`}],project:[{key:`project_title`,label:`Título do projecto`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`project_summary`,label:`Resumo executivo`,type:`textarea`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`project_type`,label:`Tipo de projecto`,options:`project_type`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`project_type_other`,label:`Especifique o tipo de projecto`,required:!0,showWhen:e=>e.purpose!==`simulate_only`&&e.project_type===`other`},{key:`sector_id`,label:`Sector de actividade`,options:`sector`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`activity_id`,label:`Actividade económica`,options:`activity`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`products_services`,label:`Produtos e serviços`,type:`textarea`,showWhen:e=>e.purpose!==`simulate_only`},{key:`maturity_stage`,label:`Fase de maturidade`,options:`maturity_stage`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`expected_start_date`,label:`Data prevista de início`,type:`date`,showWhen:e=>e.purpose!==`simulate_only`},{key:`project_duration_years`,label:`Duração prevista (anos)`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`existing_project_id`,label:`Referência do projecto existente`,showWhen:e=>e.project_type===`expansion`}],location:[{key:`province_id`,label:`Província`,options:`province`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`district_id`,label:`Distrito`,options:`district`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`admin_post_id`,label:`Posto administrativo`,options:`admin_post`,showWhen:e=>e.purpose!==`simulate_only`},{key:`locality_id`,label:`Localidade`,options:`locality`,showWhen:e=>e.purpose!==`simulate_only`},{key:`site_known`,label:`Local conhecido?`,options:`yes_no`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`land_status`,label:`Situação do terreno`,options:`land_status`,showWhen:e=>e.purpose!==`simulate_only`},{key:`area_required`,label:`Área necessária`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`area_unit`,label:`Unidade da área`,options:`area_unit`,showWhen:e=>e.purpose!==`simulate_only`},{key:`latitude`,label:`Latitude`,type:`number`,showWhen:e=>e.site_known===`yes`},{key:`longitude`,label:`Longitude`,type:`number`,showWhen:e=>e.site_known===`yes`},{key:`special_zone_id`,label:`Zona especial ZEE/ZFI`,showWhen:e=>e.purpose!==`simulate_only`},{key:`infrastructure_needs`,label:`Necessidades de infra-estrutura`,options:`infrastructure`,multiple:!0,showWhen:e=>e.purpose!==`simulate_only`}],financial:[{key:`currency`,label:`Moeda`,options:`currency`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`total_investment`,label:`Investimento total`,type:`number`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`own_capital`,label:`Capital próprio`,type:`number`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`domestic_debt`,label:`Financiamento interno`,type:`number`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`foreign_debt`,label:`Financiamento externo`,type:`number`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`grants`,label:`Subvenções`,type:`number`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`secured_amount`,label:`Montante mobilizado`,type:`number`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`sought_amount`,label:`Montante procurado`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`annual_revenue`,label:`Receitas anuais estimadas`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`annual_operating_costs`,label:`Custos operacionais anuais`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`expected_profit`,label:`Lucro esperado`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`financing_term_months`,label:`Prazo de financiamento (meses)`,type:`number`,showWhen:e=>Number(e.domestic_debt)+Number(e.foreign_debt)>0},{key:`funds_origin_countries`,label:`Países de origem dos fundos`,options:`country`,multiple:!0,showWhen:e=>Number(e.foreign_debt)>0}],impact:[{key:`direct_jobs`,label:`Empregos directos`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`indirect_jobs`,label:`Empregos indirectos`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`national_jobs`,label:`Empregos nacionais`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`foreign_jobs`,label:`Empregos estrangeiros`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`exports_value`,label:`Exportações estimadas`,type:`number`},{key:`import_substitution_value`,label:`Substituição de importações estimada`,type:`number`},{key:`skills_needed`,label:`Qualificações/competências necessárias`,type:`textarea`},{key:`local_content_percentage`,label:`Conteúdo local (%)`,type:`number`},{key:`environmental_category`,label:`Categoria ambiental`,options:`environmental_category`},{key:`community_benefits`,label:`Benefícios comunitários`,type:`textarea`}],tax:[{key:`fiscal_period`,label:`Ano do período fiscal a simular`,options:`fiscal_period`,required:!0},{key:`fiscal_periodicity`,label:`Periodicidade/período de referência`,options:`fiscal_periodicity`,required:!0},{key:`fiscal_component`,label:`Componente que pretende explorar`,options:`fiscal_component`,required:!0},{key:`irps_salary_view`,label:`Que resultado de remuneração pretende explorar?`,options:`irps_salary_view`,required:!0,showWhen:e=>e.fiscal_component===`irps`&&e.fiscal_income_category===`employment`},{key:`fiscal_income_category`,label:`Categoria de rendimento`,options:`fiscal_income_category`,required:!0,showWhen:e=>[`irps`,`irpc`,`withholding`].includes(String(e.fiscal_component))},{key:`fiscal_residency_assessment`,label:`Residência fiscal indicada pelo utilizador`,options:`fiscal_residency_assessment`,required:!0,showWhen:e=>[`irps`,`irpc`,`withholding`,`iva`].includes(String(e.fiscal_component))},{key:`fiscal_residency_country`,label:`País que indica como residência fiscal (opcional; não é verificação)`,options:`country`,showWhen:e=>[`irps`,`irpc`,`withholding`,`iva`].includes(String(e.fiscal_component))},{key:`fiscal_operation`,label:`Tipo de operação`,options:`fiscal_operation`,required:!0,showWhen:e=>[`iva`,`irpc`,`withholding`,`customs_ice`].includes(String(e.fiscal_component))},{key:`fiscal_activity`,label:`Actividade económica (descrição exploratória)`,required:!0,showWhen:e=>[`ispc`,`irpc`].includes(String(e.fiscal_component))},{key:`fiscal_establishments`,label:`Número de estabelecimentos envolvidos`,type:`number`,required:!0,showWhen:e=>[`ispc`,`iva`,`irpc`].includes(String(e.fiscal_component))},{key:`fiscal_documentation`,label:`Estado da documentação de despesas`,options:`fiscal_documentation`,required:!0,showWhen:e=>[`iva`,`irpc`,`irps`].includes(String(e.fiscal_component))},{key:`fiscal_customs_code`,label:`Código pautal (necessário para classificação aduaneira)`,required:!0,showWhen:e=>e.fiscal_component===`customs_ice`},{key:`fiscal_vat_refund_state`,label:`Estado do crédito/pedido de reembolso de IVA`,options:`fiscal_refund_state`,required:!0,showWhen:e=>e.fiscal_component===`iva`&&e.fiscal_operation===`refund`},{key:`tax_calculation`,label:`Pretende calcular um cenário aritmético?`,options:`tax_calculation`,required:!0},{key:`base`,label:`Base para o cenário`,type:`number`,required:!0,showWhen:e=>e.tax_calculation===`yes`},{key:`rate`,label:`Taxa hipotética do cenário (%)`,type:`number`,required:!0,showWhen:e=>e.tax_calculation===`yes`},{key:`reduction`,label:`Redução hipotética (%)`,type:`number`,required:!0,showWhen:e=>e.tax_calculation===`yes`},{key:`sales_taxable`,label:`Vendas tributadas`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`sales_exempt`,label:`Vendas isentas`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`sales_zero_rate`,label:`Vendas à taxa zero`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`exports`,label:`Exportações`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`deductible_costs`,label:`Custos dedutíveis`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`non_deductible_costs`,label:`Custos não dedutíveis`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`carried_losses`,label:`Prejuízos transitados`,type:`number`,showWhen:e=>e.purpose!==`simulate_only`},{key:`payroll`,label:`Dados de remunerações (estrutura prevista)`,type:`textarea`,showWhen:e=>e.purpose!==`simulate_only`},{key:`outbound_payments`,label:`Pagamentos ao exterior (estrutura prevista)`,type:`textarea`,showWhen:e=>e.purpose!==`simulate_only`},{key:`imports`,label:`Importações (estrutura prevista)`,type:`textarea`,showWhen:e=>e.purpose!==`simulate_only`},{key:`claimed_benefits`,label:`Benefícios alegados para validação`,type:`textarea`,showWhen:e=>e.purpose!==`simulate_only`},{key:`reference_date`,label:`Data de referência`,type:`date`,required:!0,showWhen:e=>e.purpose!==`simulate_only`}],opportunity:[{key:`offer_or_demand`,label:`Oferta ou procura`,options:`offer_or_demand`,showWhen:e=>e.manifestation_type===`business`},{key:`opportunity_type`,label:`Necessidade de negócio`,options:`opportunity_type`,showWhen:e=>e.manifestation_type===`business`},{key:`opportunity_type_other`,label:`Especifique a necessidade`,required:!0,showWhen:e=>e.manifestation_type===`business`&&e.opportunity_type===`other`},{key:`opportunity_description`,label:`Descrição da necessidade`,type:`textarea`,showWhen:e=>e.manifestation_type===`business`},{key:`opportunity_value`,label:`Valor da oportunidade`,type:`number`,showWhen:e=>e.manifestation_type===`business`},{key:`opportunity_currency`,label:`Moeda da oportunidade`,options:`currency`,showWhen:e=>e.manifestation_type===`business`&&!!e.opportunity_value},{key:`opportunity_conditions`,label:`Condições da oportunidade`,type:`textarea`,showWhen:e=>e.manifestation_type===`business`},{key:`opportunity_deadline`,label:`Prazo da oportunidade`,type:`date`,showWhen:e=>e.manifestation_type===`business`},{key:`confidentiality`,label:`Confidencialidade`,options:`confidentiality`,showWhen:e=>e.manifestation_type===`business`},{key:`publish_requested`,label:`Pretende pedir publicação?`,options:`preferred_publication`,showWhen:e=>e.manifestation_type===`business`}],documents:[{key:`required_documents`,label:`Documentos aplicáveis a preparar`,options:`document_types`,multiple:!0,showWhen:e=>e.purpose!==`simulate_only`}],review:[{key:`terms_accepted`,label:`Aceito os termos de utilização`,options:`yes_no`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`truth_declaration`,label:`Declaro que as informações são verdadeiras`,options:`yes_no`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`reuse_simulation`,label:`Autorizo reutilizar os dados da simulação`,options:`yes_no`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`contact_authorisation`,label:`Autorizo contacto para acompanhamento`,options:`yes_no`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`publication_authorisation`,label:`Autorizo a publicação solicitada`,options:`yes_no`,required:!0,showWhen:e=>e.publish_requested===`yes`},{key:`public_fields_confirmation`,label:`Confirmo os campos propostos para publicação`,options:`yes_no`,required:!0,showWhen:e=>e.publish_requested===`yes`},{key:`validation_acknowledged`,label:`Confirmo que li os avisos de validação`,options:`yes_no`,required:!0,showWhen:e=>e.purpose!==`simulate_only`},{key:`final_declaration_name`,label:`Nome para a declaração final`,required:!0,showWhen:e=>e.purpose!==`simulate_only`}]};_.yes_no=[`yes`,`no`],_.infrastructure=[`energia`,`água`,`estrada`,`porto`,`ferrovia`,`telecomunicações`,`armazenamento`];function b(e,t,n){let r={...e,[t]:n},i=t===`foreign_debt`&&Number(n)>0&&Number(e[t]??0)>0?[]:{province_id:[`district_id`,`admin_post_id`,`locality_id`],district_id:[`admin_post_id`,`locality_id`],admin_post_id:[`locality_id`],sector_id:[`activity_id`],site_known:[`latitude`,`longitude`],project_type:[`project_type_other`],opportunity_type:[`opportunity_type_other`],foreign_debt:[`funds_origin_countries`],tax_calculation:[`base`,`rate`,`reduction`],fiscal_component:[`fiscal_income_category`,`irps_salary_view`,`fiscal_residency_assessment`,`fiscal_residency_country`,`fiscal_operation`,`fiscal_activity`,`fiscal_establishments`,`fiscal_documentation`,`fiscal_customs_code`,`fiscal_vat_refund_state`],fiscal_operation:[`fiscal_vat_refund_state`],fiscal_income_category:[`irps_salary_view`]}[t]??[];for(let e of i)delete r[e],delete r[`${e}_label`];if(t===`manifestation_type`&&n!==`business`)for(let e of y.opportunity)delete r[e.key],delete r[`${e.key}_label`];return r}var x=new Set([`person_type`,`investor_origin`,`tax_residency_country`,`fiscal_residency_country`,`entity_stage`,`legal_form`,`nuit`,`investor_profile_id`,`profile_confirmation`,`legal_name`,`commercial_name`,`registration_number`,`representative_name`,`representative_capacity`,`email`,`phone`,`address`,`contact_country`,`contact_province`,`contact_district`,`preferred_channel`]);function S(e){return Object.fromEntries(Object.entries(e).filter(([e])=>{let t=e.replace(/_label$/,``);return!x.has(t)}))}function C(e,t=!0){let n={},r={},i={},a={};for(let[o,s]of Object.entries(e))if(!(!t&&x.has(o.replace(/_label$/,``)))){if(o.endsWith(`_label`)){let e=x.has(o.slice(0,-6))?i:a;e[o.slice(0,-6)]=s;continue}(x.has(o)?n:r)[o]=s}return Object.keys(i).length&&(n.selection_labels=i),Object.keys(a).length&&(r.selection_labels=a),{personal_snapshot:n,economic_snapshot:r}}function w(e,t){let n={...e,...t},r={...e.selection_labels,...t.selection_labels};if(delete n.selection_labels,delete n.personal_snapshot,delete n.simulation_sources,r&&typeof r==`object`)for(let[e,t]of Object.entries(r))(typeof t==`string`||Array.isArray(t)&&t.every(e=>typeof e==`string`))&&(n[`${e}_label`]=Array.isArray(n[e])?t:Array.isArray(t)?t[0]:t);return n}function T(e){let t=e=>Array.isArray(e)?e.map(t):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)])):e;return JSON.stringify(t(C(e)))}function E(e,t){let n={};for(let r of y[t]??[]){if(r.showWhen&&!r.showWhen(e))continue;let t=e[r.key],i=t===void 0||t===``||Array.isArray(t)&&t.length===0;if(r.required&&i&&(n[r.key]=`Este campo é obrigatório.`),r.type===`number`&&t!==void 0&&t!==``){let e=Number(t);(!Number.isFinite(e)||e<0)&&(n[r.key]=`Introduza um número igual ou superior a zero.`)}[`rate`,`reduction`,`local_content_percentage`].includes(r.key)&&t!==void 0&&t!==``&&Number(t)>100&&(n[r.key]=`O valor não pode exceder 100.`),r.key===`email`&&typeof t==`string`&&t&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)&&(n[r.key]=`Introduza um endereço de correio electrónico válido.`)}if(t===`financial`&&[`own_capital`,`domestic_debt`,`foreign_debt`,`grants`,`total_investment`].every(t=>e[t]!==void 0&&e[t]!==``)){let t=[`own_capital`,`domestic_debt`,`foreign_debt`,`grants`].reduce((t,n)=>t+Number(e[n]),0);Math.abs(t-Number(e.total_investment))>.01&&(n.total_investment=`A soma do capital, dívida e subvenções deve corresponder ao investimento total.`)}return n}function D(e){if(!e||typeof e!=`object`||Array.isArray(e))return{integrity:`invalid`,value:null,context:null,explanation:null};let t=e,n=t.indicative_total;if(typeof n!=`string`||!/^(?:\d+)(?:\.\d+)?$/.test(n))return{integrity:`invalid`,value:null,context:null,explanation:null};if(t.contract_version===void 0)return{integrity:`legacy`,value:n,context:null,explanation:null};if(t.contract_version!==1||t.legal_interpretation!==!1)return{integrity:`invalid`,value:null,context:null,explanation:null};let r=t.context,i=t.result;if(!r||typeof r!=`object`||Array.isArray(r)||!i||typeof i!=`object`||Array.isArray(i))return{integrity:`invalid`,value:null,context:null,explanation:null};let a=r,o=i;return o.status!==`calculated`||o.value!==n||o.unit!==null||typeof o.explanation!=`string`||!o.explanation.trim()||!Array.isArray(o.missing_inputs)||o.missing_inputs.length!==0||!Array.isArray(o.source_ids)||o.source_ids.length!==0||typeof a.reference_date!=`string`||!/^\d{4}-\d{2}-\d{2}$/.test(a.reference_date)||typeof a.scenario_id!=`string`||!Number.isSafeInteger(a.scenario_version)||Number(a.scenario_version)<1||typeof a.engine_version!=`string`||a.currency!==null||a.currency_fraction_digits!==null||a.ruleset_version!==null?{integrity:`invalid`,value:null,context:null,explanation:null}:{integrity:`versioned`,value:n,context:a,explanation:o.explanation}}function O(e){if(Array.isArray(e))return`[${e.map(O).join(`,`)}]`;if(e&&typeof e==`object`){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${O(t[e])}`).join(`,`)}}`}return JSON.stringify(e)??`null`}function k(e){if(e?.status!==`completed`||!e.result_snapshot||typeof e.result_snapshot!=`object`||Array.isArray(e.result_snapshot))return null;let t=e.result_snapshot;if(t.contract_version!==1)return null;let n=t.context;if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n.scenario_version;if(!Number.isSafeInteger(r)||Number(r)<1)return null;let i=Array.isArray(e.reports)?e.reports.filter(e=>e&&typeof e==`object`&&!Array.isArray(e)):[];i.sort((e,t)=>{let n=typeof e.created_at==`string`?e.created_at:``;return(typeof t.created_at==`string`?t.created_at:``).localeCompare(n)});let a=i.find(e=>e.status===`ready`&&e.version_no===r&&typeof e.id==`string`&&e.report_snapshot&&typeof e.report_snapshot==`object`&&!Array.isArray(e.report_snapshot)&&O(e.report_snapshot)===O(t)&&typeof e.report_sha256==`string`&&/^[a-f0-9]{64}$/i.test(e.report_sha256));return a?{id:a.id,version_no:r,report_sha256:a.report_sha256,created_at:typeof a.created_at==`string`?a.created_at:null}:null}function A(e,t=new Date().toISOString()){if(e.status!==`completed`||!e.result_snapshot||typeof e.result_snapshot!=`object`)throw Error(`Só é possível exportar uma simulação concluída com relatório disponível.`);let n=e.result_snapshot,r=(e,t)=>{if(typeof e!=`string`||!/^(?:\d+)(?:\.\d+)?$/.test(e))throw Error(`O campo ${t} não está disponível num formato seguro.`);return e};if(n.contract_version!==void 0&&n.contract_version!==1)throw Error(`A versão do contrato do resultado não é suportada.`);let i=[];if(n.contract_version===1){let e=n.context,t=n.result;if(!e||typeof e!=`object`||!t||typeof t!=`object`)throw Error(`O snapshot versionado do resultado está incompleto.`);let a=e,o=t,s=r(o.value,`resultado versionado`);if(o.status!==`calculated`||s!==r(n.indicative_total,`resultado`)||n.legal_interpretation!==!1||typeof a.reference_date!=`string`||!/^\d{4}-\d{2}-\d{2}$/.test(a.reference_date)||typeof a.scenario_id!=`string`||!Number.isSafeInteger(a.scenario_version)||Number(a.scenario_version)<1||typeof a.engine_version!=`string`||a.currency!==null||a.ruleset_version!==null)throw Error(`O envelope do resultado não reconcilia com o snapshot aritmético.`);i=[[`Versão do contrato`,`1`],[`Data de referência`,a.reference_date],[`ID do cenário`,a.scenario_id],[`Versão do motor`,a.engine_version],[`Estado do resultado`,o.status],[`Explicação do resultado`,o.explanation]]}let a=[...Array.isArray(e.reports)?e.reports.filter(e=>e&&typeof e==`object`&&!Array.isArray(e)):[]].filter(e=>e.status===`ready`).sort((e,t)=>{let n=typeof e.created_at==`string`?e.created_at:``;return(typeof t.created_at==`string`?t.created_at:``).localeCompare(n)})[0];if(n.contract_version===1){let t=k(e);if(!t)throw Error(`Relatorio imutavel nao corresponde a versao atual do resultado.`);a=t}let o=Number.isSafeInteger(e.version_no)?String(e.version_no):`não identificada`;return`\uFEFF${[[`Relatório`,`Simulação aritmética indicativa`],...i,[`Data de exportação`,t],[`Data do resultado`,typeof e.updated_at==`string`?e.updated_at:`não disponível`],[`Período`,`cenário aritmético pontual; sem período fiscal atribuído`],[`ID da execução`,typeof e.id==`string`?e.id:`não disponível`],[`Versão da execução`,o],[`ID do relatório`,typeof a?.id==`string`?a.id:`não disponível`],[`Versão do relatório/cenário`,Number.isSafeInteger(a?.version_no)?String(a?.version_no):`não identificada`],[`Hash SHA-256 do relatório`,typeof a?.report_sha256==`string`&&/^[a-f0-9]{64}$/i.test(a.report_sha256)?a.report_sha256:`não disponível`],[`Fórmula`,typeof n.formula_version==`string`?n.formula_version:`não identificada`],[`Versão de regras`,`não aplicável; motor aritmético genérico`],[`Expressão aplicada`,`base × taxa_percentual ÷ 100 × (1 − redução_percentual ÷ 100)`],[`Base introduzida`,r(n.base,`base`)],[`Taxa percentual introduzida`,r(n.rate_percent,`taxa`)],[`Redução hipotética percentual`,r(n.reduction_percent,`redução`)],[`Resultado aritmético indicativo`,r(n.indicative_total,`resultado`)],[`Moeda`,typeof n.currency==`string`?n.currency:`não fornecida`],[`Fontes legais`,`nenhuma associada; parâmetros fornecidos pelo utilizador`],[`IDs de fontes`,`nenhum`],[`Arredondamento fiscal`,`não aplicado; sem regra de arredondamento fiscal`],[`Interpretação legal`,n.legal_interpretation===!1?`não`:`não confirmada`],[`Limitações`,`Aritmética indicativa; sem validação fiscal, fundamento legal, arredondamento fiscal ou aconselhamento.`]].map(e=>e.map(p).join(`,`)).join(`\r
`)}`}function j(e){return JSON.stringify({version:1,data:e})}function M(e){if(!e||e.length>3e4)return null;try{let t=JSON.parse(e);if(t.version!==1||!t.data||typeof t.data!=`object`)return null;let n=t.data,r=(e,t=80)=>typeof e==`string`&&e.length<=t,i=n.loan,a=n.breakEven,o=n.funding,s=e=>Array.isArray(e)&&e.length<=50&&e.every(e=>e&&typeof e==`object`&&r(e.label,120)&&r(e.amount,80));return![`Mensal`,`Trimestral`,`Anual`,`Outro período`].includes(String(n.budgetPeriod))||!i||!a||!o||![`principal`,`rate`,`months`,`periodMonths`,`gracePeriods`,`upfrontFee`,`recurringFee`].every(e=>r(i[e]))||![`nominal`,`effective`].includes(String(i.rateType))||![`fixed`,`price`,`variable`].every(e=>r(a[e]))||![`total`,`secured`].every(e=>r(o[e]))||!s(n.incomes)||!s(n.expenses)?null:n}catch{return null}}function N(e,t,n){let r=/^(\d+)(?:\.(\d+))?$/.exec(e.trim());if(!r||(r[2]?.length??0)>t)throw Error(`${n}: introduza um valor decimal não negativo com até ${t} casas.`);let i=(r[2]??``).padEnd(t,`0`);return BigInt(r[1])*10n**BigInt(t)+BigInt(i||`0`)}function P(e){let t=e<0n?-e:e,n=`${t/100n}.${String(t%100n).padStart(2,`0`)}`;return e<0n?`-${n}`:n}function F(e){let t=I(e*100000000n,L);return`${t/1000000n}.${String(t%1000000n).padStart(6,`0`)}`}function I(e,t){return(e+t/2n)/t}var L=1000000000000n,R=(e,t)=>I(e,t),z=(e,t)=>R(e*t,L);function ee(e,t){let n=L,r=e,i=t;for(;i>0;)i%2==1&&(n=z(n,r)),i=Math.floor(i/2),i>0&&(r=z(r,r));return n}function te(e,t){let n=L,r=e;for(;n<r;){let i=(n+r+1n)/2n;ee(i,t)<=e?n=i:r=i-1n}return n}function ne(e,t,n){let r=N(e,2,`Custos fixos`),i=N(t,2,`Preço unitário`),a=N(n,2,`Custo variável`);if(i<=a)throw Error(`O preço unitário deve ser superior ao custo variável.`);let o=(r+(i-a)-1n)/(i-a),s=o*i;return{contributionPerUnit:P(i-a),breakEvenUnits:o.toString(),breakEvenRevenue:P(s),status:`estimated`}}function re(e,t){let n=N(e,2,`Investimento total`),r=N(t,2,`Financiamento mobilizado`);return{gap:P(n-r),reconciles:n===r,status:`estimated`}}function ie(e){let t=N(e.principal,2,`Capital`),n=N(e.annualRatePercent,6,`Taxa anual`),r=N(e.upfrontFee??`0`,2,`Comissão inicial`),i=N(e.recurringFee??`0`,2,`Comissão periódica`);if(!Number.isSafeInteger(e.periodMonths)||![1,2,3,4,6,12].includes(e.periodMonths))throw Error(`Periodicidade: use 1, 2, 3, 4, 6 ou 12 meses.`);if(!Number.isSafeInteger(e.termMonths)||e.termMonths<e.periodMonths||e.termMonths>600||e.termMonths%e.periodMonths!==0)throw Error(`O prazo deve ser múltiplo da periodicidade e não exceder 600 meses.`);let a=e.termMonths/e.periodMonths,o=e.gracePeriods??0;if(!Number.isSafeInteger(o)||o<0||o>=a)throw Error(`A carência deve ser inferior ao número total de prestações.`);if(r>t)throw Error(`A comissão inicial não pode exceder o capital.`);let s=R(n*L,100000000n),c;if(e.rateType===`nominal`)c=R(s,BigInt(12/e.periodMonths));else{let t=12/e.periodMonths;c=te(L+s,t)-L}let l=a-o,u=ee(L+c,l),d=c===0n?R(t,BigInt(l)):R(t*c*u,L*(u-L)),f=t,p=[];for(let e=1;e<=a;e++){let t=f,n=R(f*c,L),r=e<=o,s=r?0n:e===a?f:d-n;if(s<0n)throw Error(`As condições não amortizam o capital; reveja a taxa e o prazo.`);f-=s;let l=s+n;p.push({period:e,openingBalance:P(t),interest:P(n),principal:P(s),fee:P(i),totalPayment:P(l+i),closingBalance:P(f),type:r?`interest_only`:`amortization`})}let m=p.reduce((e,t)=>e+N(t.interest,2,`Juro`),0n),h=r+i*BigInt(a);return{periodicRatePercent:F(c),netDisbursed:P(t-r),upfrontFee:P(r),totalInterest:P(m),totalFees:P(h),totalPaid:P(t+m+h),schedule:p,status:`estimated`}}function ae(e,t){let n=e.reduce((e,t)=>e+N(t,2,`Receita`),0n),r=t.reduce((e,t)=>e+N(t,2,`Despesa`),0n);return{incomeTotal:P(n),expenseTotal:P(r),operatingBalance:P(n-r),status:`estimated`}}function oe(e){let t=ie(e.loan),n=ne(e.breakEven.fixedCosts,e.breakEven.unitPrice,e.breakEven.variableCostPerUnit),r=re(e.funding.totalInvestment,e.funding.securedFunding),i=ae(e.incomes.map(e=>e.amount),e.expenses.map(e=>e.amount));return`\uFEFF${[[`Relatório`,`Ferramentas de planeamento financeiro (indicativo)`],[`Versão do modelo`,`financial-tools-v1`],[`Data de exportação`,e.generatedAt??new Date().toISOString()],[`Moeda`,e.currency],[`Estado`,`Estimativa com pressupostos introduzidos pelo utilizador`],[`Fonte dos pressupostos`,`Valores introduzidos pelo utilizador`],[`Período do orçamento e dos custos fixos`,e.budgetPeriod],[`Fórmula da prestação`,`Saldo decrescente; taxa nominal divide pelos períodos ou taxa efectiva convertida; última prestação ajusta resíduos`],[`Fórmula do ponto de equilíbrio`,`custos fixos / (preço unitário - custo variável unitário), unidades arredondadas para cima`],[`Fórmula do financiamento`,`investimento total - financiamento mobilizado; saldo negativo indica excedente declarado`],[`Fórmula do orçamento`,`soma das receitas - soma das despesas`],[`Limitações`,`Não é proposta bancária nem aconselhamento; não inclui impostos; taxas e condições são pressupostos do utilizador.`],[],[`Pressupostos do empréstimo`],[`Capital`,e.loan.principal],[`Taxa anual (%)`,e.loan.annualRatePercent],[`Tipo de taxa`,e.loan.rateType],[`Prazo (meses)`,e.loan.termMonths],[`Periodicidade (meses)`,e.loan.periodMonths],[`Carência (períodos)`,e.loan.gracePeriods??0],[`Comissão inicial`,e.loan.upfrontFee??`0`],[`Comissão periódica`,e.loan.recurringFee??`0`],[`Taxa por período (%)`,t.periodicRatePercent],[`Desembolso líquido`,t.netDisbursed],[`Juros totais`,t.totalInterest],[`Comissões totais`,t.totalFees],[`Total pago`,t.totalPaid],[],[`Pressupostos do ponto de equilíbrio`],[`Custos fixos do período`,e.breakEven.fixedCosts],[`Preço unitário`,e.breakEven.unitPrice],[`Custo variável unitário`,e.breakEven.variableCostPerUnit],[`Margem de contribuição unitária`,n.contributionPerUnit],[`Unidades de equilíbrio`,n.breakEvenUnits],[`Receita de equilíbrio`,n.breakEvenRevenue],[],[`Necessidade de financiamento`],[`Investimento total`,e.funding.totalInvestment],[`Financiamento mobilizado`,e.funding.securedFunding],[`Diferença por financiar`,r.gap],[],[`Orçamento`,e.currency],[`Categoria`,`Descrição`,`Montante`],...e.incomes.map(e=>[`Receita`,e.label,e.amount]),...e.expenses.map(e=>[`Despesa`,e.label,e.amount]),[`Total de receitas`,``,i.incomeTotal],[`Total de despesas`,``,i.expenseTotal],[`Saldo operacional`,``,i.operatingBalance],[],[`Plano de reembolso`,e.currency],[`Período`,`Saldo inicial`,`Juros`,`Capital`,`Comissão`,`Prestação total`,`Saldo final`],...t.schedule.map(e=>[e.period,e.openingBalance,e.interest,e.principal,e.fee,e.totalPayment,e.closingBalance])].map(e=>e.map(p).join(`,`)).join(`\r
`)}`}var se=[`IRPS`,`INSS`,`IVA`,`IRPC`,`ISPC`,`RETENCOES`];function ce(e,t){return{component:e,referenceDate:t,status:`indeterminate`,value:null,unit:null,explanation:`A componente ${e} não tem regra oficial aprovada e vigente associada neste simulador.`,missingInputs:[`approved_rule`,`effective_parameters`,`applicable_classification`],sourceIds:[]}}var B=Intl;function le(e){try{let t=new Intl.NumberFormat(`en`,{style:`currency`,currency:e}).resolvedOptions().maximumFractionDigits;return t!==void 0&&Number.isInteger(t)?t:null}catch{return null}}var ue=[...new Set([`MZN`,`USD`,`EUR`,`ZAR`,...B.supportedValuesOf?.(`currency`)??[]])].filter(e=>le(e)===2).sort(),de=e=>ue.includes(e),V=o();function H({label:e,value:t,onChange:n,step:r=`0.01`}){return(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[e,(0,V.jsx)(`input`,{type:`number`,min:`0`,step:r,value:t,onChange:e=>n(e.target.value),className:`mt-1 w-full rounded border p-2`})]})}function fe(e){let t=(0,f.c)(260),{currency:n,snapshot:r,onSnapshotChange:i,onCurrencyChange:a}=e,o;t[0]===r?o=t[1]:(o=M(r),t[0]=r,t[1]=o);let s=o,c;t[2]===s?.loan?c=t[3]:(c=s?.loan??{principal:`100000`,rate:`18`,months:`24`,rateType:`nominal`,periodMonths:`1`,gracePeriods:`0`,upfrontFee:`0`,recurringFee:`0`},t[2]=s?.loan,t[3]=c);let[l,u]=(0,d.useState)(c),p;t[4]===s?.breakEven?p=t[5]:(p=s?.breakEven??{fixed:`50000`,price:`1000`,variable:`600`},t[4]=s?.breakEven,t[5]=p);let[m,h]=(0,d.useState)(p),g;t[6]===s?.funding?g=t[7]:(g=s?.funding??{total:`1000000`,secured:`250000`},t[6]=s?.funding,t[7]=g);let[_,v]=(0,d.useState)(g),y;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(y=[{label:`Vendas e serviços`,amount:`200000`}],t[8]=y):y=t[8];let[b,x]=(0,d.useState)(y),S;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(S=[{label:`Despesas operacionais`,amount:`150000`}],t[9]=S):S=t[9];let[C,w]=(0,d.useState)(S),[T,E]=(0,d.useState)(`Mensal`),[D,O]=(0,d.useState)(!1),k;t[10]===r?k=t[11]:(k=()=>{let e=M(r);e&&(E(e.budgetPeriod),u({principal:e.loan.principal,rate:e.loan.rate,months:e.loan.months,rateType:e.loan.rateType,periodMonths:e.loan.periodMonths,gracePeriods:e.loan.gracePeriods,upfrontFee:e.loan.upfrontFee,recurringFee:e.loan.recurringFee}),h(e.breakEven),v(e.funding),x(e.incomes),w(e.expenses)),O(!0)},t[10]=r,t[11]=k);let A;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(A=[],t[12]=A):A=t[12],(0,d.useEffect)(k,A);let N,P;t[13]!==m||t[14]!==T||t[15]!==C||t[16]!==_||t[17]!==b||t[18]!==l||t[19]!==i||t[20]!==r||t[21]!==D?(P=()=>{if(!D)return;let e=j({budgetPeriod:T,loan:l,breakEven:m,funding:_,incomes:b,expenses:C});e!==r&&i(e)},N=[D,r,i,T,l,m,_,b,C],t[13]=m,t[14]=T,t[15]=C,t[16]=_,t[17]=b,t[18]=l,t[19]=i,t[20]=r,t[21]=D,t[22]=N,t[23]=P):(N=t[22],P=t[23]),(0,d.useEffect)(P,N);let F,I,L,R,z,ee,te,se,ce,B,le,fe,U,W,G,xe,Se,Ce,K,we,q,Te,Ee,De,J;if(t[24]!==m.fixed||t[25]!==m.price||t[26]!==m.variable||t[27]!==T||t[28]!==n||t[29]!==C||t[30]!==_.secured||t[31]!==_.total||t[32]!==b||t[33]!==l||t[34]!==a){let e,r=``;try{e=ie({principal:l.principal,annualRatePercent:l.rate,rateType:l.rateType,termMonths:Number(l.months),periodMonths:Number(l.periodMonths),gracePeriods:Number(l.gracePeriods),upfrontFee:l.upfrontFee,recurringFee:l.recurringFee}),L=ne(m.fixed,m.price,m.variable),I=re(_.total,_.secured),F=ae(b.map(be),C.map(ye))}catch(e){let t=e;r=t instanceof Error?t.message:`Verifique os valores introduzidos.`}J=ve,Se=`space-y-4 rounded-lg border border-slate-300 p-4`,Ce=`financial-tools-title`,t[60]===Symbol.for(`react.memo_cache_sentinel`)?(K=(0,V.jsx)(`h3`,{id:`financial-tools-title`,className:`text-lg font-semibold`,children:`Ferramentas de planeamento financeiro`}),we=(0,V.jsx)(`p`,{className:`text-sm text-slate-700`,children:`Estimativas educativas com os valores que introduzir. Não incluem impostos, comissões ou seguros, salvo indicação. Use a mesma moeda em cada cálculo.`}),t[60]=K,t[61]=we):(K=t[60],we=t[61]);let i;t[62]===a?i=t[63]:(i=e=>a(e.target.value.toUpperCase()),t[62]=a,t[63]=i);let o;t[64]===n?o=t[65]:(o=n!==``&&!de(n),t[64]=n,t[65]=o),t[66]!==n||t[67]!==i||t[68]!==o?(q=(0,V.jsxs)(`label`,{className:`block max-w-xs text-sm font-medium`,children:[`Moeda dos valores (código ISO)`,(0,V.jsx)(`input`,{list:`financial-currency-options`,inputMode:`text`,maxLength:3,pattern:`[A-Z]{3}`,autoCapitalize:`characters`,value:n,onChange:i,className:`mt-1 w-full rounded border p-2`,"aria-invalid":o})]}),t[66]=n,t[67]=i,t[68]=o,t[69]=q):q=t[69],t[70]===Symbol.for(`react.memo_cache_sentinel`)?(Te=(0,V.jsx)(`datalist`,{id:`financial-currency-options`,children:ue.map(_e)}),t[70]=Te):Te=t[70];let s=!de(n)||!!r,c;t[71]!==m.fixed||t[72]!==m.price||t[73]!==m.variable||t[74]!==T||t[75]!==n||t[76]!==C||t[77]!==_.secured||t[78]!==_.total||t[79]!==b||t[80]!==l.gracePeriods||t[81]!==l.months||t[82]!==l.periodMonths||t[83]!==l.principal||t[84]!==l.rate||t[85]!==l.rateType||t[86]!==l.recurringFee||t[87]!==l.upfrontFee?(c=()=>{let e=oe({currency:n,budgetPeriod:T,loan:{principal:l.principal,annualRatePercent:l.rate,termMonths:Number(l.months),periodMonths:Number(l.periodMonths),rateType:l.rateType,gracePeriods:Number(l.gracePeriods),upfrontFee:l.upfrontFee,recurringFee:l.recurringFee},breakEven:{fixedCosts:m.fixed,unitPrice:m.price,variableCostPerUnit:m.variable},funding:{totalInvestment:_.total,securedFunding:_.secured},incomes:b,expenses:C}),t=new Blob([e],{type:`text/csv;charset=utf-8`}),r=URL.createObjectURL(t),i=document.createElement(`a`);i.href=r,i.download=`ferramentas-financeiras.csv`,i.click(),window.setTimeout(()=>URL.revokeObjectURL(r),1e3)},t[71]=m.fixed,t[72]=m.price,t[73]=m.variable,t[74]=T,t[75]=n,t[76]=C,t[77]=_.secured,t[78]=_.total,t[79]=b,t[80]=l.gracePeriods,t[81]=l.months,t[82]=l.periodMonths,t[83]=l.principal,t[84]=l.rate,t[85]=l.rateType,t[86]=l.recurringFee,t[87]=l.upfrontFee,t[88]=c):c=t[88],t[89]!==s||t[90]!==c?(Ee=(0,V.jsx)(`button`,{type:`button`,disabled:s,className:`rounded border px-3 py-2 text-sm focus-visible:outline-2 disabled:opacity-50`,onClick:c,children:`Exportar resultados em CSV`}),t[89]=s,t[90]=c,t[91]=Ee):Ee=t[91],De=r&&(0,V.jsx)(`p`,{role:`alert`,className:`text-sm text-red-800`,children:r}),xe=`grid gap-5 md:grid-cols-2`,R=`space-y-2`;let d=n||`moeda por seleccionar`;t[92]===d?z=t[93]:(z=(0,V.jsxs)(`legend`,{className:`font-semibold`,children:[`Prestação indicativa —`,` `,d]}),t[92]=d,t[93]=z),t[94]===Symbol.for(`react.memo_cache_sentinel`)?(ee=(0,V.jsx)(`p`,{role:`note`,className:`text-sm text-slate-700`,children:`Simulação educativa, não constitui oferta nem concessão de crédito. A investeMoz não capta depósitos nem se apresenta como operador de microfinanças autorizado; o registo de operadores é um processo separado desta calculadora.`}),t[94]=ee):ee=t[94];let f;t[95]===l?f=t[96]:(f=e=>J(u,l,`principal`,e),t[95]=l,t[96]=f),t[97]!==l.principal||t[98]!==f?(te=(0,V.jsx)(H,{label:`Capital`,value:l.principal,onChange:f}),t[97]=l.principal,t[98]=f,t[99]=te):te=t[99];let p;t[100]===l?p=t[101]:(p=e=>J(u,l,`rate`,e),t[100]=l,t[101]=p),t[102]!==l.rate||t[103]!==p?(se=(0,V.jsx)(H,{label:`Taxa anual (%)`,value:l.rate,step:`0.000001`,onChange:p}),t[102]=l.rate,t[103]=p,t[104]=se):se=t[104];let h;t[105]===l?h=t[106]:(h=e=>J(u,l,`months`,e),t[105]=l,t[106]=h),t[107]!==l.months||t[108]!==h?(ce=(0,V.jsx)(H,{label:`Prazo (meses)`,value:l.months,step:`1`,onChange:h}),t[107]=l.months,t[108]=h,t[109]=ce):ce=t[109];let g;t[110]===l?g=t[111]:(g=e=>J(u,l,`rateType`,e.target.value),t[110]=l,t[111]=g);let v,y;t[112]===Symbol.for(`react.memo_cache_sentinel`)?(v=(0,V.jsx)(`option`,{value:`nominal`,children:`Nominal anual`}),y=(0,V.jsx)(`option`,{value:`effective`,children:`Efectiva anual`}),t[112]=v,t[113]=y):(v=t[112],y=t[113]),t[114]!==l.rateType||t[115]!==g?(B=(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Taxa`,(0,V.jsxs)(`select`,{className:`mt-1 w-full rounded border p-2`,value:l.rateType,onChange:g,children:[v,y]})]}),t[114]=l.rateType,t[115]=g,t[116]=B):B=t[116];let x;t[117]===l?x=t[118]:(x=e=>J(u,l,`periodMonths`,e),t[117]=l,t[118]=x),t[119]!==l.periodMonths||t[120]!==x?(le=(0,V.jsx)(H,{label:`Periodicidade (meses)`,value:l.periodMonths,step:`1`,onChange:x}),t[119]=l.periodMonths,t[120]=x,t[121]=le):le=t[121];let S;t[122]===l?S=t[123]:(S=e=>J(u,l,`gracePeriods`,e),t[122]=l,t[123]=S),t[124]!==l.gracePeriods||t[125]!==S?(fe=(0,V.jsx)(H,{label:`Carência (prestações só de juros)`,value:l.gracePeriods,step:`1`,onChange:S}),t[124]=l.gracePeriods,t[125]=S,t[126]=fe):fe=t[126];let w;t[127]===l?w=t[128]:(w=e=>J(u,l,`upfrontFee`,e),t[127]=l,t[128]=w),t[129]!==l.upfrontFee||t[130]!==w?(U=(0,V.jsx)(H,{label:`Comissão inicial`,value:l.upfrontFee,onChange:w}),t[129]=l.upfrontFee,t[130]=w,t[131]=U):U=t[131];let E;t[132]===l?E=t[133]:(E=e=>J(u,l,`recurringFee`,e),t[132]=l,t[133]=E),t[134]!==l.recurringFee||t[135]!==E?(W=(0,V.jsx)(H,{label:`Comissão por prestação`,value:l.recurringFee,onChange:E}),t[134]=l.recurringFee,t[135]=E,t[136]=W):W=t[136],G=e&&de(n)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`p`,{"aria-live":`polite`,children:[`Taxa por período: `,e.periodicRatePercent,`%; desembolso líquido: `,e.netDisbursed,` `,n,`; juros: `,e.totalInterest,`; comissões: `,e.totalFees,`; total pago:`,` `,e.totalPaid,`.`]}),(0,V.jsx)(`p`,{className:`text-xs`,children:`Método: saldo decrescente com prestação nivelada; a última prestação ajusta cêntimos residuais. A carência paga apenas juros. Taxa nominal divide a taxa anual pelos períodos; taxa efectiva converte a taxa anual para a periodicidade indicada.`}),(0,V.jsx)(`div`,{className:`max-h-64 overflow-auto`,children:(0,V.jsxs)(`table`,{className:`min-w-full text-xs`,children:[(0,V.jsx)(`caption`,{className:`sr-only`,children:`Plano de reembolso indicativo`}),(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Nº`,`Juros`,`Capital`,`Comissão`,`Prestação`,`Saldo`].map(ge)})}),(0,V.jsx)(`tbody`,{children:e.schedule.map(he)})]})}),(0,V.jsx)(`p`,{className:`text-xs`,children:`* Período de carência: pagamento apenas de juros e comissão indicada.`})]}),t[24]=m.fixed,t[25]=m.price,t[26]=m.variable,t[27]=T,t[28]=n,t[29]=C,t[30]=_.secured,t[31]=_.total,t[32]=b,t[33]=l,t[34]=a,t[35]=F,t[36]=I,t[37]=L,t[38]=R,t[39]=z,t[40]=ee,t[41]=te,t[42]=se,t[43]=ce,t[44]=B,t[45]=le,t[46]=fe,t[47]=U,t[48]=W,t[49]=G,t[50]=xe,t[51]=Se,t[52]=Ce,t[53]=K,t[54]=we,t[55]=q,t[56]=Te,t[57]=Ee,t[58]=De,t[59]=J}else F=t[35],I=t[36],L=t[37],R=t[38],z=t[39],ee=t[40],te=t[41],se=t[42],ce=t[43],B=t[44],le=t[45],fe=t[46],U=t[47],W=t[48],G=t[49],xe=t[50],Se=t[51],Ce=t[52],K=t[53],we=t[54],q=t[55],Te=t[56],Ee=t[57],De=t[58],J=t[59];let Oe;t[137]!==R||t[138]!==z||t[139]!==ee||t[140]!==te||t[141]!==se||t[142]!==ce||t[143]!==B||t[144]!==le||t[145]!==fe||t[146]!==U||t[147]!==W||t[148]!==G?(Oe=(0,V.jsxs)(`fieldset`,{className:R,children:[z,ee,te,se,ce,B,le,fe,U,W,G]}),t[137]=R,t[138]=z,t[139]=ee,t[140]=te,t[141]=se,t[142]=ce,t[143]=B,t[144]=le,t[145]=fe,t[146]=U,t[147]=W,t[148]=G,t[149]=Oe):Oe=t[149];let ke=n||`moeda por seleccionar`,Y;t[150]===ke?Y=t[151]:(Y=(0,V.jsxs)(`legend`,{className:`font-semibold`,children:[`Ponto de equilíbrio —`,` `,ke]}),t[150]=ke,t[151]=Y);let Ae;t[152]===T?Ae=t[153]:(Ae=T.toLowerCase(),t[152]=T,t[153]=Ae);let X=`Custos fixos (${Ae})`,Z;t[154]!==m||t[155]!==J?(Z=e=>J(h,m,`fixed`,e),t[154]=m,t[155]=J,t[156]=Z):Z=t[156];let je;t[157]!==m.fixed||t[158]!==X||t[159]!==Z?(je=(0,V.jsx)(H,{label:X,value:m.fixed,onChange:Z}),t[157]=m.fixed,t[158]=X,t[159]=Z,t[160]=je):je=t[160];let Me;t[161]!==m||t[162]!==J?(Me=e=>J(h,m,`price`,e),t[161]=m,t[162]=J,t[163]=Me):Me=t[163];let Ne;t[164]!==m.price||t[165]!==Me?(Ne=(0,V.jsx)(H,{label:`Preço por unidade`,value:m.price,onChange:Me}),t[164]=m.price,t[165]=Me,t[166]=Ne):Ne=t[166];let Pe;t[167]!==m||t[168]!==J?(Pe=e=>J(h,m,`variable`,e),t[167]=m,t[168]=J,t[169]=Pe):Pe=t[169];let Fe;t[170]!==m.variable||t[171]!==Pe?(Fe=(0,V.jsx)(H,{label:`Custo variável por unidade`,value:m.variable,onChange:Pe}),t[170]=m.variable,t[171]=Pe,t[172]=Fe):Fe=t[172];let Ie;t[173]!==n||t[174]!==L?.breakEvenRevenue||t[175]!==L?.breakEvenUnits?(Ie=de(n)&&(0,V.jsxs)(`p`,{"aria-live":`polite`,children:[`Unidades: `,L?.breakEvenUnits??`—`,`; vendas:`,` `,L?.breakEvenRevenue??`—`,` `,n]}),t[173]=n,t[174]=L?.breakEvenRevenue,t[175]=L?.breakEvenUnits,t[176]=Ie):Ie=t[176];let Le;t[177]!==Y||t[178]!==je||t[179]!==Ne||t[180]!==Fe||t[181]!==Ie?(Le=(0,V.jsxs)(`fieldset`,{className:`space-y-2`,children:[Y,je,Ne,Fe,Ie]}),t[177]=Y,t[178]=je,t[179]=Ne,t[180]=Fe,t[181]=Ie,t[182]=Le):Le=t[182];let Q=n||`moeda por seleccionar`,Re;t[183]===Q?Re=t[184]:(Re=(0,V.jsxs)(`legend`,{className:`font-semibold`,children:[`Necessidade de financiamento —`,` `,Q]}),t[183]=Q,t[184]=Re);let ze;t[185]!==_||t[186]!==J?(ze=e=>J(v,_,`total`,e),t[185]=_,t[186]=J,t[187]=ze):ze=t[187];let Be;t[188]!==_.total||t[189]!==ze?(Be=(0,V.jsx)(H,{label:`Investimento total`,value:_.total,onChange:ze}),t[188]=_.total,t[189]=ze,t[190]=Be):Be=t[190];let Ve;t[191]!==_||t[192]!==J?(Ve=e=>J(v,_,`secured`,e),t[191]=_,t[192]=J,t[193]=Ve):Ve=t[193];let $;t[194]!==_.secured||t[195]!==Ve?($=(0,V.jsx)(H,{label:`Montante já mobilizado`,value:_.secured,onChange:Ve}),t[194]=_.secured,t[195]=Ve,t[196]=$):$=t[196];let He;t[197]!==n||t[198]!==I?.gap?(He=de(n)&&(0,V.jsxs)(`p`,{"aria-live":`polite`,children:[`Diferença por financiar: `,I?.gap??`—`,` `,n]}),t[197]=n,t[198]=I?.gap,t[199]=He):He=t[199];let Ue;t[200]!==Re||t[201]!==Be||t[202]!==$||t[203]!==He?(Ue=(0,V.jsxs)(`fieldset`,{className:`space-y-2`,children:[Re,Be,$,He]}),t[200]=Re,t[201]=Be,t[202]=$,t[203]=He,t[204]=Ue):Ue=t[204];let We=n||`moeda por seleccionar`,Ge;t[205]===We?Ge=t[206]:(Ge=(0,V.jsxs)(`legend`,{className:`font-semibold`,children:[`Orçamento do período —`,` `,We]}),t[205]=We,t[206]=Ge);let Ke;t[207]===Symbol.for(`react.memo_cache_sentinel`)?(Ke=(0,V.jsx)(`p`,{className:`text-sm`,children:`Introduza os totais por fonte de receita e categoria de despesa.`}),t[207]=Ke):Ke=t[207];let qe;t[208]===Symbol.for(`react.memo_cache_sentinel`)?(qe=e=>E(e.target.value),t[208]=qe):qe=t[208];let Je,Ye,Xe,Ze;t[209]===Symbol.for(`react.memo_cache_sentinel`)?(Je=(0,V.jsx)(`option`,{children:`Mensal`}),Ye=(0,V.jsx)(`option`,{children:`Trimestral`}),Xe=(0,V.jsx)(`option`,{children:`Anual`}),Ze=(0,V.jsx)(`option`,{children:`Outro período`}),t[209]=Je,t[210]=Ye,t[211]=Xe,t[212]=Ze):(Je=t[209],Ye=t[210],Xe=t[211],Ze=t[212]);let Qe;t[213]===T?Qe=t[214]:(Qe=(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Período do orçamento`,(0,V.jsxs)(`select`,{value:T,onChange:qe,className:`mt-1 w-full rounded border p-2`,children:[Je,Ye,Xe,Ze]})]}),t[213]=T,t[214]=Qe);let $e;if(t[215]!==T||t[216]!==b){let e;t[218]!==T||t[219]!==b.length?(e=(e,t)=>(0,V.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_auto]`,children:[(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Fonte da receita `,t+1,(0,V.jsx)(`input`,{type:`text`,maxLength:120,value:e.label,onChange:e=>x(n=>n.map((n,r)=>r===t?{...n,label:e.target.value}:n)),className:`mt-1 w-full rounded border p-2`})]}),(0,V.jsx)(H,{label:`Valor da receita (${T.toLowerCase()})`,value:e.amount,onChange:e=>x(n=>n.map((n,r)=>r===t?{...n,amount:e}:n))}),(0,V.jsx)(`button`,{type:`button`,disabled:b.length<=1,"aria-label":`Remover receita ${e.label||t+1}`,className:`self-end rounded border px-3 py-2 text-sm disabled:opacity-50`,onClick:()=>x(e=>e.length>1?e.filter((e,n)=>n!==t):e),children:`Remover`})]},`income-${t}`),t[218]=T,t[219]=b.length,t[220]=e):e=t[220],$e=b.map(e),t[215]=T,t[216]=b,t[217]=$e}else $e=t[217];let et=b.length>=50,tt;t[221]===Symbol.for(`react.memo_cache_sentinel`)?(tt=()=>x(me),t[221]=tt):tt=t[221];let nt;t[222]===et?nt=t[223]:(nt=(0,V.jsx)(`button`,{type:`button`,disabled:et,className:`text-sm underline disabled:opacity-50`,onClick:tt,children:`Adicionar receita`}),t[222]=et,t[223]=nt);let rt;if(t[224]!==T||t[225]!==C){let e;t[227]!==T||t[228]!==C.length?(e=(e,t)=>(0,V.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_auto]`,children:[(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Categoria da despesa `,t+1,(0,V.jsx)(`input`,{type:`text`,maxLength:120,value:e.label,onChange:e=>w(n=>n.map((n,r)=>r===t?{...n,label:e.target.value}:n)),className:`mt-1 w-full rounded border p-2`})]}),(0,V.jsx)(H,{label:`Valor da despesa (${T.toLowerCase()})`,value:e.amount,onChange:e=>w(n=>n.map((n,r)=>r===t?{...n,amount:e}:n))}),(0,V.jsx)(`button`,{type:`button`,disabled:C.length<=1,"aria-label":`Remover despesa ${e.label||t+1}`,className:`self-end rounded border px-3 py-2 text-sm disabled:opacity-50`,onClick:()=>w(e=>e.length>1?e.filter((e,n)=>n!==t):e),children:`Remover`})]},`expense-${t}`),t[227]=T,t[228]=C.length,t[229]=e):e=t[229],rt=C.map(e),t[224]=T,t[225]=C,t[226]=rt}else rt=t[226];let it=C.length>=50,at;t[230]===Symbol.for(`react.memo_cache_sentinel`)?(at=()=>w(pe),t[230]=at):at=t[230];let ot;t[231]===it?ot=t[232]:(ot=(0,V.jsx)(`button`,{type:`button`,disabled:it,className:`text-sm underline disabled:opacity-50`,onClick:at,children:`Adicionar despesa`}),t[231]=it,t[232]=ot);let st;t[233]!==F||t[234]!==n?(st=F&&de(n)&&(0,V.jsxs)(`p`,{"aria-live":`polite`,children:[`Receitas: `,F.incomeTotal,` `,n,`; despesas:`,` `,F.expenseTotal,`; saldo operacional:`,` `,(0,V.jsx)(`strong`,{children:F.operatingBalance}),`.`]}),t[233]=F,t[234]=n,t[235]=st):st=t[235];let ct;t[236]!==Ge||t[237]!==Qe||t[238]!==$e||t[239]!==nt||t[240]!==rt||t[241]!==ot||t[242]!==st?(ct=(0,V.jsxs)(`fieldset`,{className:`space-y-2`,children:[Ge,Ke,Qe,$e,nt,rt,ot,st]}),t[236]=Ge,t[237]=Qe,t[238]=$e,t[239]=nt,t[240]=rt,t[241]=ot,t[242]=st,t[243]=ct):ct=t[243];let lt;t[244]!==xe||t[245]!==Oe||t[246]!==Le||t[247]!==Ue||t[248]!==ct?(lt=(0,V.jsxs)(`div`,{className:xe,children:[Oe,Le,Ue,ct]}),t[244]=xe,t[245]=Oe,t[246]=Le,t[247]=Ue,t[248]=ct,t[249]=lt):lt=t[249];let ut;return t[250]!==Se||t[251]!==Ce||t[252]!==K||t[253]!==we||t[254]!==q||t[255]!==Te||t[256]!==Ee||t[257]!==De||t[258]!==lt?(ut=(0,V.jsxs)(`section`,{className:Se,"aria-labelledby":Ce,children:[K,we,q,Te,Ee,De,lt]}),t[250]=Se,t[251]=Ce,t[252]=K,t[253]=we,t[254]=q,t[255]=Te,t[256]=Ee,t[257]=De,t[258]=lt,t[259]=ut):ut=t[259],ut}function pe(e){return e.length>=50?e:[...e,{label:`Outra despesa ${e.length+1}`,amount:`0`}]}function me(e){return e.length>=50?e:[...e,{label:`Outra receita ${e.length+1}`,amount:`0`}]}function he(e){return(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsxs)(`th`,{scope:`row`,className:`p-1`,children:[e.period,e.type===`interest_only`?`*`:``]}),(0,V.jsx)(`td`,{className:`p-1`,children:e.interest}),(0,V.jsx)(`td`,{className:`p-1`,children:e.principal}),(0,V.jsx)(`td`,{className:`p-1`,children:e.fee}),(0,V.jsx)(`td`,{className:`p-1`,children:e.totalPayment}),(0,V.jsx)(`td`,{className:`p-1`,children:e.closingBalance})]},e.period)}function ge(e){return(0,V.jsx)(`th`,{className:`p-1 text-left`,children:e},e)}function _e(e){return(0,V.jsx)(`option`,{value:e,children:e},e)}function ve(e,t,n,r){return e({...t,[n]:r})}function ye(e){return e.amount}function be(e){return e.amount}function U(e,t){let n=/^(\d+)(?:\.(\d{1,2}))?$/.exec(e.trim());if(!n)throw Error(`${t}: introduza um montante não negativo com até duas casas decimais.`);return BigInt(n[1])*100n+BigInt((n[2]??``).padEnd(2,`0`)||`0`)}function W(e,t){let n=/^(-?\d+)(?:\.(\d{1,2}))?$/.exec(e.trim());if(!n)throw Error(`${t}: introduza um montante com até duas casas decimais.`);return(n[1].startsWith(`-`)?-1n:1n)*(BigInt(n[1].replace(`-`,``))*100n+BigInt((n[2]??``).padEnd(2,`0`)||`0`))}function G(e){let t=e<0n?-e:e;return`${e<0n?`-`:``}${t/100n}.${String(t%100n).padStart(2,`0`)}`}function xe(e){if(e.currency)try{if(new Intl.NumberFormat(`en`,{style:`currency`,currency:e.currency}).resolvedOptions().maximumFractionDigits!==2)throw Error(`Esta ferramenta requer moeda com duas casas decimais.`)}catch(e){throw e instanceof Error&&e.message.includes(`duas casas`)?e:Error(`Seleccione uma moeda suportada com duas casas decimais.`)}let t=e.periods??12;if(!Number.isSafeInteger(t)||t<1||t>60)throw Error(`O período deve estar entre 1 e 60 meses.`);let n=W(e.openingCash,`Saldo inicial`),r=U(e.monthlyRevenue,`Receita mensal`),i=U(e.monthlyOperatingCosts,`Custos operacionais`),a=U(e.monthlyDebtService,`Serviço da dívida`),o=U(e.monthlyTaxAssessed??`0`,`Imposto apurado`),s=U(e.vatCreditEstimated??`0`,`Crédito de IVA estimado`),c=U(e.vatRefundRequested??`0`,`Reembolso de IVA pedido`),l=U(e.vatRefundRecognized??`0`,`Reembolso de IVA reconhecido`),u=U(e.vatRefundExpectedReceipt??`0`,`Recebimento previsto de IVA`);if(u>l)throw Error(`O recebimento previsto de IVA não pode exceder o montante reconhecido.`);let d=e.vatRefundExpectedMonth?Number(e.vatRefundExpectedMonth):0;if(u>0n&&(!Number.isSafeInteger(d)||d<1||d>t))throw Error(`Indique o mês previsto do recebimento entre 1 e o horizonte projectado.`);let f=[];for(let e=1;e<=t;e++){let t=n,s=u>0n&&d===e?u:0n,c=r-i-a-o+s;n+=c,f.push({month:e,openingCash:G(t),revenue:G(r),operatingCosts:G(i),debtService:G(a),taxAssessed:G(o),vatRefundExpectedReceipt:G(s),netFlow:G(c),closingCash:G(n)})}return{rows:f,endingCash:G(n),firstDeficitMonth:f.find(e=>BigInt(e.closingCash.replace(`.`,``))<0n)?.month??null,vatCreditEstimated:G(s),vatRefundRequested:G(c),vatRefundRecognized:G(l),vatRefundExpectedReceipt:G(u),status:`estimated`}}function Se(e){if(!e.currency)throw Error(`Seleccione a moeda antes de exportar.`);let t=xe(e);return`\uFEFF${[[`Relatório`,`Projecção educativa de tesouraria`],[`Moeda`,e.currency??`Não seleccionada`],[`Pressupostos`,`Saldo inicial`,e.openingCash],[`Pressupostos`,`Receita mensal`,e.monthlyRevenue],[`Pressupostos`,`Custos operacionais mensais`,e.monthlyOperatingCosts],[`Pressupostos`,`Serviço mensal da dívida`,e.monthlyDebtService],[`Pressupostos`,`Imposto apurado mensal (saída de caixa)`,e.monthlyTaxAssessed??`0`],[`Informativo; não caixa`,`Crédito de IVA estimado`,e.vatCreditEstimated??`0`],[`Informativo; não caixa`,`Pedido de reembolso de IVA`,e.vatRefundRequested??`0`],[`Informativo; não caixa`,`Reembolso de IVA reconhecido`,e.vatRefundRecognized??`0`],[`Pressuposto condicional de caixa`,`Recebimento previsto de reembolso IVA`,e.vatRefundExpectedReceipt??`0`],[`Pressuposto condicional de caixa`,`Mês previsto do recebimento IVA`,e.vatRefundExpectedMonth??`não indicado`],[],[`Mês`,`Saldo inicial`,`Receitas`,`Custos operacionais`,`Serviço da dívida`,`Imposto apurado`,`Recebimento IVA previsto`,`Fluxo líquido`,`Saldo final`],...t.rows.map(e=>[e.month,e.openingCash,e.revenue,e.operatingCosts,e.debtService,e.taxAssessed,e.vatRefundExpectedReceipt,e.netFlow,e.closingCash]),[],[`Nota`,`Recebimento previsto é pressuposto não garantido. Crédito estimado, pedido e montante reconhecido não entram no caixa. Projecção exclui sazonalidade e movimentos pontuais.`]].map(e=>e.map(p).join(`,`)).join(`\r
`)}`}function Ce(e){let t=(0,f.c)(20),{currency:n,onCurrencyChange:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i={openingCash:`0`,monthlyRevenue:`200000`,monthlyOperatingCosts:`150000`,monthlyDebtService:`0`,monthlyTaxAssessed:`0`,vatCreditEstimated:`0`,vatRefundRequested:`0`,vatRefundRecognized:`0`,vatRefundExpectedReceipt:`0`,vatRefundExpectedMonth:``},t[0]=i):i=t[0];let[a,o]=(0,d.useState)(i),s;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(s=(e,t)=>o(n=>({...n,[e]:t})),t[1]=s):s=t[1];let c=s,l;if(t[2]!==n||t[3]!==a||t[4]!==r){let e,i=``;try{e=xe({...a,currency:n})}catch(e){let t=e;i=t instanceof Error?t.message:`Verifique os valores introduzidos.`}let o;t[6]===r?o=t[7]:(o=e=>r(e.target.value.toUpperCase()),t[6]=r,t[7]=o);let s;t[8]===n?s=t[9]:(s=n!==``&&!de(n),t[8]=n,t[9]=s);let u;t[10]!==n||t[11]!==o||t[12]!==s?(u=(0,V.jsxs)(`label`,{className:`block max-w-xs text-sm font-medium`,children:[`Moeda dos valores (código ISO)`,(0,V.jsx)(`input`,{list:`cashflow-currency-options`,inputMode:`text`,maxLength:3,pattern:`[A-Z]{3}`,autoCapitalize:`characters`,value:n,onChange:o,className:`mt-1 w-full rounded border p-2`,"aria-invalid":s})]}),t[10]=n,t[11]=o,t[12]=s,t[13]=u):u=t[13];let d,f,p;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(f=(0,V.jsx)(`datalist`,{id:`cashflow-currency-options`,children:ue.map(q)}),p=(0,V.jsx)(`h3`,{id:`cashflow-title`,className:`text-lg font-semibold`,children:`Projecção de tesouraria — 12 meses`}),d=(0,V.jsx)(`p`,{className:`text-sm text-slate-700`,children:`Introduza pressupostos na mesma moeda. O imposto apurado reduz a caixa. Crédito estimado, pedido e montante reconhecido são informativos e não contam como caixa. Apenas o recebimento previsto entra no mês indicado, como hipótese não garantida.`}),t[14]=d,t[15]=f,t[16]=p):(d=t[14],f=t[15],p=t[16]);let m;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(m=[[`openingCash`,`Saldo inicial`],[`monthlyRevenue`,`Receita mensal`],[`monthlyOperatingCosts`,`Custos operacionais mensais`],[`monthlyDebtService`,`Prestação mensal`],[`monthlyTaxAssessed`,`Imposto apurado a pagar (mensal)`],[`vatCreditEstimated`,`Crédito de IVA estimado (não caixa)`],[`vatRefundRequested`,`Reembolso de IVA pedido (não caixa)`],[`vatRefundRecognized`,`Reembolso reconhecido (não caixa)`],[`vatRefundExpectedReceipt`,`Recebimento IVA previsto (condicional)`],[`vatRefundExpectedMonth`,`Mês previsto do recebimento (1–12)`]],t[17]=m):m=t[17];let h;t[18]===a?h=t[19]:(h=(0,V.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:m.map(e=>{let[t,n]=e;return(0,V.jsxs)(`label`,{className:`text-sm font-medium`,children:[n,(0,V.jsx)(`input`,{type:`number`,min:t===`vatRefundExpectedMonth`?`1`:`0`,max:t===`vatRefundExpectedMonth`?`12`:void 0,step:t===`vatRefundExpectedMonth`?`1`:`0.01`,value:a[t],onChange:e=>c(t,e.target.value),className:`mt-1 w-full rounded border p-2`})]},t)})}),t[18]=a,t[19]=h),l=(0,V.jsxs)(`section`,{className:`space-y-4 rounded-lg border border-slate-300 p-4`,"aria-labelledby":`cashflow-title`,children:[u,f,p,d,h,i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-sm text-red-800`,children:i}),e&&de(n)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`p`,{"aria-live":`polite`,className:`font-semibold`,children:[`Saldo ao fim de 12 meses (`,n,`):`,` `,e.endingCash]}),(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 text-sm focus-visible:outline-2`,onClick:()=>{let e=new Blob([Se({...a,currency:n,periods:12})],{type:`text/csv;charset=utf-8`}),t=URL.createObjectURL(e),r=document.createElement(`a`);r.href=t,r.download=`projecao-tesouraria.csv`,r.click(),URL.revokeObjectURL(t)},children:`Descarregar CSV`}),e.firstDeficitMonth&&(0,V.jsxs)(`output`,{className:`block rounded bg-amber-50 p-2 text-sm`,children:[`O saldo projectado fica negativo no mês`,` `,e.firstDeficitMonth,`.`]}),(0,V.jsxs)(`p`,{className:`text-sm`,children:[`Crédito estimado: `,e.vatCreditEstimated,`; pedido: `,e.vatRefundRequested,`; reconhecido:`,` `,e.vatRefundRecognized,`. Estes valores não foram somados à caixa.`]}),(0,V.jsx)(`div`,{className:`overflow-x-auto`,children:(0,V.jsxs)(`table`,{className:`min-w-full text-sm`,children:[(0,V.jsx)(`caption`,{className:`sr-only`,children:`Projecção mensal de tesouraria`}),(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Mês`,`Saldo inicial`,`Receitas`,`Custos`,`Dívida`,`Imposto apurado`,`Reembolso previsto`,`Fluxo líquido`,`Saldo final`].map(we)})}),(0,V.jsx)(`tbody`,{children:e.rows.map(K)})]})})]})]}),t[2]=n,t[3]=a,t[4]=r,t[5]=l}else l=t[5];return l}function K(e){return(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:e.month}),(0,V.jsx)(`td`,{className:`p-2`,children:e.openingCash}),(0,V.jsx)(`td`,{className:`p-2`,children:e.revenue}),(0,V.jsx)(`td`,{className:`p-2`,children:e.operatingCosts}),(0,V.jsx)(`td`,{className:`p-2`,children:e.debtService}),(0,V.jsx)(`td`,{className:`p-2`,children:e.taxAssessed}),(0,V.jsx)(`td`,{className:`p-2`,children:e.vatRefundExpectedReceipt}),(0,V.jsx)(`td`,{className:`p-2`,children:e.netFlow}),(0,V.jsx)(`td`,{className:`p-2`,children:e.closingCash})]},e.month)}function we(e){return(0,V.jsx)(`th`,{scope:`col`,className:`p-2 text-left`,children:e},e)}function q(e){return(0,V.jsx)(`option`,{value:e,children:e},e)}function Te(e){let t=new Set([`MZN`,`USD`,`EUR`,`ZAR`,...Intl.supportedValuesOf?.(`currency`)??[]]);try{return t.has(e)&&new Intl.NumberFormat(`en`,{style:`currency`,currency:e}).resolvedOptions().maximumFractionDigits===2}catch{return!1}}function Ee(e){let t=JSON.stringify({version:16,plan:{...e,...e.useSupplierPaymentTerms===!0?{products:e.products.map(e=>({...e,productInventoryPurchasesByPeriod:e.productInventoryPurchasesByPeriod?.map(e=>({...e,paymentInstallments:e.paymentInstallments??[{lagMonths:e.paymentLagMonths??0,percent:`100`}]}))??null}))}:{},monthlyInventoryPurchases:e.monthlyInventoryPurchases??``,inventoryPurchaseLeadMonths:e.inventoryPurchaseLeadMonths??0,inventoryPurchaseSchedule:e.inventoryPurchaseSchedule??null,useInventoryPurchaseSchedule:e.useInventoryPurchaseSchedule??!1,useProductInventorySchedule:e.useProductInventorySchedule??!1,useSupplierPaymentTerms:e.useSupplierPaymentTerms??!1,monthlyVariableCostPaymentsByPeriod:e.monthlyVariableCostPaymentsByPeriod??null,salesCollectionLagMonths:e.salesCollectionLagMonths??null,salesCollectionPercent:e.salesCollectionPercent??`100`,openingReceivablesCollectionMonth:e.openingReceivablesCollectionMonth??null,openingReceivablesCollectionPercent:e.openingReceivablesCollectionPercent??`100`,openingReceivablesInstallments:e.openingReceivablesInstallments??[],salesRecoverySchedule:e.salesRecoverySchedule??[]}});if(t.length>6e4)throw Error(`O plano financeiro excede o limite de armazenamento de 60 KB. Reduza produtos ou agendas mensais antes de guardar.`);return t}function De(e){if(!e||e.length>6e4)return null;try{let t=JSON.parse(e);if(t.version!==1&&t.version!==2&&t.version!==3&&t.version!==4&&t.version!==5&&t.version!==6&&t.version!==7&&t.version!==8&&t.version!==9&&t.version!==10&&t.version!==11&&t.version!==12&&t.version!==13&&t.version!==14&&t.version!==15&&t.version!==16||!t.plan||typeof t.plan!=`object`)return null;let n=t.plan;if([`currency`,`openingCash`,`monthlyCollections`,`monthlyVariableCostPayments`,`monthlyOperatingExpenses`,`monthlyOperatingPayments`,`monthlyPayrollExpense`,`monthlyPayrollPayments`,`assetInvestment`,`inventory`,`receivables`,`payables`,`equity`,`shareholderLoans`,`bankLoanProceeds`,`grants`,`assetDepreciation`,`monthlyInterestExpense`,`monthlyInterestPayment`,`monthlyPrincipalRepayment`].some(e=>typeof n[e]!=`string`)||!Number.isSafeInteger(n.periods)||!Number.isSafeInteger(n.depreciationLifeMonths)||n.monthlyInventoryPurchases!==void 0&&typeof n.monthlyInventoryPurchases!=`string`||t.version!==1&&typeof n.monthlyInventoryPurchases!=`string`||n.inventoryPurchaseLeadMonths!==void 0&&(!Number.isSafeInteger(n.inventoryPurchaseLeadMonths)||Number(n.inventoryPurchaseLeadMonths)<0||Number(n.inventoryPurchaseLeadMonths)>12)||t.version===3&&!Number.isSafeInteger(n.inventoryPurchaseLeadMonths)||[12,13,14,15,16].includes(Number(t.version))&&(!Object.hasOwn(n,`inventoryPurchaseSchedule`)||!Object.hasOwn(n,`useInventoryPurchaseSchedule`)||typeof n.useInventoryPurchaseSchedule!=`boolean`)||n.inventoryPurchaseSchedule!==void 0&&n.inventoryPurchaseSchedule!==null&&(![12,13,14,15,16].includes(Number(t.version))||!Array.isArray(n.inventoryPurchaseSchedule)||n.inventoryPurchaseSchedule.length<Number(n.periods)||n.inventoryPurchaseSchedule.length>60||n.inventoryPurchaseSchedule.some(e=>!e||typeof e!=`object`||typeof e.amount!=`string`||!Number.isSafeInteger(e.leadMonths)||e.leadMonths<0||e.leadMonths>12||e.paymentLagMonths!==void 0))||n.useInventoryPurchaseSchedule===!0&&!Array.isArray(n.inventoryPurchaseSchedule)||[13,14,15,16].includes(Number(t.version))&&!Object.hasOwn(n,`monthlyVariableCostPaymentsByPeriod`)||n.monthlyVariableCostPaymentsByPeriod!==void 0&&n.monthlyVariableCostPaymentsByPeriod!==null&&(![13,14,15,16].includes(Number(t.version))||!Array.isArray(n.monthlyVariableCostPaymentsByPeriod)||n.monthlyVariableCostPaymentsByPeriod.length<Number(n.periods)||n.monthlyVariableCostPaymentsByPeriod.length>60||n.monthlyVariableCostPaymentsByPeriod.some(e=>typeof e!=`string`))||n.salesCollectionLagMonths!==void 0&&n.salesCollectionLagMonths!==null&&(!Number.isSafeInteger(n.salesCollectionLagMonths)||Number(n.salesCollectionLagMonths)<0||Number(n.salesCollectionLagMonths)>12)||[4,5,6].includes(Number(t.version))&&!Object.hasOwn(n,`salesCollectionLagMonths`)||n.salesCollectionPercent!==void 0&&typeof n.salesCollectionPercent!=`string`||[5,6].includes(Number(t.version))&&!Object.hasOwn(n,`salesCollectionPercent`))return null;let r=Z(String(n.salesCollectionPercent??`100`),`Percentagem de cobranÃ§a`);if(r<0n||r>100000000n||n.openingReceivablesCollectionMonth!==void 0&&n.openingReceivablesCollectionMonth!==null&&(!Number.isSafeInteger(n.openingReceivablesCollectionMonth)||Number(n.openingReceivablesCollectionMonth)<1||Number(n.openingReceivablesCollectionMonth)>60)||n.openingReceivablesCollectionPercent!==void 0&&typeof n.openingReceivablesCollectionPercent!=`string`||t.version===6&&(!Object.hasOwn(n,`openingReceivablesCollectionMonth`)||!Object.hasOwn(n,`openingReceivablesCollectionPercent`)))return null;let i=Z(String(n.openingReceivablesCollectionPercent??`100`),`Percentagem de cobranÃ§a dos valores a receber de abertura`);if(i<0n||i>100000000n)return null;if([7,8,9,10,11,12,13,14,15,16].includes(Number(t.version))){if(!Array.isArray(n.openingReceivablesInstallments)||n.openingReceivablesInstallments.length>60)return null;let e=n.openingReceivablesCollectionMonth===null||n.openingReceivablesCollectionMonth===void 0?0n:i;for(let t of n.openingReceivablesInstallments){if(!t||typeof t!=`object`||!Number.isSafeInteger(t.month)||t.month<1||t.month>60||typeof t.percent!=`string`)return null;let n=Z(t.percent,`Percentagem da parcela de recebÃ­veis`);if(n<0n||n>100000000n)return null;e+=n}if(e>100000000n)return null}if([8,9,10,11,12,13,14,15,16].includes(Number(t.version))){if(!Array.isArray(n.salesRecoverySchedule)||n.salesRecoverySchedule.length>60)return null;let e=new Set;for(let t of n.salesRecoverySchedule){if(!t||typeof t!=`object`||!Number.isSafeInteger(t.month)||t.month<1||t.month>60||typeof t.percent!=`string`||e.has(t.month))return null;e.add(t.month);let n=Z(t.percent,`Percentagem de recuperaÃ§Ã£o de vendas`);if(n<0n||n>100000000n)return null}}for(let e of[`monthlyOperatingExpensesByPeriod`,`monthlyOperatingPaymentsByPeriod`,`monthlyPayrollExpenseByPeriod`,`monthlyPayrollPaymentsByPeriod`]){let r=n[e];if(r!==void 0&&(![11,12,13,14,15,16].includes(Number(t.version))||!Array.isArray(r)||r.length<Number(n.periods)||r.length>60||r.some(e=>typeof e!=`string`)))return null}for(let e of[`presentationCurrency`,`fxRate`,`fxDate`,`fxSource`])if(n[e]!==void 0&&typeof n[e]!=`string`)return null;if(t.version>=14&&typeof n.useProductInventorySchedule!=`boolean`||t.version<14&&n.useProductInventorySchedule===!0||t.version>=15&&typeof n.useSupplierPaymentTerms!=`boolean`||t.version<15&&n.useSupplierPaymentTerms===!0||n.useSupplierPaymentTerms===!0&&n.useProductInventorySchedule!==!0)return null;if(n.scenarioAdjustments!==void 0){let e=n.scenarioAdjustments;for(let t of[`favorable`,`unfavorable`]){let n=e[t];if(!n||typeof n!=`object`||[`unitVolumePercent`,`unitPricePercent`,`unitCostPercent`,`operatingCostsPercent`,`cashCollectionsPercent`].some(e=>typeof n[e]!=`string`))return null}}return!Array.isArray(n.products)||n.products.length===0||n.products.some(e=>{if(!e||typeof e!=`object`||[`label`,`monthlyUnits`,`unitPrice`,`unitVariableCost`].some(t=>typeof e[t]!=`string`))return!0;let r=e,i=r.monthlyUnitsByPeriod,a=r.unitPriceByPeriod,o=r.unitVariableCostByPeriod,s=e=>e===void 0||[10,11,12,13,14,15,16].includes(Number(t.version))&&Array.isArray(e)&&e.length>=Number(n.periods)&&e.length<=60&&e.every(e=>typeof e==`string`);return i!==void 0&&(![9,10,11,12,13,14,15,16].includes(Number(t.version))||!Array.isArray(i)||i.length<Number(n.periods)||i.length>60||i.some(e=>typeof e!=`string`))||!s(a)||!s(o)||r.productInventoryOpening!==void 0&&(Number(t.version)<14||typeof r.productInventoryOpening!=`string`)||r.productInventoryPurchasesByPeriod!==void 0&&(Number(t.version)<14||!Array.isArray(r.productInventoryPurchasesByPeriod)||r.productInventoryPurchasesByPeriod.length<Number(n.periods)||r.productInventoryPurchasesByPeriod.length>60||r.productInventoryPurchasesByPeriod.some(e=>!e||typeof e.amount!=`string`||!Number.isSafeInteger(e.leadMonths)||e.leadMonths<0||e.leadMonths>12||e.paymentLagMonths!==void 0&&(!Number.isSafeInteger(e.paymentLagMonths)||e.paymentLagMonths<0||e.paymentLagMonths>12)||e.paymentInstallments!==void 0&&(t.version!==16||!Array.isArray(e.paymentInstallments)||e.paymentInstallments.length>12||e.paymentInstallments.some(e=>!e||!Number.isSafeInteger(e.lagMonths)||e.lagMonths<0||e.lagMonths>12||typeof e.percent!=`string`||Z(e.percent,`Percentagem da parcela`)<0n||Z(e.percent,`Percentagem da parcela`)>100000000n)||e.paymentInstallments.reduce((e,t)=>e+Z(t.percent,`Percentagem da parcela`),0n)>100000000n)))||n.useProductInventorySchedule===!0&&(typeof r.productInventoryOpening!=`string`||!Array.isArray(r.productInventoryPurchasesByPeriod))||n.useSupplierPaymentTerms===!0&&r.productInventoryPurchasesByPeriod.some(e=>t.version===15?!Number.isSafeInteger(e.paymentLagMonths)||e.paymentLagMonths<0||e.paymentLagMonths>12:!Array.isArray(e.paymentInstallments))})?null:{...n,inventoryPurchaseLeadMonths:Number(n.inventoryPurchaseLeadMonths??0),salesCollectionLagMonths:n.salesCollectionLagMonths===null||n.salesCollectionLagMonths===void 0?null:Number(n.salesCollectionLagMonths),salesCollectionPercent:String(n.salesCollectionPercent??`100`),openingReceivablesCollectionMonth:n.openingReceivablesCollectionMonth===null||n.openingReceivablesCollectionMonth===void 0?null:Number(n.openingReceivablesCollectionMonth),openingReceivablesCollectionPercent:String(n.openingReceivablesCollectionPercent??`100`),openingReceivablesInstallments:Array.isArray(n.openingReceivablesInstallments)?n.openingReceivablesInstallments.map(e=>({month:Number(e.month),percent:String(e.percent)})):[],salesRecoverySchedule:Array.isArray(n.salesRecoverySchedule)?n.salesRecoverySchedule.map(e=>({month:Number(e.month),percent:String(e.percent)})):[],inventoryPurchaseSchedule:Array.isArray(n.inventoryPurchaseSchedule)?n.inventoryPurchaseSchedule.map(e=>({amount:String(e.amount),leadMonths:Number(e.leadMonths)})):null,useInventoryPurchaseSchedule:n.useInventoryPurchaseSchedule===!0,useProductInventorySchedule:n.useProductInventorySchedule===!0,useSupplierPaymentTerms:n.useSupplierPaymentTerms===!0,monthlyVariableCostPaymentsByPeriod:Array.isArray(n.monthlyVariableCostPaymentsByPeriod)?n.monthlyVariableCostPaymentsByPeriod.map(String):null}}catch{return null}}function J(e,t,n=!1){let r=(n?/^(-?\d+)(?:\.(\d{1,2}))?$/:/^(\d+)(?:\.(\d{1,2}))?$/).exec(e.trim());if(!r||e.length>40)throw Error(`${t}: use um montante${n?``:` nÃ£o negativo`} com atÃ© duas casas decimais.`);return(r[1].startsWith(`-`)?-1n:1n)*(BigInt(r[1].replace(`-`,``))*100n+BigInt((r[2]??``).padEnd(2,`0`)||`0`))}function Oe(e){let t=/^(\d+)(?:\.(\d{1,3}))?$/.exec(e.trim());if(!t||e.length>40)throw Error(`Quantidade: use um valor nÃ£o negativo com atÃ© trÃªs casas decimais.`);return BigInt(t[1])*1000n+BigInt((t[2]??``).padEnd(3,`0`)||`0`)}function ke(e,t){return(e*t+500n)/1000n}function Y(e){let t=e<0n?-e:e;return`${e<0n?`-`:``}${t/100n}.${String(t%100n).padStart(2,`0`)}`}function Ae(e,t,n){let r=/^(\d+)(?:\.(\d+))?$/.exec(e.trim());if(!r||(r[2]?.length??0)>t||e.length>40)throw Error(`${n}: use um decimal positivo com atÃ© ${t} casas.`);return BigInt(r[1])*10n**BigInt(t)+BigInt((r[2]??``).padEnd(t,`0`)||`0`)}function X(e,t,n){return(e<0n?-1n:1n)*(((e<0n?-e:e)*t+n/2n)/n)}function Z(e,t){let n=/^(-?\d+)(?:\.(\d{1,6}))?$/.exec(e.trim());if(!n||e.length>40)throw Error(`${t}: indique uma percentagem com atÃ© seis casas.`);return(n[1].startsWith(`-`)?-1n:1n)*(BigInt(n[1].replace(`-`,``))*1000000n+BigInt((n[2]??``).padEnd(6,`0`)||`0`))}function je(e){return`${e/1000000n}.${String(e%1000000n).padStart(6,`0`).replace(/0+$/,``)}`.replace(/\.$/,``)}function Me(e,t,n){let r=100000000n+Z(t,n);if(r<0n)throw Error(`${n}: a reduÃ§Ã£o nÃ£o pode exceder 100%.`);let i=((e<0n?-e:e)*r+50000000n)/100000000n;return e<0n?-i:i}function Ne(e){return`${e/1000n}.${String(e%1000n).padStart(3,`0`)}`}function Pe(e,t){let n=(e,n)=>Ne(Me(Oe(e),t.unitVolumePercent,`${n}: volume`)),r=(e,t,n)=>Y(Me(J(e,n),t,n)),i=Z(e.salesCollectionPercent??`100`,`Percentagem de cobranÃ§a`),a=100000000n+Z(t.cashCollectionsPercent,`VariaÃ§Ã£o das cobranÃ§as`),o=(i*a+50000000n)/100000000n,s=je(o<0n?0n:o>100000000n?100000000n:o),c=(Z(e.openingReceivablesCollectionPercent??`100`,`Percentagem de cobranÃ§a dos valores a receber de abertura`)*a+50000000n)/100000000n,l=c<0n?0n:c>100000000n?100000000n:c,u=e.openingReceivablesCollectionMonth===null||e.openingReceivablesCollectionMonth===void 0?e.openingReceivablesCollectionPercent??`100`:je(l),d=100000000n-(e.openingReceivablesCollectionMonth===null||e.openingReceivablesCollectionMonth===void 0?0n:l),f=(e.openingReceivablesInstallments??[]).map(e=>{let t=(Z(e.percent,`Percentagem da parcela de recebÃ­veis`)*a+50000000n)/100000000n,n=t<0n?0n:t>d?d:t;return d-=n,{...e,percent:je(n)}}),p=(e.salesRecoverySchedule??[]).map(e=>{let t=(Z(e.percent,`Percentagem de recuperaÃ§Ã£o de vendas`)*a+50000000n)/100000000n;return{...e,percent:je(t<0n?0n:t>100000000n?100000000n:t)}});return{...e,products:e.products.map(i=>({...i,monthlyUnits:n(i.monthlyUnits,i.label),monthlyUnitsByPeriod:i.monthlyUnitsByPeriod?.map((e,t)=>n(e,`${i.label}: mÃªs ${t+1}`)),unitPrice:r(i.unitPrice,t.unitPricePercent,`${i.label}: preÃ§o`),unitPriceByPeriod:i.unitPriceByPeriod?.map((e,n)=>r(e,t.unitPricePercent,`${i.label}: preÃ§o mÃªs ${n+1}`)),unitVariableCost:r(i.unitVariableCost,t.unitCostPercent,`${i.label}: custo unitÃ¡rio`),unitVariableCostByPeriod:i.unitVariableCostByPeriod?.map((e,n)=>r(e,t.unitCostPercent,`${i.label}: custo unitÃ¡rio mÃªs ${n+1}`)),productInventoryPurchasesByPeriod:e.useProductInventorySchedule===!0?i.productInventoryPurchasesByPeriod?.map((n,a)=>({...n,amount:a>=(e.periods??12)?n.amount:r(r(n.amount,t.unitVolumePercent,`${i.label}: stock volume mes ${a+1}`),t.unitCostPercent,`${i.label}: compra mes ${a+1}`)})):i.productInventoryPurchasesByPeriod})),monthlyVariableCostPayments:r(r(e.monthlyVariableCostPayments,t.unitVolumePercent,`Volume de pagamentos variÃ¡veis`),t.unitCostPercent,`Custo dos pagamentos variÃ¡veis`),monthlyVariableCostPaymentsByPeriod:e.monthlyVariableCostPaymentsByPeriod?.map((e,n)=>r(r(e,t.unitVolumePercent,`Volume dos pagamentos de compras mês ${n+1}`),t.unitCostPercent,`Pagamento de compras mês ${n+1}`))??null,monthlyInventoryPurchases:e.monthlyInventoryPurchases===void 0||e.monthlyInventoryPurchases.trim()===``?void 0:r(r(e.monthlyInventoryPurchases,t.unitVolumePercent,`Volume de compras para existÃªncias`),t.unitCostPercent,`Compras para existÃªncias`),inventoryPurchaseSchedule:e.useInventoryPurchaseSchedule===!0?e.inventoryPurchaseSchedule?.map((n,i)=>({...n,amount:i>=(e.periods??12)?n.amount:r(r(n.amount,t.unitVolumePercent,`Compras para existências, volume mês ${i+1}`),t.unitCostPercent,`Compras para existências mês ${i+1}`)})):e.inventoryPurchaseSchedule,monthlyOperatingExpenses:r(e.monthlyOperatingExpenses,t.operatingCostsPercent,`Despesas operacionais`),monthlyOperatingExpensesByPeriod:e.monthlyOperatingExpensesByPeriod?.map((e,n)=>r(e,t.operatingCostsPercent,`Despesas operacionais mes ${n+1}`)),monthlyOperatingPayments:r(e.monthlyOperatingPayments,t.operatingCostsPercent,`Pagamentos operacionais`),monthlyOperatingPaymentsByPeriod:e.monthlyOperatingPaymentsByPeriod?.map((e,n)=>r(e,t.operatingCostsPercent,`Pagamentos operacionais mes ${n+1}`)),monthlyPayrollExpense:r(e.monthlyPayrollExpense,t.operatingCostsPercent,`Pessoal`),monthlyPayrollExpenseByPeriod:e.monthlyPayrollExpenseByPeriod?.map((e,n)=>r(e,t.operatingCostsPercent,`Despesa com pessoal mes ${n+1}`)),monthlyPayrollPayments:r(e.monthlyPayrollPayments,t.operatingCostsPercent,`Pagamentos de pessoal`),monthlyPayrollPaymentsByPeriod:e.monthlyPayrollPaymentsByPeriod?.map((e,n)=>r(e,t.operatingCostsPercent,`Pagamentos de pessoal mes ${n+1}`)),monthlyCollections:r(e.monthlyCollections,t.cashCollectionsPercent,`CobranÃ§as`),salesCollectionPercent:s,openingReceivablesCollectionPercent:u,openingReceivablesInstallments:f,salesRecoverySchedule:p}}function Fe(e){if(!e.scenarioAdjustments)throw Error(`Indique os pressupostos para os cenÃ¡rios favorÃ¡vel e desfavorÃ¡vel.`);let t=Ie(e),n=Pe(e,e.scenarioAdjustments.favorable),r=Pe(e,e.scenarioAdjustments.unfavorable);return{base:t,favorable:{adjustments:e.scenarioAdjustments.favorable,result:Ie(n)},unfavorable:{adjustments:e.scenarioAdjustments.unfavorable,result:Ie(r)},changedAssumptions:[`unidades vendidas`,`preÃ§o unitÃ¡rio`,`custo variÃ¡vel unitÃ¡rio`,`compras para existÃªncias`,`despesas e pessoal`,`cobranÃ§as`]}}function Ie(e){if(!Te(e.currency))throw Error(`Seleccione um cÃ³digo de moeda ISO suportado.`);let t=e.periods??12;if(!Number.isSafeInteger(t)||t<1||t>60)throw Error(`O horizonte deve estar entre 1 e 60 meses.`);if(!Number.isSafeInteger(e.depreciationLifeMonths)||e.depreciationLifeMonths<1||e.depreciationLifeMonths>600)throw Error(`A vida Ãºtil contabilÃ­stica deve estar entre 1 e 600 meses.`);let n=e.inventoryPurchaseLeadMonths??0;if(!Number.isSafeInteger(n)||n<0||n>12)throw Error(`O prazo de entrega das compras deve estar entre 0 e 12 meses.`);let r=e.inventoryPurchaseSchedule??null;if(r!==null&&(!Array.isArray(r)||r.length<t||r.length>60||r.some(e=>!e||typeof e.amount!=`string`||!Number.isSafeInteger(e.leadMonths)||e.leadMonths<0||e.leadMonths>12)))throw Error(`A agenda de compras deve cobrir os ${t} meses e usar prazos de entrega entre 0 e 12 meses.`);let i=e.useInventoryPurchaseSchedule===!0,a=e.useProductInventorySchedule===!0,o=e.useSupplierPaymentTerms===!0;if(o&&!a)throw Error(`Os prazos de pagamento a fornecedores exigem compras planeadas por produto.`);if(i&&a)throw Error(`Seleccione compras agregadas ou stock por produto, nao os dois modos.`);if(i&&r===null)throw Error(`Indique a agenda mensal de compras para a utilizar.`);let s=e.salesCollectionLagMonths??null;if(s!==null&&(!Number.isSafeInteger(s)||s<0||s>12))throw Error(`O prazo de cobranÃ§a das vendas deve estar entre 0 e 12 meses.`);let c=e.salesCollectionPercent??`100`,l=Z(c,`Percentagem de cobranÃ§a`);if(l<0n||l>100000000n)throw Error(`A percentagem de cobranÃ§a deve estar entre 0 e 100.`);let u=e.openingReceivablesCollectionMonth??null;if(u!==null&&(!Number.isSafeInteger(u)||u<1||u>t))throw Error(`O mÃªs de cobranÃ§a dos valores a receber deve estar dentro do horizonte da simulaÃ§Ã£o.`);let d=e.openingReceivablesCollectionPercent??`100`,f=Z(d,`Percentagem de cobranÃ§a dos valores a receber de abertura`);if(f<0n||f>100000000n)throw Error(`A percentagem de cobranÃ§a dos valores a receber deve estar entre 0 e 100.`);let p=e.openingReceivablesInstallments??[];if(!Array.isArray(p)||p.length>60)throw Error(`A agenda de recebÃ­veis deve ter atÃ© 60 parcelas.`);let m=u===null?0n:f,h=p.map(e=>{if(!Number.isSafeInteger(e.month)||e.month<1||e.month>t)throw Error(`Cada parcela de recebÃ­veis deve estar dentro do horizonte da simulaÃ§Ã£o.`);let n=Z(e.percent,`Percentagem da parcela de recebÃ­veis`);if(n<0n||n>100000000n)throw Error(`A percentagem de cada parcela deve estar entre 0 e 100.`);return m+=n,n});if(m>100000000n)throw Error(`A soma das cobranÃ§as declaradas de recebÃ­veis de abertura nÃ£o pode exceder 100%.`);let g=e.salesRecoverySchedule??[];if(!Array.isArray(g)||g.length>60)throw Error(`A agenda de recuperação deve ter até 60 parcelas.`);let _=new Set,v=new Map;if(g.forEach(e=>{if(!Number.isSafeInteger(e.month)||e.month<1||e.month>t||_.has(e.month))throw Error(`Cada recuperação deve ter um mês único dentro do horizonte.`);_.add(e.month);let n=Z(e.percent,`Percentagem de recuperação de vendas`);if(n<0n||n>100000000n)throw Error(`A percentagem de recuperação deve estar entre 0 e 100.`);v.set(e.month,n)}),!e.products.length)throw Error(`Adicione pelo menos um produto ou serviÃ§o.`);let y=e.presentationCurrency||e.currency;if(!Te(y))throw Error(`Seleccione uma moeda de apresentaÃ§Ã£o ISO suportada.`);let b=null;if(y!==e.currency){if(!e.fxRate||!e.fxDate||!e.fxSource?.trim())throw Error(`Para converter moeda, indique taxa, data efectiva e fonte da taxa de cÃ¢mbio.`);if(b=Ae(e.fxRate,8,`Taxa de cÃ¢mbio`),b===0n)throw Error(`A taxa de cÃ¢mbio deve ser superior a zero.`);let t=/^\d{4}-\d{2}-\d{2}$/.test(e.fxDate)?new Date(`${e.fxDate}T00:00:00Z`):null;if(!t||Number.isNaN(t.getTime())||t.toISOString().slice(0,10)!==e.fxDate)throw Error(`Indique uma data de cÃ¢mbio vÃ¡lida no formato AAAA-MM-DD.`);if(e.fxSource.trim().length>2e3)throw Error(`A fonte da taxa de cÃ¢mbio excede o limite de caracteres.`)}let x=e.products.map((e,n)=>{let r=e.monthlyUnitsByPeriod,i=e.unitPriceByPeriod,o=e.unitVariableCostByPeriod;if(r!==void 0&&(!Array.isArray(r)||r.length<t||r.length>60))throw Error(`O plano de unidades do produto ${n+1} deve cobrir os ${t} meses do horizonte.`);let s=(e,n,r)=>{if(e===void 0)return Array(t).fill(n);if(!Array.isArray(e)||e.length<t||e.length>60)throw Error(`${r}: a agenda deve cobrir os ${t} meses do horizonte e ter no mÃ¡ximo 60 meses.`);return e.map((e,t)=>J(e,`${r}, mÃªs ${t+1}`))},c=J(e.unitPrice,`PreÃ§o do produto ${n+1}`),l=J(e.unitVariableCost,`Custo variÃ¡vel do produto ${n+1}`);a&&J(e.productInventoryOpening??``,`Opening inventory for ${e.label}`);let u=e.productInventoryPurchasesByPeriod??null;if(a&&(!Array.isArray(u)||u.length<t||u.length>60||u.some(e=>!e||typeof e.amount!=`string`||!Number.isSafeInteger(e.leadMonths)||e.leadMonths<0||e.leadMonths>12)))throw Error(`${e.label}: declare purchases and lead times for all ${t} months.`);return{units:r?.map(Oe)??Array(t).fill(Oe(e.monthlyUnits)),prices:s(i,c,`PreÃ§o do produto ${n+1}`),costs:s(o,l,`Custo variÃ¡vel do produto ${n+1}`)}}),S=e.products.map((e,n)=>{if(!a)return{opening:null,orders:null};let r=J(e.productInventoryOpening??``,`Existencias iniciais de ${e.label}`),i=e.productInventoryPurchasesByPeriod;if(!Array.isArray(i)||i.length<t||i.length>60||i.some(e=>!e||typeof e.amount!=`string`||!Number.isSafeInteger(e.leadMonths)||e.leadMonths<0||e.leadMonths>12||o&&(e.paymentInstallments===void 0?!Number.isSafeInteger(e.paymentLagMonths)||e.paymentLagMonths<0||e.paymentLagMonths>12:!Array.isArray(e.paymentInstallments)||e.paymentInstallments.length>12||e.paymentInstallments.some(e=>!Number.isSafeInteger(e.lagMonths)||e.lagMonths<0||e.lagMonths>12||typeof e.percent!=`string`||Z(e.percent,`Percentagem da parcela`)<0n||Z(e.percent,`Percentagem da parcela`)>100000000n)||e.paymentInstallments.reduce((e,t)=>e+Z(t.percent,`Percentagem da parcela`),0n)>100000000n)))throw Error(`${e.label}: declare encomendas e prazos de entrega para todos os ${t} meses.`);return{opening:r,orders:i.slice(0,t).map((t,n)=>({amount:J(t.amount,`${e.label}: compra para existencias, mes ${n+1}`),leadMonths:t.leadMonths,paymentLagMonths:t.paymentLagMonths??0,paymentInstallments:t.paymentInstallments??[{lagMonths:t.paymentLagMonths??0,percent:`100`}]}))}}),C=Array(t).fill(0n),w=Array(t).fill(0n);for(let e of x)for(let n=0;n<t;n++)C[n]+=ke(e.units[n],e.prices[n]),w[n]+=ke(e.units[n],e.costs[n]);let T=C.reduce((e,t)=>e+t,0n),E=w.reduce((e,t)=>e+t,0n),D=J(e.monthlyCollections,`CobranÃ§as mensais`),O=J(e.monthlyVariableCostPayments,`Pagamentos de compras`),k=e.monthlyInventoryPurchases?.trim()?J(e.monthlyInventoryPurchases,`Compras mensais para existÃªncias`):null,A=a?Array.from({length:t},(e,t)=>S.reduce((e,n)=>e+n.orders[t].amount,0n)):i?r.slice(0,t).map((e,t)=>J(e.amount,`Compras para existências, mês ${t+1}`)):k===null?null:Array(t).fill(k),j=a?Array(t).fill(0):i?r.slice(0,t).map(e=>e.leadMonths):Array(t).fill(n),M=A!==null,N=J(e.monthlyOperatingExpenses,`Despesas operacionais`),P=(e,n,r)=>{if(e===void 0)return Array(t).fill(n);if(!Array.isArray(e)||e.length<t||e.length>60)throw Error(`${r}: a agenda deve cobrir os ${t} meses e ter no maximo 60 meses.`);return e.slice(0,t).map((e,t)=>J(e,`${r}, mes ${t+1}`))},F=Array(t).fill(0n),I=0n,L=o?e.products.map((e,n)=>S[n].orders.flatMap((e,n)=>{let r=e.amount,i=e.paymentInstallments.map(i=>{let a=Z(i.percent,`Percentagem da parcela`),o=(e.amount*a+50000000n)/100000000n,s=o>r?r:o;r-=s;let c=n+1+i.lagMonths,l=c<=t;return l?F[c-1]+=s:I+=s,{orderMonth:n+1,paymentMonth:c,percent:i.percent,amount:Y(s),paidWithinHorizon:l}});return r>0n&&(I+=r,i.push({orderMonth:n+1,paymentMonth:null,percent:`remaining`,amount:Y(r),paidWithinHorizon:!1})),i})):null,R=o?F:P(e.monthlyVariableCostPaymentsByPeriod??void 0,O,`Pagamentos de compras`),z=P(e.monthlyOperatingExpensesByPeriod,N,`Despesas operacionais`),ee=J(e.monthlyOperatingPayments,`Pagamentos operacionais`),te=P(e.monthlyOperatingPaymentsByPeriod,ee,`Pagamentos operacionais`),ne=J(e.monthlyPayrollExpense,`Despesa com pessoal`),re=P(e.monthlyPayrollExpenseByPeriod,ne,`Despesa com pessoal`),ie=J(e.monthlyPayrollPayments,`Pagamentos de pessoal`),ae=P(e.monthlyPayrollPaymentsByPeriod,ie,`Pagamentos de pessoal`),oe=J(e.assetInvestment,`Investimento em activos`),se=J(e.inventory,`ExistÃªncias iniciais`),ce=S.reduce((e,t)=>e+(t.opening??0n),0n);if(a&&ce!==se)throw Error(`A soma das existencias iniciais por produto deve coincidir com as existencias iniciais do plano.`);let B=J(e.receivables,`Valores a receber`),le=J(e.payables,`Valores a pagar`),ue=J(e.equity,`Capital prÃ³prio`),de=J(e.shareholderLoans,`Suprimentos`),V=J(e.bankLoanProceeds,`EmprÃ©stimos recebidos`),H=J(e.grants,`SubvenÃ§Ãµes`),fe=J(e.assetDepreciation,`Base contabilÃ­stica dos activos`),pe=J(e.monthlyInterestExpense,`Juros reconhecidos`),me=J(e.monthlyInterestPayment,`Pagamento de juros`),he=J(e.monthlyPrincipalRepayment,`Reembolso de capital`),ge=se+B-le,_e=oe+ge,ve=ue+de+V+H,ye=_e-ve,be=(fe+BigInt(e.depreciationLifeMonths)/2n)/BigInt(e.depreciationLifeMonths),U=J(e.openingCash,`Saldo inicial`,!0),W=U+ve-_e,G=se,xe=0n,Se=0n,Ce=0n,K=0n,we=0n,q=0n,Ee=0n,De=0n,je=0n,Me=0n,Ne=0n,Pe=new Map,Fe=a?S.map(e=>({balance:e.opening,inTransit:0n,arrivals:new Map,totalReceipts:0n,totalShortfall:0n,monthlyRows:[]})):[],Ie=[],Le=u===null?0n:(B*f+50000000n)/100000000n,Q=new Map,Re=[],ze=B-Le;p.forEach((e,t)=>{let n=(B*h[t]+50000000n)/100000000n,r=n>ze?ze:n;ze-=r,Q.set(e.month,(Q.get(e.month)??0n)+r),Re.push({month:e.month,percent:e.percent,amount:r})});let Be=B,Ve=[];for(let n=1;n<=t;n++){let t=R[n-1],r=z[n-1],i=te[n-1],o=re[n-1],c=ae[n-1],d=C[n-1],f=w[n-1],p=G,m=null,h=null,g=null,_=null,y=[];if(M){let t=A[n-1],r=j[n-1];if(a)g=0n,m=0n,h=0n,xe=0n,y=x.map((t,r)=>{let i=Fe[r],a=S[r].orders[n-1],o=n+a.leadMonths;i.arrivals.set(o,(i.arrivals.get(o)??0n)+a.amount);let s=i.arrivals.get(n)??0n;i.arrivals.delete(n),i.inTransit+=a.amount-s;let c=ke(t.units[n-1],t.costs[n-1]),l=i.balance+s,u=c>l?c-l:0n;return i.balance=l>c?l-c:0n,i.totalReceipts+=s,i.totalShortfall+=u,g+=s,m+=u,h+=i.balance,xe+=i.inTransit,{label:e.products[r].label,opening:Y(l-s),purchases:Y(a.amount),leadMonths:a.leadMonths,paymentLagMonths:a.paymentLagMonths,receipts:Y(s),inTransit:Y(i.inTransit),consumption:Y(c),shortfall:Y(u),closing:Y(i.balance)}}),Fe.forEach((e,t)=>{e.monthlyRows.push({month:n,...y[t]})}),Se+=g,Ce+=m,G=h,_=xe;else{let e=n+r;Pe.set(e,(Pe.get(e)??0n)+t),g=Pe.get(n)??0n,Pe.delete(n),xe+=t-g,Se+=g;let i=p+g;m=f>i?f-i:0n,h=i>f?i-f:0n,G=h,_=xe,Ce+=m}}let b=n<e.depreciationLifeMonths?be:n===e.depreciationLifeMonths?fe-be*BigInt(e.depreciationLifeMonths-1):0n,T=d-f-r-o-b,E=T-pe,O=null,k=null,N=null;if(s!==null){let e=n+s,t=(d*l+50000000n)/100000000n;Ie.push({dueMonth:e,balance:d}),Me+=d,k=0n;for(let e of Ie){if(e.dueMonth!==n||e.balance===0n)continue;let r=e.balance<t?e.balance:t;e.balance-=r,Me-=r,k+=r}let r=v.get(n)??0n,i=(Ie.filter(e=>e.dueMonth<n).reduce((e,t)=>e+t.balance,0n)*r+50000000n)/100000000n;N=i;for(let e of Ie){if(e.dueMonth>=n||i<=0n)continue;let t=e.balance<i?e.balance:i;e.balance-=t,i-=t}N-=i,Me-=N,O=k+N,Ee+=k,De+=N,q+=O}let P=D+(O??0n),F=(n===u?Le:0n)+(Q.get(n)??0n);Be-=F;let I=P+F,L=t+i+c+me+he,ee=I-L;W+=ee,K+=E,we+=I,je+=F,Ne+=L,Ve.push({month:n,revenue:Y(d),cashCollections:Y(I),openingReceivablesBalance:Y(Be),openingReceivablesCollections:Y(F),salesCollections:O===null?null:Y(O),salesScheduledCollections:k===null?null:Y(k),salesRecoveryCollections:N===null?null:Y(N),otherCollections:O===null?null:Y(D),salesReceivablesClosing:O===null?null:Y(Me),variableCost:Y(f),inventoryOpening:M?Y(p):null,inventoryPurchases:M?Y(A[n-1]):null,inventoryLeadMonths:M&&!a?j[n-1]:null,inventoryReceipts:g===null?null:Y(g),inventoryInTransit:_===null?null:Y(_),inventoryConsumption:Y(f),inventoryClosing:h===null?null:Y(h),inventoryShortfall:m===null?null:Y(m),operatingExpenses:Y(r),payrollExpense:Y(o),depreciation:Y(b),interestExpense:Y(pe),operatingResult:Y(T),profitBeforeTax:Y(E),variableCostPayments:Y(t),operatingPayments:Y(i),payrollPayments:Y(c),interestPayment:Y(me),principalRepayment:Y(he),netCashFlow:Y(ee),closingCash:Y(W)})}let $=M?{status:Ce>0n?`estimated_with_shortfall`:`estimated`,leadMonths:i||a?null:n,openingInventory:Y(se),monthlyPurchases:i||a?null:Y(k),purchaseSchedule:i||a?A.map((e,t)=>({month:t+1,amount:Y(e),leadMonths:a?null:j[t]})):null,totalPurchases:Y(A.reduce((e,t)=>e+t,0n)),totalReceipts:Y(Se),totalConsumption:Y(E),endingInventory:Y(G),inTransitAtEnd:Y(xe),totalShortfall:Y(Ce),productSchedules:a?x.map((t,n)=>({label:e.products[n].label,openingInventory:Y(S[n].opening),purchaseSchedule:S[n].orders.map((e,t)=>({month:t+1,amount:Y(e.amount),leadMonths:e.leadMonths,paymentLagMonths:e.paymentLagMonths})),paymentSchedule:L?.[n]??null,totalPurchases:Y(S[n].orders.reduce((e,t)=>e+t.amount,0n)),totalReceipts:Y(Fe[n].totalReceipts),totalConsumption:Y(t.units.reduce((e,n,r)=>e+ke(n,t.costs[r]),0n)),endingInventory:Y(Fe[n].balance),inTransitAtEnd:Y(Fe[n].inTransit),totalShortfall:Y(Fe[n].totalShortfall),monthlyRows:Fe[n].monthlyRows})):null}:{status:`indeterminate`,leadMonths:i||a?null:n,openingInventory:Y(se),monthlyPurchases:null,purchaseSchedule:null,totalPurchases:null,totalReceipts:null,totalConsumption:Y(E),endingInventory:null,inTransitAtEnd:null,totalShortfall:null,productSchedules:null},He={currency:e.currency,workingCapital:Y(ge),initialUses:Y(_e),financing:Y(ve),fundingGap:Y(ye),fundingStatus:ye>0n?`shortfall`:ye<0n?`surplus`:`balanced`,openingReceivables:Y(B),openingCashAfterInitialUses:Y(U+ve-_e),totalRevenue:Y(T),totalCashCollections:Y(we),totalOpeningReceivablesCollections:Y(je),openingReceivablesAtEnd:Y(Be),openingReceivablesCollectionMonth:u,openingReceivablesCollectionPercent:u===null?null:d,openingReceivablesInstallments:Re.map(e=>({month:e.month,percent:e.percent,amount:Y(e.amount)})),totalSalesCollections:s===null?null:Y(q),totalScheduledSalesCollections:s===null?null:Y(Ee),totalSalesRecoveryCollections:s===null?null:Y(De),salesReceivablesAtEnd:s===null?null:Y(Me),salesCollectionLagMonths:s,salesCollectionPercent:s===null?null:c,totalPayments:Y(Ne),supplierPaymentsOutstandingAtEnd:o?Y(I):null,totalProfitBeforeTax:Y(K),endingCash:Y(W),inventoryProjection:$,rows:Ve,status:`estimated`},Ue=b===null?null:{currency:y,rate:e.fxRate,date:e.fxDate,source:e.fxSource.trim(),workingCapital:Y(X(ge,b,100000000n)),initialUses:Y(X(_e,b,100000000n)),financing:Y(X(ve,b,100000000n)),fundingGap:Y(X(ye,b,100000000n)),fundingStatus:He.fundingStatus,totalRevenue:Y(X(T,b,100000000n)),totalCashCollections:Y(X(we,b,100000000n)),totalOpeningReceivablesCollections:Y(X(je,b,100000000n)),openingReceivablesAtEnd:Y(X(B-je,b,100000000n)),openingReceivablesInstallments:He.openingReceivablesInstallments?.map(e=>({...e,amount:Y(X(J(e.amount,`Parcela de recebÃ­veis`),b,100000000n))}))??[],totalSalesCollections:He.totalSalesCollections===null?null:Y(X(q,b,100000000n)),totalScheduledSalesCollections:He.totalScheduledSalesCollections===null?null:Y(X(Ee,b,100000000n)),totalSalesRecoveryCollections:He.totalSalesRecoveryCollections===null?null:Y(X(De,b,100000000n)),salesReceivablesAtEnd:He.salesReceivablesAtEnd===null?null:Y(X(Me,b,100000000n)),totalPayments:Y(X(Ne,b,100000000n)),totalProfitBeforeTax:Y(X(K,b,100000000n)),endingCash:Y(X(W,b,100000000n)),inventoryProjection:{status:$.status,leadMonths:$.leadMonths,openingInventory:Y(X(J($.openingInventory,`ExistÃªncias iniciais`,!0),b,100000000n)),monthlyPurchases:$.monthlyPurchases===null?null:Y(X(J($.monthlyPurchases,`Compras para existÃªncias`,!0),b,100000000n)),totalPurchases:$.totalPurchases===null?null:Y(X(J($.totalPurchases,`Compras totais`,!0),b,100000000n)),totalReceipts:$.totalReceipts===null?null:Y(X(J($.totalReceipts,`RecepÃ§Ãµes totais`,!0),b,100000000n)),totalConsumption:Y(X(J($.totalConsumption,`Consumo total`,!0),b,100000000n)),endingInventory:$.endingInventory===null?null:Y(X(J($.endingInventory,`ExistÃªncias finais`,!0),b,100000000n)),inTransitAtEnd:$.inTransitAtEnd===null?null:Y(X(J($.inTransitAtEnd,`ExistÃªncias em trÃ¢nsito`,!0),b,100000000n)),totalShortfall:$.totalShortfall===null?null:Y(X(J($.totalShortfall,`Falta de stock`,!0),b,100000000n))},rows:Ve.map(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,e===`month`||t===null?t:Y(X(J(String(t),e,!0),b,100000000n))])))};return{...He,presentationCurrency:y,conversion:Ue}}function Le(e,t=new Date().toISOString()){let n=Ie(e),r=[[`Rendimentos facturados`,`income`,`revenue`],[`Custo variÃ¡vel dos produtos`,`expense`,`variableCost`],[`Despesas operacionais reconhecidas`,`expense`,`operatingExpenses`],[`Despesas com pessoal reconhecidas`,`expense`,`payrollExpense`],[`DepreciaÃ§Ã£o contabilÃ­stica`,`expense`,`depreciation`],[`Juros reconhecidos`,`expense`,`interestExpense`]].map(([e,t,r])=>{let i=n.rows.map(e=>({period:e.month,amount:e[r]}));return[e,t,Y(i.reduce((t,n)=>t+J(n.amount,e,!0),0n)),`unclassified`,JSON.stringify(i)]}),i=null;if(e.scenarioAdjustments){let t=[...Object.values(e.scenarioAdjustments.favorable),...Object.values(e.scenarioAdjustments.unfavorable)],n=t.some(e=>e!==``);if(n&&t.every(e=>e!==``))i=Fe(e);else if(n)throw Error(`Complete ou limpe todas as variaÃ§Ãµes antes de exportar os cenÃ¡rios.`)}return`\uFEFF${[[`RelatÃ³rio`,`Plano financeiro empresarial indicativo`],[`VersÃ£o do modelo`,`business-plan-v13`],[`Prazo de cobranÃ§a das vendas`,e.salesCollectionLagMonths===null||e.salesCollectionLagMonths===void 0?`agenda manual`:`${e.salesCollectionLagMonths} meses`],[`Percentagem cobrada no prazo declarado`,e.salesCollectionLagMonths===null||e.salesCollectionLagMonths===void 0?`nÃ£o aplicÃ¡vel; modo manual`:`${e.salesCollectionPercent??`100`}%`],[`Agenda de recuperação de vendas vencidas`,JSON.stringify(e.salesRecoverySchedule??[])],[`MÃªs de cobranÃ§a dos valores a receber de abertura`,n.openingReceivablesCollectionMonth??`sem previsÃ£o declarada`],[`Percentagem de cobranÃ§a dos valores de abertura`,n.openingReceivablesCollectionPercent===null?`nÃ£o aplicÃ¡vel`:`${n.openingReceivablesCollectionPercent}%`],[`Parcelas adicionais de recebÃ­veis de abertura`,JSON.stringify(n.openingReceivablesInstallments)],[`Data de exportaÃ§Ã£o`,t],[`Horizonte`,`${e.periods??12} meses`],[`Moeda de cÃ¡lculo`,n.currency],[`Moeda de apresentaÃ§Ã£o`,n.presentationCurrency],[`Fonte dos pressupostos`,`Valores introduzidos pelo utilizador`],[`FacturaÃ§Ã£o`,`unidades mensais Ã— preÃ§o unitÃ¡rio`],[`Custo variÃ¡vel`,`unidades mensais Ã— custo variÃ¡vel unitÃ¡rio`],[`Compras mensais para existÃªncias`,e.monthlyInventoryPurchases?.trim()||`nÃ£o fornecidas; projeÃ§Ã£o de existÃªncias indeterminada`],[`Prazo de entrega das compras`,`${e.inventoryPurchaseLeadMonths??0} meses`],[`Movimento simplificado de existÃªncias`,`saldo inicial + recepÃ§Ãµes de compras âˆ’ consumo mensal; encomendas chegam apÃ³s o prazo de entrega; nÃ£o reduz as vendas planeadas perante falta de stock`],[`Resultado antes de impostos`,`facturaÃ§Ã£o âˆ’ custo variÃ¡vel âˆ’ despesas operacionais âˆ’ pessoal âˆ’ depreciaÃ§Ã£o contabilÃ­stica âˆ’ juros reconhecidos`],[`Fluxo de caixa`,`cobranÃ§as âˆ’ pagamentos de compras âˆ’ pagamentos operacionais âˆ’ pessoal âˆ’ juros pagos âˆ’ capital reembolsado`],[`DepreciaÃ§Ã£o`,`base contabilÃ­stica / vida Ãºtil em meses; residual reconciliado no Ãºltimo mÃªs`],[`Impostos`,`nÃ£o calculados nem incluÃ­dos`],[`Uso inicial`,`activos + existÃªncias + valores a receber âˆ’ valores a pagar`],[`Fontes iniciais`,`capital prÃ³prio + suprimentos + emprÃ©stimos + subvenÃ§Ãµes`],[`Taxa de cÃ¢mbio`,n.conversion?n.conversion.rate:`nÃ£o aplicada`],[`Data da taxa de cÃ¢mbio`,n.conversion?.date??`nÃ£o aplicada`],[`Fonte da taxa de cÃ¢mbio`,n.conversion?.source??`nÃ£o aplicada`],[],[`Pressupostos por produto/serviÃ§o`],[`Produto/serviÃ§o`,`Unidades por mes (JSON; extras preservados)`,`Precos unitarios por mes (JSON; vazio = constante)`,`Custos unitarios por mes (JSON; vazio = constante)`],...e.products.map(e=>[e.label,e.monthlyUnitsByPeriod?JSON.stringify(e.monthlyUnitsByPeriod):e.monthlyUnits,e.unitPriceByPeriod?JSON.stringify(e.unitPriceByPeriod):e.unitPrice,e.unitVariableCostByPeriod?JSON.stringify(e.unitVariableCostByPeriod):e.unitVariableCost]),[],[`Pressupostos mensais de despesas e pessoal`],[`Despesas operacionais reconhecidas por mes (JSON; vazio = constante)`,JSON.stringify(e.monthlyOperatingExpensesByPeriod??[])],[`Pagamentos operacionais por mes (JSON; vazio = constante)`,JSON.stringify(e.monthlyOperatingPaymentsByPeriod??[])],[`Despesas de pessoal reconhecidas por mes (JSON; vazio = constante)`,JSON.stringify(e.monthlyPayrollExpenseByPeriod??[])],[`Pagamentos de pessoal por mes (JSON; vazio = constante)`,JSON.stringify(e.monthlyPayrollPaymentsByPeriod??[])],[],[`Resumo`,n.currency],[`Fundo de maneio lÃ­quido`,n.workingCapital],[`Usos iniciais`,n.initialUses],[`Fontes de financiamento`,n.financing],[`Estado da reconciliaÃ§Ã£o do financiamento`,n.fundingStatus],[`DiferenÃ§a entre usos e fontes`,n.fundingGap],[`FacturaÃ§Ã£o no horizonte`,n.totalRevenue],[`CobranÃ§as no horizonte`,n.totalCashCollections],[`CobranÃ§a de valores a receber de abertura`,n.totalOpeningReceivablesCollections],[`Valores de abertura por receber no fim`,n.openingReceivablesAtEnd],[`CobranÃ§as da facturaÃ§Ã£o modelada`,n.totalSalesCollections??`agenda manual`],[`FacturaÃ§Ã£o por cobrar no fim`,n.salesReceivablesAtEnd??`agenda manual`],[`Resultado antes de impostos`,n.totalProfitBeforeTax],[`Pagamentos a fornecedores fora do horizonte`,n.supplierPaymentsOutstandingAtEnd??`nao aplicavel`],[`Ponte contabilÃ­stico-fiscal`,`incomplete`],[`MatÃ©ria colectÃ¡vel`,`indeterminate`],[`Entradas fiscais em falta`,`expense_deductibility_classification; approved_tax_adjustments; applicable_tax_period; approved_effective_rule`],[`Resultado contabilÃ­stico antes de impostos (ponte)`,n.totalProfitBeforeTax],[],[`Linhas contabilÃ­sticas para classificaÃ§Ã£o fiscal`,`Efeito`,`Total`,`Tratamento fiscal`,`Valores mensais`],...r,[`Capital reembolsado`,`fluxo de caixa; excluÃ­do das despesas contabilÃ­sticas`,``,`nÃ£o aplicÃ¡vel Ã\xA0 ponte de resultado`,``],[`Caixa final projectada`,n.endingCash],[`ProjecÃ§Ã£o de existÃªncias`,n.inventoryProjection.status],[`ExistÃªncias finais`,n.inventoryProjection.endingInventory??`indeterminadas`],[`ExistÃªncias em trÃ¢nsito no fim do horizonte`,n.inventoryProjection.inTransitAtEnd??`indeterminadas`],[`RecepÃ§Ãµes de compras no horizonte`,n.inventoryProjection.totalReceipts??`indeterminadas`],[`Falta total de stock estimada`,n.inventoryProjection.totalShortfall??`indeterminada`],...n.inventoryProjection.purchaseSchedule?[[`Agenda mensal de compras e recepção`,JSON.stringify(n.inventoryProjection.purchaseSchedule)]]:[],...n.inventoryProjection.productSchedules?[[],[`Existencias por produto`,`Mes`,`Inicial`,`Encomendas`,`Prazo de entrega`,`Recepcoes`,`Em transito`,`Consumo`,`Falta`,`Final`],...n.inventoryProjection.productSchedules.flatMap(e=>e.monthlyRows.map(t=>[e.label,t.month,t.opening,t.purchases,t.leadMonths,t.receipts,t.inTransit,t.consumption,t.shortfall,t.closing]))]:[],...n.inventoryProjection.productSchedules?.some(e=>e.paymentSchedule!==null)?[[],[`Pagamentos a fornecedores por prazo declarado`,`Produto`,`Mes da encomenda`,`Mes de pagamento`,`Percentagem`,`Montante`,`Situacao no horizonte`],...n.inventoryProjection.productSchedules.flatMap(e=>e.paymentSchedule?.map(t=>[e.label,t.orderMonth,t.paymentMonth??`sem prazo declarado`,t.percent===`remaining`?`saldo nao alocado`:t.percent,t.amount,t.paidWithinHorizon?`incluido no horizonte`:`por pagar`])??[])]:[],...i?[[],[`ComparaÃ§Ã£o de cenÃ¡rios`,`Valores na moeda de cÃ¡lculo`],[`CenÃ¡rio`,`FacturaÃ§Ã£o`,`Resultado antes impostos`,`Caixa final`,`ExistÃªncias finais`,`Falta de stock`],[`Base`,i.base.totalRevenue,i.base.totalProfitBeforeTax,i.base.endingCash,i.base.inventoryProjection.endingInventory??`indeterminadas`,i.base.inventoryProjection.totalShortfall??`indeterminada`],[`FavorÃ¡vel`,`VariaÃ§Ãµes`,JSON.stringify(i.favorable.adjustments),i.favorable.result.totalRevenue,i.favorable.result.totalProfitBeforeTax,i.favorable.result.endingCash,i.favorable.result.inventoryProjection.endingInventory??`indeterminadas`,i.favorable.result.inventoryProjection.totalShortfall??`indeterminada`],[`DesfavorÃ¡vel`,`VariaÃ§Ãµes`,JSON.stringify(i.unfavorable.adjustments),i.unfavorable.result.totalRevenue,i.unfavorable.result.totalProfitBeforeTax,i.unfavorable.result.endingCash,i.unfavorable.result.inventoryProjection.endingInventory??`indeterminadas`,i.unfavorable.result.inventoryProjection.totalShortfall??`indeterminada`]]:[],...n.conversion?[[],[`Resumo convertido`,n.conversion.currency],[`Fundo de maneio lÃ­quido`,n.conversion.workingCapital],[`Usos iniciais`,n.conversion.initialUses],[`Fontes de financiamento`,n.conversion.financing],[`Estado da reconciliaÃ§Ã£o do financiamento`,n.conversion.fundingStatus],[`DiferenÃ§a entre usos e fontes`,n.conversion.fundingGap],[`FacturaÃ§Ã£o no horizonte`,n.conversion.totalRevenue],[`CobranÃ§as no horizonte`,n.conversion.totalCashCollections],[`CobranÃ§a de valores a receber de abertura`,n.conversion.totalOpeningReceivablesCollections],[`Valores de abertura por receber no fim`,n.conversion.openingReceivablesAtEnd],[`Resultado antes de impostos`,n.conversion.totalProfitBeforeTax],[`Caixa final projectada`,n.conversion.endingCash]]:[],[],`MÃªs.FacturaÃ§Ã£o.CobranÃ§as.CobranÃ§as de vendas.CobranÃ§as iniciais das vendas.RecuperaÃ§Ãµes de vendas vencidas.CobranÃ§a de valores de abertura.Valores de abertura por receber.Outras cobranÃ§as.Custo variÃ¡vel/consumo.ExistÃªncias iniciais.Encomendas para existÃªncias.Prazo da encomenda (meses).RecepÃ§Ãµes de compras.ExistÃªncias em trÃ¢nsito.ExistÃªncias finais.Falta de stock.Despesas operacionais.Pagamentos operacionais.Pessoal.Pagamentos de pessoal.DepreciaÃ§Ã£o.Juros.Pagamento de juros.Pagamento de compras.Resultado antes impostos.Pagamento capital.Fluxo lÃ­quido.Caixa final`.split(`.`),...n.rows.map(e=>[e.month,e.revenue,e.cashCollections,e.salesCollections??`agenda manual`,e.salesScheduledCollections??`agenda manual`,e.salesRecoveryCollections??`agenda manual`,e.openingReceivablesCollections,e.openingReceivablesBalance,e.otherCollections??`incluÃ­das nas cobranÃ§as manuais`,e.variableCost,e.inventoryOpening??`indeterminado`,e.inventoryPurchases??`indeterminadas`,e.inventoryLeadMonths??`indeterminado`,e.inventoryReceipts??`indeterminadas`,e.inventoryInTransit??`indeterminadas`,e.inventoryClosing??`indeterminadas`,e.inventoryShortfall??`indeterminada`,e.operatingExpenses,e.operatingPayments,e.payrollExpense,e.payrollPayments,e.depreciation,e.interestExpense,e.interestPayment,e.variableCostPayments,e.profitBeforeTax,e.principalRepayment,e.netCashFlow,e.closingCash]),...n.conversion?[[],[`MÃªs convertido`,`FacturaÃ§Ã£o`,`CobranÃ§as`,`CobranÃ§as de vendas`,`CobranÃ§as iniciais das vendas`,`RecuperaÃ§Ãµes de vendas vencidas`,`CobranÃ§a de valores de abertura`,`Valores de abertura por receber`,`Outras cobranÃ§as`,`Resultado antes impostos`,`Fluxo lÃ­quido`,`Caixa final`],...n.conversion.rows.map(e=>[e.month??``,e.revenue??``,e.cashCollections??``,e.salesCollections??`agenda manual`,e.salesScheduledCollections??``,e.salesRecoveryCollections??``,e.openingReceivablesCollections??``,e.openingReceivablesBalance??``,e.otherCollections??`incluÃ­das nas cobranÃ§as manuais`,e.profitBeforeTax??``,e.netCashFlow??``,e.closingCash??``])]:[],[],[`LimitaÃ§Ãµes`,`Estimativa sem aconselhamento fiscal, parÃ¢metros legais, sazonalidade, inflaÃ§Ã£o ou validaÃ§Ã£o contabilÃ­stica. Moeda original preservada.`]].map(e=>e.map(p).join(`,`)).join(`\r
`)}`}function Q(e){let t=/^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(e);if(!t)throw Error(`O resultado financeiro contém um montante inválido.`);let n=BigInt(t[2])*100n+BigInt((t[3]??``).padEnd(2,`0`)||`0`);return t[1]?-n:n}function Re(e){let t=e<0n?-e:e;return`${e<0n?`-`:``}${t/100n}.${String(t%100n).padStart(2,`0`)}`}function ze(e){if(e.rows.length===0)throw Error(`A previsão financeira não contém períodos para mapear.`);let t=0n,n=0n,r=0n,i=0n,a=Q(e.openingCashAfterInitialUses),o=Q(e.openingReceivables),s=0n,c=0;for(let l of e.rows){if(!Number.isSafeInteger(l.month)||l.month<=c)throw Error(`Os períodos da previsão financeira não estão em ordem.`);c=l.month;let e=Q(String(l.revenue));n+=e,t+=e;for(let e of[`variableCost`,`operatingExpenses`,`payrollExpense`,`depreciation`,`interestExpense`])t-=Q(String(l[e]));let u=l.salesCollections===null?0n:Q(String(l.salesCollections)),d=Q(String(l.openingReceivablesCollections)),f=Q(String(l.openingReceivablesBalance));if(f!==o-d)throw Error(`O saldo de recebíveis de abertura não reconcilia com as cobranças do período.`);o=f,s+=d;let p=l.otherCollections===null?Q(String(l.cashCollections))-u-d:Q(String(l.otherCollections));if(p<0n)throw Error(`A previsão financeira contém cobranças reconciliadas inválidas.`);let m=Q(String(l.cashCollections));if(m!==u+d+p)throw Error(`As cobranças mensais não reconciliam com as suas origens.`);r+=m;let h=m-Q(String(l.variableCostPayments))-Q(String(l.operatingPayments))-Q(String(l.payrollPayments))-Q(String(l.interestPayment))-Q(String(l.principalRepayment));if(h!==Q(String(l.netCashFlow)))throw Error(`O fluxo líquido mensal não reconcilia com recebimentos e pagamentos.`);let g=Q(String(l.closingCash));if(g!==a+h)throw Error(`O saldo de caixa mensal não reconcilia com o período anterior.`);a=g,i+=h}if(t!==Q(e.totalProfitBeforeTax))throw Error(`O resultado contabilístico não reconcilia com as linhas mapeadas.`);if(n!==Q(e.totalRevenue))throw Error(`A facturação total não reconcilia com os períodos mapeados.`);if(r!==Q(e.totalCashCollections))throw Error(`As cobranças totais não reconciliam com o calendário de caixa.`);if(s!==Q(e.totalOpeningReceivablesCollections)||o!==Q(e.openingReceivablesAtEnd))throw Error(`Os recebíveis de abertura não reconciliam com a previsão final.`);if(a!==Q(e.endingCash)||i!==Q(e.endingCash)-Q(e.openingCashAfterInitialUses))throw Error(`O saldo final de caixa não reconcilia com o calendário mensal.`)}function Be(e){ze(e);let t=[{code:`revenue`,origin:`Produtos/serviços facturados`,accountingEffect:`income`,taxTreatment:`unclassified`,field:`revenue`},{code:`cost_of_sales`,origin:`Custo variável dos produtos`,accountingEffect:`expense`,taxTreatment:`unclassified`,field:`variableCost`},{code:`operating_expenses`,origin:`Despesas operacionais reconhecidas`,accountingEffect:`expense`,taxTreatment:`unclassified`,field:`operatingExpenses`},{code:`personnel`,origin:`Despesas com pessoal reconhecidas`,accountingEffect:`expense`,taxTreatment:`unclassified`,field:`payrollExpense`},{code:`depreciation`,origin:`Depreciação contabilística`,accountingEffect:`expense`,taxTreatment:`unclassified`,field:`depreciation`},{code:`interest_expense`,origin:`Juros reconhecidos`,accountingEffect:`expense`,taxTreatment:`unclassified`,field:`interestExpense`}].map(({field:t,...n})=>{let r=e.rows.map(e=>({period:e.month,amount:String(e[t])}));return{...n,total:Re(r.reduce((e,t)=>e+Q(t.amount),0n)),monthlyAmounts:r}});return{status:`incomplete`,currency:e.currency,accountingProfitBeforeTax:e.totalProfitBeforeTax,taxableBase:{status:`indeterminate`,amount:null,missingInputs:[`expense_deductibility_classification`,`approved_tax_adjustments`,`applicable_tax_period`,`approved_effective_rule`]},accountingLines:t,cashSchedule:e.rows.map(e=>({period:e.month,collectionMode:e.salesCollections===null?`manual`:`scheduled`,salesCollections:e.salesCollections,openingReceivablesCollections:e.openingReceivablesCollections,openingReceivablesBalance:e.openingReceivablesBalance,otherCollections:e.otherCollections??Re(Q(e.cashCollections)-(e.salesCollections===null?0n:Q(e.salesCollections))-Q(e.openingReceivablesCollections)),collections:e.cashCollections,collectionsTotal:e.cashCollections,salesReceivablesBalance:e.salesReceivablesClosing,supplierPayments:e.variableCostPayments,operatingPayments:e.operatingPayments,personnelPayments:e.payrollPayments,interestPayments:e.interestPayment,principalRepayments:e.principalRepayment,netCashFlow:e.netCashFlow,closingCash:e.closingCash})),notes:[`A classificação fiscal das linhas contabilísticas está pendente; este mapeamento não afirma dedutibilidade.`,`Cobranças e pagamentos são fluxos de caixa separados das receitas e despesas reconhecidas.`,`Reembolsos de capital aparecem apenas no calendário de caixa e não como despesa contabilística.`,`Nenhum imposto, contribuição, retenção ou pagamento fiscal é somado como zero ou estimado nesta ponte.`]}}var Ve={currency:``,presentationCurrency:``,fxRate:``,fxDate:``,fxSource:``,openingCash:`0`,products:[{label:`Produto ou serviço`,monthlyUnits:`100`,unitPrice:`1000`,unitVariableCost:`400`}],monthlyCollections:`100000`,salesCollectionLagMonths:null,salesCollectionPercent:`100`,salesRecoverySchedule:[],openingReceivablesCollectionMonth:null,openingReceivablesCollectionPercent:`100`,openingReceivablesInstallments:[],monthlyVariableCostPayments:`40000`,monthlyVariableCostPaymentsByPeriod:null,monthlyInventoryPurchases:`40000`,inventoryPurchaseLeadMonths:0,inventoryPurchaseSchedule:null,useInventoryPurchaseSchedule:!1,useProductInventorySchedule:!1,useSupplierPaymentTerms:!1,monthlyOperatingExpenses:`20000`,monthlyOperatingPayments:`20000`,monthlyPayrollExpense:`15000`,monthlyPayrollPayments:`15000`,assetInvestment:`100000`,inventory:`20000`,receivables:`10000`,payables:`5000`,equity:`80000`,shareholderLoans:`0`,bankLoanProceeds:`50000`,grants:`0`,assetDepreciation:`100000`,depreciationLifeMonths:60,monthlyInterestExpense:`0`,monthlyInterestPayment:`0`,monthlyPrincipalRepayment:`0`,periods:12};function $({label:e,value:t,onChange:n,allowNegative:r=!1}){return(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[e,(0,V.jsx)(`input`,{type:`number`,min:r?void 0:`0`,step:`0.01`,value:t,onChange:e=>n(e.target.value),className:`mt-1 w-full rounded border p-2`})]})}function He(e){let t=(0,f.c)(214),{currency:n,snapshot:r,onCurrencyChange:i,onSnapshotChange:a}=e,o=typeof r==`string`&&r.length>6e4,[s,c]=(0,d.useState)(o?`O snapshot guardado excede 60 KB e nao pode ser carregado com seguranca. O formulario nao o vai substituir.`:``),[l,u]=(0,d.useState)(null),p;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(p=()=>u(null),t[0]=p):p=t[0];let m;if(t[1]===r?m=t[2]:(m=[r],t[1]=r,t[2]=m),(0,d.useEffect)(p,m),o){let e;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,V.jsx)(`summary`,{className:`cursor-pointer text-lg font-semibold`,children:`Plano financeiro empresarial`}),t[3]=e):e=t[3];let n;return t[4]===s?n=t[5]:(n=(0,V.jsxs)(`details`,{className:`rounded-lg border border-slate-300 p-4`,open:!0,children:[e,(0,V.jsx)(`p`,{role:`alert`,className:`my-3 rounded border border-red-300 p-3 text-sm text-red-900`,children:s})]}),t[4]=s,t[5]=n),n}let h;t[6]!==o||t[7]!==a?(h=e=>{if(!o){u(e);try{a(Ee(e)),c(``)}catch(e){let t=e;c(t instanceof Error?t.message:`Nao foi possivel guardar o plano financeiro.`)}}},t[6]=o,t[7]=a,t[8]=h):h=t[8];let g=h,_;if(t[9]!==n||t[10]!==i||t[11]!==g||t[12]!==r||t[13]!==s||t[14]!==l){let e=[{key:`monthlyVariableCostPaymentsByPeriod`,baseKey:`monthlyVariableCostPayments`,label:`Pagamento de compras/variáveis`},{key:`monthlyOperatingExpensesByPeriod`,baseKey:`monthlyOperatingExpenses`,label:`Despesas operacionais reconhecidas`},{key:`monthlyOperatingPaymentsByPeriod`,baseKey:`monthlyOperatingPayments`,label:`Pagamento de despesas operacionais`},{key:`monthlyPayrollExpenseByPeriod`,baseKey:`monthlyPayrollExpense`,label:`Custo de pessoal reconhecido`},{key:`monthlyPayrollPaymentsByPeriod`,baseKey:`monthlyPayrollPayments`,label:`Pagamento de pessoal`}],a;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(a={monthlyUnitsByPeriod:`monthlyUnits`,unitPriceByPeriod:`unitPrice`,unitVariableCostByPeriod:`unitVariableCost`},t[16]=a):a=t[16];let o=a,c=l??De(r)??{...Ve,currency:n},u=(e,t)=>g({...c,currency:n,[e]:t}),d=(e,t,n)=>u(`salesRecoverySchedule`,(c.salesRecoverySchedule??[]).map((r,i)=>i===e?{...r,[t]:t===`month`?Number(n):String(n)}:r)),f=(e,t,r)=>g({...c,currency:n,openingReceivablesInstallments:(c.openingReceivablesInstallments??[]).map((n,i)=>i===e?t===`month`?{...n,month:Number(r)}:{...n,percent:String(r)}:n)}),p=()=>u(`openingReceivablesInstallments`,[...c.openingReceivablesInstallments??[],{month:1,percent:`0`}]),m=e=>u(`openingReceivablesInstallments`,(c.openingReceivablesInstallments??[]).filter((t,n)=>n!==e)),h=Number.isSafeInteger(c.periods)&&(c.periods??0)>=1&&(c.periods??0)<=60?c.periods??12:12,v=t=>{let r=Number.isSafeInteger(t)?Math.max(1,Math.min(60,t)):h,i=(e,t)=>e?Array.from({length:Math.max(r,e.length)},(n,r)=>e[r]??t):void 0;g({...c,currency:n,periods:r,...Object.fromEntries(e.map(e=>{let{key:t,baseKey:n}=e;return[t,i(c[t],c[n])]})),products:c.products.map(e=>({...e,monthlyUnitsByPeriod:i(e.monthlyUnitsByPeriod,e.monthlyUnits),unitPriceByPeriod:i(e.unitPriceByPeriod,e.unitPrice),unitVariableCostByPeriod:i(e.unitVariableCostByPeriod,e.unitVariableCost),productInventoryPurchasesByPeriod:e.productInventoryPurchasesByPeriod?Array.from({length:Math.max(r,e.productInventoryPurchasesByPeriod.length)},(t,n)=>e.productInventoryPurchasesByPeriod?.[n]??{amount:`0`,leadMonths:0,...c.useSupplierPaymentTerms?{paymentLagMonths:0,paymentInstallments:[{lagMonths:0,percent:`100`}]}:{}}):null})),inventoryPurchaseSchedule:c.inventoryPurchaseSchedule?Array.from({length:Math.max(r,c.inventoryPurchaseSchedule.length)},(e,t)=>c.inventoryPurchaseSchedule?.[t]??{amount:c.monthlyInventoryPurchases??``,leadMonths:c.inventoryPurchaseLeadMonths??0}):null})},y=()=>{let e=!(c.useInventoryPurchaseSchedule??!1),t=c.inventoryPurchaseSchedule??Array.from({length:h},()=>({amount:c.monthlyInventoryPurchases??``,leadMonths:c.inventoryPurchaseLeadMonths??0}));g({...c,currency:n,inventoryPurchaseSchedule:t,useInventoryPurchaseSchedule:e})},b=()=>{let e=!(c.useProductInventorySchedule??!1);g({...c,currency:n,useProductInventorySchedule:e,useInventoryPurchaseSchedule:!e&&c.useInventoryPurchaseSchedule,useSupplierPaymentTerms:e?c.useSupplierPaymentTerms:!1,products:c.products.map(e=>({...e,productInventoryOpening:e.productInventoryOpening??``,productInventoryPurchasesByPeriod:e.productInventoryPurchasesByPeriod??Array.from({length:h},pt)}))})},x=()=>{let e=!(c.useSupplierPaymentTerms??!1);g({...c,currency:n,useInventoryPurchaseSchedule:!1,useProductInventorySchedule:!0,useSupplierPaymentTerms:e,products:c.products.map(e=>({...e,productInventoryOpening:e.productInventoryOpening??``,productInventoryPurchasesByPeriod:Array.from({length:Math.max(h,e.productInventoryPurchasesByPeriod?.length??0)},(t,n)=>({amount:e.productInventoryPurchasesByPeriod?.[n]?.amount??`0`,leadMonths:e.productInventoryPurchasesByPeriod?.[n]?.leadMonths??0,paymentLagMonths:e.productInventoryPurchasesByPeriod?.[n]?.paymentLagMonths??0,paymentInstallments:e.productInventoryPurchasesByPeriod?.[n]?.paymentInstallments??[{lagMonths:e.productInventoryPurchasesByPeriod?.[n]?.paymentLagMonths??0,percent:`100`}]}))}))})},S=(e,t,r,i)=>g({...c,currency:n,products:c.products.map((n,a)=>a===e&&n.productInventoryPurchasesByPeriod?{...n,productInventoryPurchasesByPeriod:n.productInventoryPurchasesByPeriod.map((e,n)=>n===t?{...e,[r]:r===`amount`?String(i):Number(i)}:e)}:n)}),C=(e,t,r,i,a)=>g({...c,currency:n,products:c.products.map((n,o)=>o===e&&n.productInventoryPurchasesByPeriod?{...n,productInventoryPurchasesByPeriod:n.productInventoryPurchasesByPeriod.map((e,n)=>n===t?{...e,paymentInstallments:(e.paymentInstallments??[{lagMonths:e.paymentLagMonths??0,percent:`100`}]).map((e,t)=>t===r?{...e,[i]:i===`percent`?String(a):Number(a)}:e)}:e)}:n)}),w=(e,t)=>g({...c,currency:n,products:c.products.map((n,r)=>r===e&&n.productInventoryPurchasesByPeriod?{...n,productInventoryPurchasesByPeriod:n.productInventoryPurchasesByPeriod.map((e,n)=>n===t?{...e,paymentInstallments:[...e.paymentInstallments??[{lagMonths:e.paymentLagMonths??0,percent:`100`}],{lagMonths:0,percent:`0`}]}:e)}:n)}),T=(e,t,r)=>g({...c,currency:n,products:c.products.map((n,i)=>i===e&&n.productInventoryPurchasesByPeriod?{...n,productInventoryPurchasesByPeriod:n.productInventoryPurchasesByPeriod.map((e,n)=>n===t?{...e,paymentInstallments:(e.paymentInstallments??[]).filter((e,t)=>t!==r)}:e)}:n)}),E=(e,t,r)=>g({...c,currency:n,inventoryPurchaseSchedule:(c.inventoryPurchaseSchedule??[]).map((n,i)=>i===e?{...n,[t]:t===`amount`?String(r):Number(r)}:n)}),D=(e,t)=>g({...c,currency:n,products:c.products.map((n,r)=>{if(r!==e)return n;let i={...n};if(i[t])delete i[t];else{let e=o[t];i[t]=Array.from({length:h},()=>n[e])}return i})}),O=(e,t,r,i)=>g({...c,currency:n,products:c.products.map((n,a)=>a===e&&n[t]?{...n,[t]:n[t].map((e,t)=>t===r?i:e)}:n)}),k=(e,t)=>{let n=c[e],r=c[t];!n&&typeof r!=`string`||u(e,n?void 0:Array.from({length:h},()=>r))},A=(e,t,n)=>{let r=c[e];r&&u(e,r.map((e,r)=>r===t?n:e))},j=(e,t,r)=>g({...c,currency:n,products:c.products.map((n,i)=>i===e?{...n,[t]:r}:n)}),M,N=``;try{M=Ie({...c,currency:n})}catch(e){let t=e;N=t instanceof Error?t.message:`Reveja os pressupostos introduzidos.`}let P={unitVolumePercent:``,unitPricePercent:``,unitCostPercent:``,operatingCostsPercent:``,cashCollectionsPercent:``},F=c.scenarioAdjustments??{favorable:P,unfavorable:P},I=(e,t,r)=>{g({...c,currency:n,scenarioAdjustments:{...F,[e]:{...F[e],[t]:r}}})},L=[...Object.values(F.favorable),...Object.values(F.unfavorable)],R=L.some(ft)&&!L.every(dt),z,ee=``;if(L.every(ut))try{z=Fe({...c,currency:n,scenarioAdjustments:F})}catch(e){let t=e;ee=t instanceof Error?t.message:`Verifique as variações dos cenários.`}let te=M?Be(M):null,ne;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(ne=(0,V.jsx)(`summary`,{className:`cursor-pointer text-lg font-semibold`,children:`Plano financeiro empresarial (pressupostos editáveis)`}),t[17]=ne):ne=t[17];let re;t[18]===s?re=t[19]:(re=s&&(0,V.jsx)(`p`,{role:`alert`,className:`my-3 rounded border border-red-300 p-3 text-sm text-red-900`,children:s}),t[18]=s,t[19]=re);let ie;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,V.jsx)(`p`,{className:`my-3 text-sm text-slate-700`,children:`Projecção indicativa com valores de exemplo editáveis ou pressupostos introduzidos pela pessoa. Facturação, cobranças, despesas, pagamentos, juros e capital reembolsado ficam separados. Não calcula impostos, não converte moedas e não substitui um plano contabilístico validado.`}),t[20]=ie):ie=t[20];let ae;t[21]===n?ae=t[22]:(ae=n&&!de(n),t[21]=n,t[22]=ae);let oe=(0,V.jsx)(`input`,{list:`plan-currency-options`,maxLength:3,pattern:`[A-Z]{3}`,value:n,onChange:e=>{let t=e.target.value.toUpperCase();i(t),g({...c,currency:t})},className:`mt-1 w-full rounded border p-2`,"aria-invalid":!!ae}),se;t[23]===oe?se=t[24]:(se=(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Moeda (código ISO)`,oe]}),t[23]=oe,t[24]=se);let ce;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(ce=(0,V.jsx)(`datalist`,{id:`plan-currency-options`,children:ue.map(lt)}),t[25]=ce):ce=t[25];let B;t[26]===u?B=t[27]:(B=e=>u(`presentationCurrency`,e.target.value.toUpperCase()),t[26]=u,t[27]=B);let le;t[28]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,V.jsx)(`datalist`,{id:`plan-presentation-currency-options`,children:ue.map(ct)}),t[28]=le):le=t[28];let H;t[29]===u?H=t[30]:(H=e=>u(`openingCash`,e),t[29]=u,t[30]=H);let fe;t[31]===Symbol.for(`react.memo_cache_sentinel`)?(fe=(0,V.jsx)(`legend`,{className:`font-semibold`,children:`Produtos ou serviços facturados por mês`}),t[31]=fe):fe=t[31];let pe=c.useProductInventorySchedule??!1,me=c.useProductInventorySchedule?`Usar existencias agregadas`:`Planear stock por produto`,he;t[32]!==pe||t[33]!==me||t[34]!==b?(he=(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,"aria-pressed":pe,onClick:b,children:me}),t[32]=pe,t[33]=me,t[34]=b,t[35]=he):he=t[35];let ge=c.useProductInventorySchedule&&(0,V.jsx)(`p`,{role:`note`,className:`text-sm`,children:`Declare o stock inicial e as encomendas de cada produto. A soma do stock inicial deve coincidir com Existencias iniciais no fundo de maneio. A falta nao reduz as vendas planeadas automaticamente.`}),_e=c.useSupplierPaymentTerms??!1,ve=c.useSupplierPaymentTerms?`Usar pagamentos mensais manuais`:`Calcular pagamentos pelo prazo do fornecedor`,ye;t[36]!==_e||t[37]!==ve||t[38]!==x?(ye=(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,"aria-pressed":_e,onClick:x,children:ve}),t[36]=_e,t[37]=ve,t[38]=x,t[39]=ye):ye=t[39];let be=c.useSupplierPaymentTerms&&(0,V.jsx)(`p`,{role:`note`,className:`text-sm`,children:`Cada encomenda e paga integralmente apos o prazo declarado, contado desde a encomenda. A agenda manual de pagamentos variaveis fica suspensa para evitar duplicacao; valores vencidos depois do horizonte sao apresentados como saldo por pagar.`}),U=c.products.map((e,t)=>(0,V.jsxs)(`div`,{className:`space-y-3 rounded border p-3`,children:[(0,V.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-4`,children:[(0,V.jsxs)(`label`,{className:`block text-sm`,children:[`Produto/serviço`,(0,V.jsx)(`input`,{value:e.label,onChange:e=>j(t,`label`,e.target.value),className:`mt-1 w-full rounded border p-2`})]}),(0,V.jsxs)(`label`,{className:`block text-sm`,children:[e.monthlyUnitsByPeriod?`Unidades mensais base`:`Unidades por mes`,(0,V.jsx)(`input`,{type:`number`,min:`0`,step:`0.001`,value:e.monthlyUnits,onChange:e=>j(t,`monthlyUnits`,e.target.value),className:`mt-1 w-full rounded border p-2`})]}),(0,V.jsx)($,{label:`Preço por unidade`,value:e.unitPrice,onChange:e=>j(t,`unitPrice`,e)}),(0,V.jsx)($,{label:`Custo variável por unidade`,value:e.unitVariableCost,onChange:e=>j(t,`unitVariableCost`,e)})]}),c.useProductInventorySchedule&&(0,V.jsxs)(`div`,{className:`space-y-2 rounded border p-3`,children:[(0,V.jsx)($,{label:`Existencias iniciais — ${e.label}`,value:e.productInventoryOpening??``,onChange:e=>g({...c,currency:n,products:c.products.map((n,r)=>r===t?{...n,productInventoryOpening:e}:n)})}),(0,V.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:(e.productInventoryPurchasesByPeriod??[]).slice(0,c.periods??12).map((e,n)=>(0,V.jsxs)(`div`,{className:`rounded border p-2`,children:[(0,V.jsx)($,{label:`Encomenda — mes ${n+1}`,value:e.amount,onChange:e=>S(t,n,`amount`,e)}),(0,V.jsxs)(`label`,{className:`block text-sm`,children:[`Prazo de recepcao`,(0,V.jsx)(`select`,{className:`mt-1 w-full rounded border p-2`,value:e.leadMonths,onChange:e=>S(t,n,`leadMonths`,Number(e.target.value)),children:Array.from({length:13},st)})]}),c.useSupplierPaymentTerms&&(0,V.jsxs)(`fieldset`,{className:`mt-2 space-y-2 text-sm`,children:[(0,V.jsx)(`legend`,{children:`Parcelas ao fornecedor`}),(e.paymentInstallments??[{lagMonths:e.paymentLagMonths??0,percent:`100`}]).map((e,r)=>(0,V.jsxs)(`div`,{className:`grid grid-cols-[1fr_1fr_auto] gap-2`,children:[(0,V.jsxs)(`label`,{children:[`Prazo`,(0,V.jsx)(`select`,{className:`mt-1 w-full rounded border p-2`,value:e.lagMonths,onChange:e=>C(t,n,r,`lagMonths`,Number(e.target.value)),children:Array.from({length:13},ot)})]}),(0,V.jsxs)(`label`,{children:[`Percentagem`,(0,V.jsx)(`input`,{className:`mt-1 w-full rounded border p-2`,type:`number`,min:`0`,max:`100`,step:`0.01`,value:e.percent,onChange:e=>C(t,n,r,`percent`,e.target.value)})]}),(0,V.jsx)(`button`,{type:`button`,className:`self-end rounded border px-2 py-2`,"aria-label":`Remover parcela`,onClick:()=>T(t,n,r),children:`Remover`})]},r)),(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1`,disabled:(e.paymentInstallments?.length??1)>=12,onClick:()=>w(t,n),children:`Adicionar parcela`})]})]},`product-stock-${t}-${n}`))})]}),(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,onClick:()=>D(t,`monthlyUnitsByPeriod`),children:e.monthlyUnitsByPeriod?`Usar unidades constantes`:`Planear unidades por mes`}),e.monthlyUnitsByPeriod&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{role:`note`,className:`text-sm`,children:`Meses fora do horizonte ficam guardados. Ao ampliar o horizonte, novos meses usam as unidades base; ajuste o plano mensal.`}),(0,V.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:e.monthlyUnitsByPeriod.slice(0,c.periods??12).map((e,n)=>(0,V.jsxs)(`label`,{className:`block text-sm`,children:[`Unidades - mes `,n+1,(0,V.jsx)(`input`,{type:`number`,min:`0`,step:`0.001`,value:e,onChange:e=>O(t,`monthlyUnitsByPeriod`,n,e.target.value),className:`mt-1 w-full rounded border p-2`})]},n))})]}),(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,onClick:()=>D(t,`unitPriceByPeriod`),children:e.unitPriceByPeriod?`Usar precos constantes`:`Planear precos por mes`}),e.unitPriceByPeriod&&(0,V.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:e.unitPriceByPeriod.slice(0,c.periods??12).map((e,n)=>(0,V.jsx)($,{label:`Preco por unidade - mes ${n+1}`,value:e,onChange:e=>O(t,`unitPriceByPeriod`,n,e)},n))}),(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,onClick:()=>D(t,`unitVariableCostByPeriod`),children:e.unitVariableCostByPeriod?`Usar custos unitarios constantes`:`Planear custos unitarios por mes`}),e.unitVariableCostByPeriod&&(0,V.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:e.unitVariableCostByPeriod.slice(0,c.periods??12).map((e,n)=>(0,V.jsx)($,{label:`Custo por unidade - mes ${n+1}`,value:e,onChange:e=>O(t,`unitVariableCostByPeriod`,n,e)},n))}),!e.monthlyUnitsByPeriod&&(e.unitPriceByPeriod||e.unitVariableCostByPeriod)&&(0,V.jsx)(`p`,{role:`note`,className:`text-sm`,children:`Meses fora do horizonte ficam guardados. Ao ampliar o horizonte, novos meses usam os valores-base.`})]},t)),W=(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,onClick:()=>g({...c,currency:n,products:[...c.products,{label:`Produto/serviço ${c.products.length+1}`,monthlyUnits:`0`,unitPrice:`0`,unitVariableCost:`0`,...c.useProductInventorySchedule?{productInventoryOpening:``,productInventoryPurchasesByPeriod:Array.from({length:h},()=>({amount:`0`,leadMonths:0,...c.useSupplierPaymentTerms?{paymentLagMonths:0,paymentInstallments:[{lagMonths:0,percent:`100`}]}:{}}))}:{}}]}),children:`Adicionar produto ou serviço`}),G;t[40]!==he||t[41]!==ge||t[42]!==ye||t[43]!==be||t[44]!==U||t[45]!==W?(G=(0,V.jsxs)(`fieldset`,{className:`my-4 space-y-3`,children:[fe,he,ge,ye,be,U,W]}),t[40]=he,t[41]=ge,t[42]=ye,t[43]=be,t[44]=U,t[45]=W,t[46]=G):G=t[46];let xe;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(xe=(0,V.jsx)(`legend`,{className:`font-semibold`,children:`Operação, custos e pagamentos mensais`}),t[47]=xe):xe=t[47];let Se=c.salesCollectionLagMonths??``,Ce;t[48]===u?Ce=t[49]:(Ce=e=>u(`salesCollectionLagMonths`,e.target.value===``?null:Number(e.target.value)),t[48]=u,t[49]=Ce);let K,we;t[50]===Symbol.for(`react.memo_cache_sentinel`)?(K=(0,V.jsx)(`option`,{value:``,children:`Usar cobranças mensais declaradas`}),we=Array.from({length:13},at),t[50]=K,t[51]=we):(K=t[50],we=t[51]);let q;t[52]!==Se||t[53]!==Ce||t[54]!==we?(q=(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Prazo entre facturação e cobrança das vendas`,(0,V.jsxs)(`select`,{value:Se,onChange:Ce,className:`mt-1 w-full rounded border p-2`,children:[K,we]})]}),t[52]=Se,t[53]=Ce,t[54]=we,t[55]=q):q=t[55];let Te=c.salesCollectionLagMonths!==null&&c.salesCollectionLagMonths!==void 0&&(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Percentagem da facturação cobrada no prazo`,(0,V.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:16,value:c.salesCollectionPercent??`100`,onChange:e=>u(`salesCollectionPercent`,e.target.value),className:`mt-1 w-full rounded border p-2`,"aria-describedby":`sales-collection-percent-help`}),(0,V.jsx)(`span`,{id:`sales-collection-percent-help`,className:`block text-xs font-normal`,children:`Introduza 0–100. O restante permanece como valor por cobrar; isto não prevê recuperação posterior.`})]}),Ee=c.salesCollectionLagMonths!==null&&c.salesCollectionLagMonths!==void 0&&(0,V.jsxs)(`div`,{className:`space-y-2 sm:col-span-2`,children:[(0,V.jsx)(`p`,{className:`text-sm font-medium`,children:`Recuperação de vendas vencidas`}),(c.salesRecoverySchedule??[]).map((e,t)=>(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[(0,V.jsxs)(`label`,{className:`text-sm`,children:[`Mês`,(0,V.jsx)(`select`,{className:`ml-2 rounded border p-2`,value:e.month,onChange:e=>d(t,`month`,Number(e.target.value)),children:Array.from({length:c.periods??12},it)})]}),(0,V.jsxs)(`label`,{className:`text-sm`,children:[`% do saldo vencido`,(0,V.jsx)(`input`,{className:`ml-2 w-24 rounded border p-2`,inputMode:`decimal`,value:e.percent,onChange:e=>d(t,`percent`,e.target.value)})]}),(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-2`,onClick:()=>u(`salesRecoverySchedule`,(c.salesRecoverySchedule??[]).filter((e,n)=>n!==t)),children:`Remover`})]},`recovery-${t}`)),(0,V.jsx)(`p`,{className:`text-xs`,children:`Cada percentagem aplica-se ao saldo vencido ainda em aberto no mês indicado, depois da cobrança inicial. Sem agenda, não se presume recuperação.`}),(c.salesRecoverySchedule??[]).length<60&&(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-1`,onClick:()=>u(`salesRecoverySchedule`,[...c.salesRecoverySchedule??[],{month:1,percent:`0`}]),children:`Adicionar recuperação`})]}),J=c.salesCollectionLagMonths===null||c.salesCollectionLagMonths===void 0?`Cobranças recebidas por mês`:`Outras cobranças mensais`,Oe;t[56]===u?Oe=t[57]:(Oe=e=>u(`monthlyCollections`,e),t[56]=u,t[57]=Oe);let ke;t[58]!==c||t[59]!==J||t[60]!==Oe?(ke=(0,V.jsx)($,{label:J,value:c.monthlyCollections,onChange:Oe}),t[58]=c,t[59]=J,t[60]=Oe,t[61]=ke):ke=t[61];let Y=c.salesCollectionLagMonths===null||c.salesCollectionLagMonths===void 0?`Modo manual: este valor representa todas as cobranças mensais e não é reconciliado automaticamente com a facturação.`:`Modo por prazo: ${c.salesCollectionPercent??`100`}% da facturação vence após o prazo indicado; o restante fica em aberto, excepto recuperações declaradas acima sobre saldos vencidos. O campo acima soma outras cobranças.`,Ae;t[62]===Y?Ae=t[63]:(Ae=(0,V.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:Y}),t[62]=Y,t[63]=Ae);let X=c.useProductInventorySchedule?(0,V.jsx)(`p`,{role:`note`,className:`text-sm sm:col-span-2`,children:`As compras agregadas ficam inactivas enquanto o stock estiver planeado por produto.`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`div`,{className:`sm:col-span-2`,children:(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,"aria-pressed":c.useInventoryPurchaseSchedule??!1,onClick:y,children:c.useInventoryPurchaseSchedule?`Usar compras e prazo constantes`:`Planear compras e prazos por mês`})}),c.useInventoryPurchaseSchedule?(0,V.jsx)(`div`,{className:`space-y-3 sm:col-span-2`,children:(c.inventoryPurchaseSchedule??[]).slice(0,c.periods??12).map((e,t)=>(0,V.jsxs)(`div`,{className:`grid gap-2 rounded border p-3 sm:grid-cols-2`,children:[(0,V.jsx)($,{label:`Encomenda para existências — mês ${t+1}`,value:e.amount,onChange:e=>E(t,`amount`,e)}),(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Prazo até à recepção — mês`,` `,t+1,(0,V.jsx)(`select`,{value:e.leadMonths,onChange:e=>E(t,`leadMonths`,Number(e.target.value)),className:`mt-1 w-full rounded border p-2`,children:Array.from({length:13},rt)})]})]},`inventory-order-${t}`))}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)($,{label:`Compras mensais para existências`,value:c.monthlyInventoryPurchases??``,onChange:e=>u(`monthlyInventoryPurchases`,e)}),(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Prazo de entrega das compras (meses)`,(0,V.jsx)(`input`,{type:`number`,min:`0`,max:`12`,step:`1`,value:String(c.inventoryPurchaseLeadMonths??0),onChange:e=>u(`inventoryPurchaseLeadMonths`,Number(e.target.value)),className:`mt-1 w-full rounded border p-2`})]})]}),(0,V.jsx)(`p`,{className:`text-xs text-slate-600 sm:col-span-2`,children:`As compras são encomendas e cada prazo declarado afecta o mês da recepção; pagamentos de compras continuam a ser um fluxo de caixa separado. Encomendas ainda não recebidas aparecem como mercadoria em trânsito. Se faltar stock, reveja compras ou vendas: a facturação introduzida não é reduzida automaticamente.`})]}),Z;t[64]===u?Z=t[65]:(Z=e=>u(`monthlyOperatingExpenses`,e),t[64]=u,t[65]=Z);let je;t[66]!==c||t[67]!==Z?(je=(0,V.jsx)($,{label:`Despesas operacionais reconhecidas`,value:c.monthlyOperatingExpenses,onChange:Z}),t[66]=c,t[67]=Z,t[68]=je):je=t[68];let Me;t[69]===u?Me=t[70]:(Me=e=>u(`monthlyOperatingPayments`,e),t[69]=u,t[70]=Me);let Ne;t[71]!==c||t[72]!==Me?(Ne=(0,V.jsx)($,{label:`Pagamento de despesas operacionais`,value:c.monthlyOperatingPayments,onChange:Me}),t[71]=c,t[72]=Me,t[73]=Ne):Ne=t[73];let Pe;t[74]===u?Pe=t[75]:(Pe=e=>u(`monthlyPayrollExpense`,e),t[74]=u,t[75]=Pe);let Q;t[76]!==c||t[77]!==Pe?(Q=(0,V.jsx)($,{label:`Custo mensal de pessoal`,value:c.monthlyPayrollExpense,onChange:Pe}),t[76]=c,t[77]=Pe,t[78]=Q):Q=t[78];let Re;t[79]===u?Re=t[80]:(Re=e=>u(`monthlyPayrollPayments`,e),t[79]=u,t[80]=Re);let ze;t[81]!==c||t[82]!==Re?(ze=(0,V.jsx)($,{label:`Pagamento mensal de pessoal`,value:c.monthlyPayrollPayments,onChange:Re}),t[81]=c,t[82]=Re,t[83]=ze):ze=t[83];let He=c.useSupplierPaymentTerms&&(0,V.jsx)(`p`,{role:`note`,className:`text-sm sm:col-span-2`,children:`Os pagamentos de compras sao calculados pelas encomendas e prazos acima; o valor mensal manual fica suspenso para evitar contar os mesmos pagamentos duas vezes.`}),mt=e.filter(e=>{let{key:t}=e;return!c.useSupplierPaymentTerms||t!==`monthlyVariableCostPaymentsByPeriod`}).map(e=>{let{key:t,baseKey:n,label:r}=e;return(0,V.jsxs)(`div`,{className:`sm:col-span-2`,children:[(0,V.jsx)(`button`,{type:`button`,className:`text-sm underline`,onClick:()=>k(t,n),children:c[t]?`Usar valor constante: ${r.toLowerCase()}`:`Planear por mês: ${r.toLowerCase()}`}),t===`monthlyVariableCostPaymentsByPeriod`&&!c[t]&&(0,V.jsx)($,{label:r,value:c[n],onChange:e=>u(n,e)}),` `,c[t]&&(0,V.jsx)(`div`,{className:`mt-2 grid gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:c[t].slice(0,c.periods??12).map((e,n)=>(0,V.jsx)($,{label:`${r} - mês ${n+1}`,value:e,onChange:e=>A(t,n,e)},n))})]},t)}),ht;t[84]!==q||t[85]!==Te||t[86]!==Ee||t[87]!==ke||t[88]!==Ae||t[89]!==X||t[90]!==je||t[91]!==Ne||t[92]!==Q||t[93]!==ze||t[94]!==He||t[95]!==mt?(ht=(0,V.jsxs)(`fieldset`,{className:`grid gap-2 sm:grid-cols-2`,children:[xe,q,Te,Ee,ke,Ae,X,je,Ne,Q,ze,He,mt]}),t[84]=q,t[85]=Te,t[86]=Ee,t[87]=ke,t[88]=Ae,t[89]=X,t[90]=je,t[91]=Ne,t[92]=Q,t[93]=ze,t[94]=He,t[95]=mt,t[96]=ht):ht=t[96];let gt;t[97]===Symbol.for(`react.memo_cache_sentinel`)?(gt=(0,V.jsx)(`legend`,{className:`font-semibold`,children:`Investimento, fundo de maneio e financiamento inicial`}),t[97]=gt):gt=t[97];let _t;t[98]===u?_t=t[99]:(_t=e=>u(`assetInvestment`,e),t[98]=u,t[99]=_t);let vt;t[100]!==c||t[101]!==_t?(vt=(0,V.jsx)($,{label:`Aquisição de activos`,value:c.assetInvestment,onChange:_t}),t[100]=c,t[101]=_t,t[102]=vt):vt=t[102];let yt;t[103]===u?yt=t[104]:(yt=e=>u(`inventory`,e),t[103]=u,t[104]=yt);let bt;t[105]!==c||t[106]!==yt?(bt=(0,V.jsx)($,{label:`Existências iniciais`,value:c.inventory,onChange:yt}),t[105]=c,t[106]=yt,t[107]=bt):bt=t[107];let xt;t[108]===u?xt=t[109]:(xt=e=>u(`receivables`,e),t[108]=u,t[109]=xt);let St;t[110]!==c||t[111]!==xt?(St=(0,V.jsx)($,{label:`Valores a receber`,value:c.receivables,onChange:xt}),t[110]=c,t[111]=xt,t[112]=St):St=t[112];let Ct=c.openingReceivablesCollectionMonth??``,wt;t[113]===u?wt=t[114]:(wt=e=>u(`openingReceivablesCollectionMonth`,e.target.value===``?null:Number(e.target.value)),t[113]=u,t[114]=wt);let Tt,Et;t[115]===Symbol.for(`react.memo_cache_sentinel`)?(Tt=(0,V.jsx)(`option`,{value:``,children:`Sem previsão de cobrança`}),Et=Array.from({length:60},nt),t[115]=Tt,t[116]=Et):(Tt=t[115],Et=t[116]);let Dt;t[117]!==Ct||t[118]!==wt||t[119]!==Et?(Dt=(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Mês previsto para cobrar valores a receber de abertura`,(0,V.jsxs)(`select`,{value:Ct,onChange:wt,className:`mt-1 w-full rounded border p-2`,children:[Tt,Et]})]}),t[117]=Ct,t[118]=wt,t[119]=Et,t[120]=Dt):Dt=t[120];let Ot=c.openingReceivablesCollectionMonth!==null&&c.openingReceivablesCollectionMonth!==void 0&&(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Percentagem prevista a cobrar`,(0,V.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:16,value:c.openingReceivablesCollectionPercent??`100`,onChange:e=>u(`openingReceivablesCollectionPercent`,e.target.value),className:`mt-1 w-full rounded border p-2`})]}),kt;t[121]===Symbol.for(`react.memo_cache_sentinel`)?(kt=(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h3`,{className:`font-medium`,children:`Parcelas adicionais de recebíveis de abertura`}),(0,V.jsx)(`p`,{className:`text-xs text-slate-600`,children:`Declare cada mês e a percentagem do saldo inicial a cobrar. Inclua a cobrança única acima na soma: o total não pode exceder 100%. Sem parcela declarada, não se presume recebimento.`})]}),t[121]=kt):kt=t[121];let At=c.openingReceivablesInstallments??[],jt;if(t[122]!==m||t[123]!==At||t[124]!==f){let e;t[126]!==m||t[127]!==f?(e=(e,t)=>(0,V.jsxs)(`div`,{className:`grid gap-2 rounded border p-3 sm:grid-cols-[1fr_1fr_auto]`,children:[(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Mês da parcela `,t+1,(0,V.jsx)(`select`,{value:e.month,onChange:e=>f(t,`month`,Number(e.target.value)),className:`mt-1 w-full rounded border p-2`,children:Array.from({length:60},tt).map(et)})]}),(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Percentagem do saldo inicial`,(0,V.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:16,value:e.percent,onChange:e=>f(t,`percent`,e.target.value),className:`mt-1 w-full rounded border p-2`})]}),(0,V.jsx)(`button`,{type:`button`,className:`self-end rounded border px-3 py-2 text-sm`,"aria-label":`Remover parcela de recebíveis ${t+1}`,onClick:()=>m(t),children:`Remover`})]},`opening-receivable-${t}`),t[126]=m,t[127]=f,t[128]=e):e=t[128],jt=At.map(e),t[122]=m,t[123]=At,t[124]=f,t[125]=jt}else jt=t[125];let Mt=(c.openingReceivablesInstallments??[]).length>=60,Nt;t[129]!==p||t[130]!==Mt?(Nt=(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 text-sm`,disabled:Mt,onClick:p,children:`Acrescentar parcela`}),t[129]=p,t[130]=Mt,t[131]=Nt):Nt=t[131];let Pt;t[132]!==jt||t[133]!==Nt?(Pt=(0,V.jsxs)(`div`,{className:`space-y-3 sm:col-span-2`,children:[kt,jt,Nt]}),t[132]=jt,t[133]=Nt,t[134]=Pt):Pt=t[134];let Ft;t[135]===u?Ft=t[136]:(Ft=e=>u(`payables`,e),t[135]=u,t[136]=Ft);let It;t[137]!==c||t[138]!==Ft?(It=(0,V.jsx)($,{label:`Valores a pagar`,value:c.payables,onChange:Ft}),t[137]=c,t[138]=Ft,t[139]=It):It=t[139];let Lt;t[140]===u?Lt=t[141]:(Lt=e=>u(`equity`,e),t[140]=u,t[141]=Lt);let Rt;t[142]!==c||t[143]!==Lt?(Rt=(0,V.jsx)($,{label:`Capital próprio`,value:c.equity,onChange:Lt}),t[142]=c,t[143]=Lt,t[144]=Rt):Rt=t[144];let zt;t[145]===u?zt=t[146]:(zt=e=>u(`shareholderLoans`,e),t[145]=u,t[146]=zt);let Bt;t[147]!==c||t[148]!==zt?(Bt=(0,V.jsx)($,{label:`Suprimentos`,value:c.shareholderLoans,onChange:zt}),t[147]=c,t[148]=zt,t[149]=Bt):Bt=t[149];let Vt;t[150]===u?Vt=t[151]:(Vt=e=>u(`bankLoanProceeds`,e),t[150]=u,t[151]=Vt);let Ht;t[152]!==c||t[153]!==Vt?(Ht=(0,V.jsx)($,{label:`Empréstimo recebido`,value:c.bankLoanProceeds,onChange:Vt}),t[152]=c,t[153]=Vt,t[154]=Ht):Ht=t[154];let Ut;t[155]===u?Ut=t[156]:(Ut=e=>u(`grants`,e),t[155]=u,t[156]=Ut);let Wt;t[157]!==c||t[158]!==Ut?(Wt=(0,V.jsx)($,{label:`Subvenções`,value:c.grants,onChange:Ut}),t[157]=c,t[158]=Ut,t[159]=Wt):Wt=t[159];let Gt;t[160]!==vt||t[161]!==bt||t[162]!==St||t[163]!==Dt||t[164]!==Ot||t[165]!==Pt||t[166]!==It||t[167]!==Rt||t[168]!==Bt||t[169]!==Ht||t[170]!==Wt?(Gt=(0,V.jsxs)(`fieldset`,{className:`grid gap-2 sm:grid-cols-2`,children:[gt,vt,bt,St,Dt,Ot,Pt,It,Rt,Bt,Ht,Wt]}),t[160]=vt,t[161]=bt,t[162]=St,t[163]=Dt,t[164]=Ot,t[165]=Pt,t[166]=It,t[167]=Rt,t[168]=Bt,t[169]=Ht,t[170]=Wt,t[171]=Gt):Gt=t[171];let Kt;t[172]===Symbol.for(`react.memo_cache_sentinel`)?(Kt=(0,V.jsx)(`legend`,{className:`font-semibold`,children:`Depreciação contabilística e dívida mensal`}),t[172]=Kt):Kt=t[172];let qt;t[173]===u?qt=t[174]:(qt=e=>u(`assetDepreciation`,e),t[173]=u,t[174]=qt);let Jt;t[175]!==c||t[176]!==qt?(Jt=(0,V.jsx)($,{label:`Base depreciável contabilística`,value:c.assetDepreciation,onChange:qt}),t[175]=c,t[176]=qt,t[177]=Jt):Jt=t[177];let Yt;t[178]===u?Yt=t[179]:(Yt=e=>u(`depreciationLifeMonths`,Number(e.target.value)),t[178]=u,t[179]=Yt);let Xt;t[180]!==c||t[181]!==Yt?(Xt=(0,V.jsxs)(`label`,{className:`block text-sm`,children:[`Vida útil (meses)`,(0,V.jsx)(`input`,{type:`number`,min:`1`,max:`600`,value:c.depreciationLifeMonths,onChange:Yt,className:`mt-1 w-full rounded border p-2`})]}),t[180]=c,t[181]=Yt,t[182]=Xt):Xt=t[182];let Zt;t[183]===u?Zt=t[184]:(Zt=e=>u(`monthlyInterestExpense`,e),t[183]=u,t[184]=Zt);let Qt;t[185]!==c||t[186]!==Zt?(Qt=(0,V.jsx)($,{label:`Despesa de juros reconhecida`,value:c.monthlyInterestExpense,onChange:Zt}),t[185]=c,t[186]=Zt,t[187]=Qt):Qt=t[187];let $t;t[188]===u?$t=t[189]:($t=e=>u(`monthlyInterestPayment`,e),t[188]=u,t[189]=$t);let en;t[190]!==c||t[191]!==$t?(en=(0,V.jsx)($,{label:`Pagamento de juros`,value:c.monthlyInterestPayment,onChange:$t}),t[190]=c,t[191]=$t,t[192]=en):en=t[192];let tn;t[193]===u?tn=t[194]:(tn=e=>u(`monthlyPrincipalRepayment`,e),t[193]=u,t[194]=tn);let nn;t[195]!==c||t[196]!==tn?(nn=(0,V.jsx)($,{label:`Reembolso de capital`,value:c.monthlyPrincipalRepayment,onChange:tn}),t[195]=c,t[196]=tn,t[197]=nn):nn=t[197];let rn;t[198]!==Jt||t[199]!==Xt||t[200]!==Qt||t[201]!==en||t[202]!==nn?(rn=(0,V.jsxs)(`fieldset`,{className:`grid gap-2 sm:grid-cols-2`,children:[Kt,Jt,Xt,Qt,en,nn]}),t[198]=Jt,t[199]=Xt,t[200]=Qt,t[201]=en,t[202]=nn,t[203]=rn):rn=t[203];let an;t[204]!==ht||t[205]!==Gt||t[206]!==rn?(an=(0,V.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[ht,Gt,rn]}),t[204]=ht,t[205]=Gt,t[206]=rn,t[207]=an):an=t[207];let on,sn;t[208]===Symbol.for(`react.memo_cache_sentinel`)?(on=(0,V.jsx)(`summary`,{className:`cursor-pointer font-semibold`,children:`Comparar cenários financeiros`}),sn=(0,V.jsx)(`p`,{className:`my-2 text-sm`,children:`“Favorável” e “desfavorável” são rótulos de cenários, não previsões. Defina como variam volume, preço, custo variável, despesas/pessoal e cobranças declaradas face ao cenário base. Com cobrança de vendas por prazo, a facturação ajustada determina esses recebimentos; esta variação aplica-se apenas às outras cobranças. Sem variações introduzidas, não há comparação.`}),t[208]=on,t[209]=sn):(on=t[208],sn=t[209]);let cn=[[`favorable`,`Favorável`],[`unfavorable`,`Desfavorável`]].map(e=>{let[t,n]=e;return(0,V.jsxs)(`fieldset`,{className:`grid gap-2 sm:grid-cols-2`,children:[(0,V.jsxs)(`legend`,{className:`font-semibold`,children:[n,` (%)`]}),[[`unitVolumePercent`,`Variação de unidades`],[`unitPricePercent`,`Variação do preço`],[`unitCostPercent`,`Variação do custo variável`],[`operatingCostsPercent`,`Variação de despesas e pessoal`],[`cashCollectionsPercent`,`Variação das cobranças`]].map(e=>{let[n,r]=e;return(0,V.jsxs)(`label`,{className:`block text-sm`,children:[r,(0,V.jsx)(`input`,{type:`number`,min:`-100`,step:`0.01`,value:F[t][n],onChange:e=>I(t,n,e.target.value),className:`mt-1 w-full rounded border p-2`})]},n)})]},t)}),ln;t[210]===cn?ln=t[211]:(ln=(0,V.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:cn}),t[210]=cn,t[211]=ln);let un;t[212]===R?un=t[213]:(un=R&&(0,V.jsx)(`output`,{className:`mt-2 block text-sm`,children:`Complete todos os pressupostos dos dois cenários ou limpe as variações para exportar o relatório.`}),t[212]=R,t[213]=un),_=(0,V.jsxs)(`details`,{className:`rounded-lg border border-slate-300 p-4`,open:!0,children:[ne,re,ie,(0,V.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:[se,ce,(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Moeda de apresentação (opcional)`,(0,V.jsx)(`input`,{list:`plan-presentation-currency-options`,maxLength:3,pattern:`[A-Z]{3}`,value:c.presentationCurrency??``,onChange:B,className:`mt-1 w-full rounded border p-2`,"aria-invalid":!!(c.presentationCurrency&&!de(c.presentationCurrency))})]}),le,c.presentationCurrency&&c.presentationCurrency!==n&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Taxa em `,c.presentationCurrency,` por 1`,` `,n,(0,V.jsx)(`input`,{type:`number`,min:`0.00000001`,step:`0.00000001`,value:c.fxRate??``,onChange:e=>u(`fxRate`,e.target.value),className:`mt-1 w-full rounded border p-2`,"aria-required":`true`})]}),(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Data efectiva da taxa`,(0,V.jsx)(`input`,{type:`date`,value:c.fxDate??``,onChange:e=>u(`fxDate`,e.target.value),className:`mt-1 w-full rounded border p-2`,"aria-required":`true`})]}),(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Fonte da taxa de câmbio`,(0,V.jsx)(`input`,{value:c.fxSource??``,maxLength:2e3,onChange:e=>u(`fxSource`,e.target.value),className:`mt-1 w-full rounded border p-2`,"aria-required":`true`})]})]}),(0,V.jsx)($,{label:`Saldo de caixa inicial`,value:c.openingCash,allowNegative:!0,onChange:H}),(0,V.jsxs)(`label`,{className:`block text-sm font-medium`,children:[`Horizonte (meses)`,(0,V.jsx)(`input`,{type:`number`,min:`1`,max:`60`,step:`1`,value:String(c.periods??12),onChange:e=>v(Number(e.target.value)),className:`mt-1 w-full rounded border p-2`})]})]}),G,an,(0,V.jsxs)(`details`,{className:`mt-4 rounded border p-3`,children:[on,sn,ln,ee&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-2 text-sm text-red-800`,children:ee}),un,z&&de(n)&&(0,V.jsxs)(`div`,{className:`mt-3 overflow-x-auto`,children:[(0,V.jsxs)(`table`,{className:`min-w-full text-sm`,children:[(0,V.jsx)(`caption`,{className:`sr-only`,children:`Comparação de resultados por cenário`}),(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Cenário`,`Variações declaradas`,`Facturação`,`Resultado antes impostos`,`Caixa final`,`Existências finais`,`Falta de stock`].map($e)})}),(0,V.jsxs)(`tbody`,{children:[(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:`Base`}),(0,V.jsx)(`td`,{className:`p-2`,children:`Sem variação`}),(0,V.jsx)(`td`,{className:`p-2`,children:z.base.totalRevenue}),(0,V.jsx)(`td`,{className:`p-2`,children:z.base.totalProfitBeforeTax}),(0,V.jsx)(`td`,{className:`p-2`,children:z.base.endingCash}),(0,V.jsx)(`td`,{className:`p-2`,children:z.base.inventoryProjection.endingInventory??`indeterminadas`}),(0,V.jsx)(`td`,{className:`p-2`,children:z.base.inventoryProjection.totalShortfall??`indeterminada`})]}),[[`Favorável`,z.favorable],[`Desfavorável`,z.unfavorable]].map(Qe)]})]}),(0,V.jsxs)(`p`,{className:`mt-2 text-xs`,children:[`Valores em `,n,`, antes de impostos. As alterações são pressupostos do utilizador; as componentes fiscais mantêm-se indeterminadas.`]})]})]}),N&&(0,V.jsx)(`p`,{role:`alert`,className:`my-3 text-sm text-red-800`,children:N}),M&&de(n)&&(0,V.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[(0,V.jsxs)(`h4`,{className:`font-semibold`,children:[`Resumo (`,n,`)`]}),(0,V.jsx)(`button`,{type:`button`,disabled:!!(ee||R),className:`rounded border px-3 py-2 text-sm focus-visible:outline-2 disabled:opacity-50`,onClick:()=>{let e=new Blob([Le({...c,currency:n})],{type:`text/csv;charset=utf-8`}),t=URL.createObjectURL(e),r=document.createElement(`a`);r.href=t,r.download=`plano-financeiro.csv`,r.click(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3)},children:`Exportar plano em CSV`}),(0,V.jsx)(`p`,{role:M.fundingStatus===`balanced`?`status`:`alert`,className:M.fundingStatus===`balanced`?`rounded bg-emerald-50 p-3 text-sm`:`rounded bg-amber-50 p-3 text-sm`,children:M.fundingStatus===`balanced`?`As fontes de financiamento reconciliam com os usos iniciais.`:M.fundingStatus===`shortfall`?`Falta financiar ${M.fundingGap} ${n} dos usos iniciais.`:`As fontes excedem os usos iniciais em ${M.fundingGap.replace(`-`,``)} ${n}.`}),(0,V.jsx)(`dl`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[[`Fundo de maneio líquido`,M.workingCapital],[`Usos iniciais`,M.initialUses],[`Fontes de financiamento`,M.financing],[`Diferenca entre usos e fontes`,M.fundingGap],[`Facturação no horizonte`,M.totalRevenue],[`Cobranças no horizonte`,M.totalCashCollections],[`Cobrança prevista de valores a receber de abertura`,M.totalOpeningReceivablesCollections],[`Valores de abertura ainda por receber`,M.openingReceivablesAtEnd],...M.totalSalesCollections===null?[]:[[`Cobranças da facturação modelada`,M.totalSalesCollections],[`Cobranças iniciais das vendas`,M.totalScheduledSalesCollections],[`Recuperações de vendas vencidas`,M.totalSalesRecoveryCollections],[`Facturação por cobrar no fim`,M.salesReceivablesAtEnd]],[`Resultado antes de impostos`,M.totalProfitBeforeTax],[`Caixa final projectada`,M.endingCash]].map(Ze)}),M.openingReceivablesInstallments.length>0&&(0,V.jsx)(`ul`,{"aria-label":`Parcelas previstas de recebíveis de abertura`,className:`space-y-1 text-sm`,children:M.openingReceivablesInstallments.map((e,t)=>(0,V.jsxs)(`li`,{children:[`Mês `,e.month,`:`,` `,e.percent,`% do saldo inicial (`,e.amount,` `,n,`)`]},`${e.month}-${t}`))}),(0,V.jsx)(`p`,{className:`text-sm`,children:`Fontes iniciais = capital próprio + suprimentos + empréstimos recebidos + subvenções. Usos iniciais = activos + fundo de maneio líquido. Juros são despesa; reembolso de capital é fluxo de caixa, não custo operacional.`}),te&&(0,V.jsxs)(`section`,{className:`space-y-2 rounded border border-amber-300 bg-amber-50 p-3`,"aria-labelledby":`financial-fiscal-bridge-title`,children:[(0,V.jsx)(`h5`,{id:`financial-fiscal-bridge-title`,className:`font-semibold`,children:`Ponte contabilístico-fiscal — incompleta`}),(0,V.jsxs)(`p`,{className:`text-sm`,children:[`Resultado contabilístico antes de impostos:`,` `,te.accountingProfitBeforeTax,` `,n,`. Matéria colectável: indeterminada; não se presume que as despesas sejam fiscalmente dedutíveis.`]}),(0,V.jsx)(`div`,{className:`overflow-x-auto`,children:(0,V.jsxs)(`table`,{className:`min-w-full text-xs`,children:[(0,V.jsx)(`caption`,{className:`sr-only`,children:`Linhas contabilísticas propostas para classificação fiscal`}),(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Origem`,`Efeito contabilístico`,`Total no período`,`Tratamento fiscal`].map(Xe)})}),(0,V.jsx)(`tbody`,{children:te.accountingLines.map(e=>(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:e.origin}),(0,V.jsxs)(`td`,{className:`p-2`,children:[e.accountingEffect===`income`?`Rendimento`:`Despesa`,`; por mês:`,` `,e.monthlyAmounts.map(Ye).join(` · `)]}),(0,V.jsxs)(`td`,{className:`p-2`,children:[e.total,` `,n]}),(0,V.jsx)(`td`,{className:`p-2`,children:`Por classificar`})]},e.code))})]})}),(0,V.jsx)(`p`,{className:`text-xs`,children:`Cobranças e pagamentos são apresentados separadamente no calendário de caixa. Reembolsos de capital não entram como despesa. Não são acrescentados valores fiscais zero nem pagamentos estimados.`})]}),M.inventoryProjection.status===`indeterminate`?(0,V.jsx)(`output`,{className:`block rounded bg-amber-50 p-3 text-sm`,children:`Existências finais indeterminadas: indique compras mensais para calcular saldo e falta de stock. Pagamentos de compras são um fluxo de caixa separado e não substituem este pressuposto.`}):(0,V.jsxs)(`output`,{className:`block rounded p-3 text-sm ${M.inventoryProjection.status===`estimated_with_shortfall`?`bg-amber-50`:`bg-emerald-50`}`,children:[`Existências finais estimadas:`,` `,M.inventoryProjection.endingInventory,` `,n,`; prazo de entrega:`,` `,M.inventoryProjection.leadMonths===null?`variável por mês`:`${M.inventoryProjection.leadMonths} mês(es)`,`. Mercadoria em trânsito no fim do horizonte:`,` `,M.inventoryProjection.inTransitAtEnd,` `,n,`. Falta total de stock estimada:`,` `,M.inventoryProjection.totalShortfall,` `,n,`. As vendas planeadas permanecem inalteradas e devem ser revistas se houver falta.`]}),(0,V.jsx)(`div`,{className:`overflow-x-auto`,children:(0,V.jsxs)(`table`,{className:`min-w-full text-xs`,children:[(0,V.jsx)(`caption`,{className:`sr-only`,children:`Encomendas, recepções, mercadoria em trânsito, consumo, falta e saldo de existências por mês`}),(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Mês`,`Saldo inicial`,`Encomendas`,`Prazo (meses)`,`Recepções`,`Em trânsito`,`Consumo`,`Falta de stock`,`Saldo final`].map(Je)})}),(0,V.jsx)(`tbody`,{children:M.rows.map(qe)})]})}),M.inventoryProjection.productSchedules&&(0,V.jsxs)(`section`,{className:`space-y-3 rounded border p-3`,children:[(0,V.jsx)(`h3`,{className:`font-semibold`,children:`Existencias por produto`}),M.inventoryProjection.productSchedules.map(e=>(0,V.jsxs)(`details`,{className:`rounded border p-2`,children:[(0,V.jsxs)(`summary`,{className:`cursor-pointer`,children:[e.label,`: stock final`,` `,e.endingInventory,` `,n,`; falta `,e.totalShortfall,` `,n]}),(0,V.jsx)(`div`,{className:`overflow-x-auto`,children:(0,V.jsxs)(`table`,{className:`min-w-full text-xs`,children:[(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Mes`,`Inicial`,`Encomendas`,`Prazo`,`Recepcoes`,`Em transito`,`Consumo`,`Falta`,`Final`].map(Ke)})}),(0,V.jsx)(`tbody`,{children:e.monthlyRows.map(Ge)})]})}),e.paymentSchedule&&(0,V.jsxs)(`div`,{className:`mt-3 overflow-x-auto`,children:[(0,V.jsx)(`h4`,{className:`font-medium`,children:`Pagamentos declarados ao fornecedor`}),(0,V.jsxs)(`table`,{className:`min-w-full text-xs`,children:[(0,V.jsx)(`thead`,{children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{className:`p-2 text-left`,children:`Encomenda`}),(0,V.jsx)(`th`,{className:`p-2 text-left`,children:`Pagamento`}),(0,V.jsx)(`th`,{className:`p-2 text-left`,children:`Parcela`}),(0,V.jsx)(`th`,{className:`p-2 text-left`,children:`Montante`}),(0,V.jsx)(`th`,{className:`p-2 text-left`,children:`Estado`})]})}),(0,V.jsx)(`tbody`,{children:e.paymentSchedule.map(e=>(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsxs)(`td`,{className:`p-2`,children:[`Mes`,` `,e.orderMonth]}),(0,V.jsx)(`td`,{className:`p-2`,children:e.paymentMonth===null?`Sem prazo declarado`:`Mes ${e.paymentMonth}`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.percent===`remaining`?`Saldo nao calendarizado`:`${e.percent}%`}),(0,V.jsxs)(`td`,{className:`p-2`,children:[e.amount,` `,n]}),(0,V.jsx)(`td`,{className:`p-2`,children:e.paidWithinHorizon?`Incluido no fluxo de caixa`:e.paymentMonth===null?`Saldo sem parcela calendarizada`:`Por pagar no fim do horizonte`})]},`${e.orderMonth}-${e.paymentMonth??`unallocated`}-${e.amount}`))})]})]})]},e.label))]}),` `,M.supplierPaymentsOutstandingAtEnd!==null&&(0,V.jsxs)(`output`,{className:`block rounded bg-amber-50 p-3 text-sm`,children:[`Compras a fornecedores ainda por pagar no fim do horizonte: `,M.supplierPaymentsOutstandingAtEnd,` `,n,`. Os pagamentos sao calculados pelas encomendas e prazos declarados; nao representam credito confirmado pelo fornecedor.`]}),M.conversion&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`p`,{className:`rounded bg-sky-50 p-3 text-sm`,children:[`Conversão de apresentação: 1 `,n,` =`,` `,M.conversion.rate,` `,M.conversion.currency,`, em`,` `,M.conversion.date,`; fonte declarada:`,` `,M.conversion.source,`. Os valores originais permanecem em `,n,`.`]}),(0,V.jsx)(`dl`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[[`Fundo de maneio`,M.conversion.workingCapital],[`Usos iniciais`,M.conversion.initialUses],[`Fontes de financiamento`,M.conversion.financing],[`Estado da reconciliacao do financiamento`,M.conversion.fundingStatus],[`Diferenca entre usos e fontes`,M.conversion.fundingGap],[`Facturação`,M.conversion.totalRevenue],[`Cobranças no horizonte`,M.conversion.totalCashCollections],[`Cobrança de valores de abertura`,M.conversion.totalOpeningReceivablesCollections],[`Valores de abertura por receber`,M.conversion.openingReceivablesAtEnd],[`Resultado antes impostos`,M.conversion.totalProfitBeforeTax],[`Caixa final`,M.conversion.endingCash]].map(e=>{let[t,n]=e;return(0,V.jsxs)(`div`,{className:`rounded bg-sky-50 p-2`,children:[(0,V.jsxs)(`dt`,{className:`text-sm`,children:[t,` (`,M.conversion.currency,`)`]}),(0,V.jsx)(`dd`,{className:`font-semibold`,children:n})]},t)})})]}),(0,V.jsx)(`div`,{className:`overflow-x-auto`,children:(0,V.jsxs)(`table`,{className:`min-w-full text-xs`,children:[(0,V.jsx)(`caption`,{className:`sr-only`,children:`Resultados financeiros mensais antes de impostos`}),(0,V.jsx)(`thead`,{children:(0,V.jsx)(`tr`,{children:[`Mês`,`Facturação`,`Cobranças`,`Cobranças das vendas`,`Cobranças iniciais`,`Recuperações vencidas`,`Cobrança de valores de abertura`,`Valores de abertura por receber`,`Outras cobranças`,`Custos variáveis`,`Despesas/pessoal`,`Depreciação`,`Juros`,`Resultado antes de impostos`,`Pagamento de capital`,`Caixa final`].map(We)})}),(0,V.jsx)(`tbody`,{children:M.rows.map(Ue)})]})})]})]}),t[9]=n,t[10]=i,t[11]=g,t[12]=r,t[13]=s,t[14]=l,t[15]=_}else _=t[15];return _}function Ue(e){return(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:e.month}),(0,V.jsx)(`td`,{className:`p-2`,children:e.revenue}),(0,V.jsx)(`td`,{className:`p-2`,children:e.cashCollections}),(0,V.jsx)(`td`,{className:`p-2`,children:e.salesCollections??`manual`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.salesScheduledCollections??`—`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.salesRecoveryCollections??`—`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.openingReceivablesCollections}),(0,V.jsx)(`td`,{className:`p-2`,children:e.openingReceivablesBalance}),(0,V.jsx)(`td`,{className:`p-2`,children:e.otherCollections??`incluídas`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.variableCost}),(0,V.jsxs)(`td`,{className:`p-2`,children:[e.operatingExpenses,` /`,` `,e.payrollExpense]}),(0,V.jsx)(`td`,{className:`p-2`,children:e.depreciation}),(0,V.jsx)(`td`,{className:`p-2`,children:e.interestExpense}),(0,V.jsx)(`td`,{className:`p-2`,children:e.profitBeforeTax}),(0,V.jsx)(`td`,{className:`p-2`,children:e.principalRepayment}),(0,V.jsx)(`td`,{className:`p-2`,children:e.closingCash})]},e.month)}function We(e){return(0,V.jsx)(`th`,{className:`p-2 text-left`,children:e},e)}function Ge(e){return(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:e.month}),(0,V.jsx)(`td`,{className:`p-2`,children:e.opening}),(0,V.jsx)(`td`,{className:`p-2`,children:e.purchases}),(0,V.jsx)(`td`,{className:`p-2`,children:e.leadMonths}),(0,V.jsx)(`td`,{className:`p-2`,children:e.receipts}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inTransit}),(0,V.jsx)(`td`,{className:`p-2`,children:e.consumption}),(0,V.jsx)(`td`,{className:`p-2`,children:e.shortfall}),(0,V.jsx)(`td`,{className:`p-2`,children:e.closing})]},e.month)}function Ke(e){return(0,V.jsx)(`th`,{className:`p-2 text-left`,children:e},e)}function qe(e){return(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:e.month}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryOpening??`indeterminado`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryPurchases??`indeterminadas`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryLeadMonths??`indeterminado`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryReceipts??`indeterminadas`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryInTransit??`indeterminadas`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryConsumption}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryShortfall??`indeterminada`}),(0,V.jsx)(`td`,{className:`p-2`,children:e.inventoryClosing??`indeterminadas`})]},e.month)}function Je(e){return(0,V.jsx)(`th`,{className:`p-2 text-left`,children:e},e)}function Ye(e){return`${e.period}: ${e.amount}`}function Xe(e){return(0,V.jsx)(`th`,{className:`p-2 text-left`,children:e},e)}function Ze(e){let[t,n]=e;return(0,V.jsxs)(`div`,{className:`rounded bg-slate-50 p-2`,children:[(0,V.jsx)(`dt`,{className:`text-sm`,children:t}),(0,V.jsx)(`dd`,{className:`font-semibold`,children:n})]},t)}function Qe(e){let[t,n]=e;return(0,V.jsxs)(`tr`,{className:`border-t`,children:[(0,V.jsx)(`th`,{scope:`row`,className:`p-2`,children:t}),(0,V.jsxs)(`td`,{className:`p-2`,children:[`Unidades`,` `,n.adjustments.unitVolumePercent,`%; preço`,` `,n.adjustments.unitPricePercent,`%; custo variável`,` `,n.adjustments.unitCostPercent,`%; compras de stock ajustadas por volume/custo; despesas`,` `,n.adjustments.operatingCostsPercent,`%; cobranças`,` `,n.adjustments.cashCollectionsPercent,`%`]}),(0,V.jsx)(`td`,{className:`p-2`,children:n.result.totalRevenue}),(0,V.jsx)(`td`,{className:`p-2`,children:n.result.totalProfitBeforeTax}),(0,V.jsx)(`td`,{className:`p-2`,children:n.result.endingCash}),(0,V.jsx)(`td`,{className:`p-2`,children:n.result.inventoryProjection.endingInventory??`indeterminadas`}),(0,V.jsx)(`td`,{className:`p-2`,children:n.result.inventoryProjection.totalShortfall??`indeterminada`})]},t)}function $e(e){return(0,V.jsx)(`th`,{className:`p-2 text-left`,children:e},e)}function et(e){return(0,V.jsxs)(`option`,{value:e,children:[`Mês `,e]},e)}function tt(e,t){return t+1}function nt(e,t){return(0,V.jsxs)(`option`,{value:t+1,children:[`Mês `,t+1]},t+1)}function rt(e,t){return(0,V.jsxs)(`option`,{value:t,children:[t,` `,`mês(es)`]},t)}function it(e,t){return(0,V.jsx)(`option`,{value:t+1,children:t+1},t+1)}function at(e,t){return(0,V.jsxs)(`option`,{value:t,children:[t,` mês(es)`]},t)}function ot(e,t){return(0,V.jsxs)(`option`,{value:t,children:[t,` `,`mes(es)`]},t)}function st(e,t){return(0,V.jsxs)(`option`,{value:t,children:[t,` `,`mes(es)`]},t)}function ct(e){return(0,V.jsx)(`option`,{value:e,children:e},e)}function lt(e){return(0,V.jsx)(`option`,{value:e,children:e},e)}function ut(e){return e!==``}function dt(e){return e!==``}function ft(e){return e!==``}function pt(){return{amount:`0`,leadMonths:0}}var mt={monthly_net_estimate:`Vista pretendida: estimativa líquida mensal. A retenção mensal e o apuramento anual são resultados distintos.`,monthly_withholding:`Vista pretendida: retenção mensal. Este desconto não representa, por si só, o apuramento anual nem o cumprimento integral das obrigações fiscais.`,annual_assessment:`Vista pretendida: apuramento anual. As retenções mensais não substituem este apuramento.`};function ht(e){let t=(0,f.c)(22),{salaryView:n}=e,r,i,a,o,s,c,l;if(t[0]!==n){let e=new Date().toISOString().slice(0,10),u=se.map(t=>ce(t,e)),d=n?mt[n]:void 0;a=`space-y-3 rounded-lg border border-amber-400 bg-amber-50 p-4`,o=`fiscal-status-title`,t[8]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,V.jsx)(`h3`,{id:`fiscal-status-title`,className:`font-semibold`,children:`Componentes fiscais e contributivas`}),c=(0,V.jsx)(`p`,{className:`text-sm`,children:`Estas componentes estão indisponíveis para cálculo porque ainda não têm regras oficiais aprovadas, parâmetros vigentes e fontes associados. O estado indeterminado não representa imposto zero nem decisão fiscal.`}),t[8]=s,t[9]=c):(s=t[8],c=t[9]),t[10]===d?l=t[11]:(l=d&&(0,V.jsxs)(`p`,{role:`note`,className:`text-sm`,children:[d,` A selecção identifica apenas a pergunta; o resultado continua indeterminado e não é calculado.`]}),t[10]=d,t[11]=l),r=`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,i=u.map(gt),t[0]=n,t[1]=r,t[2]=i,t[3]=a,t[4]=o,t[5]=s,t[6]=c,t[7]=l}else r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];let u;t[12]!==r||t[13]!==i?(u=(0,V.jsx)(`ul`,{className:r,children:i}),t[12]=r,t[13]=i,t[14]=u):u=t[14];let d;return t[15]!==a||t[16]!==o||t[17]!==s||t[18]!==c||t[19]!==l||t[20]!==u?(d=(0,V.jsxs)(`section`,{className:a,"aria-labelledby":o,children:[s,c,l,u]}),t[15]=a,t[16]=o,t[17]=s,t[18]=c,t[19]=l,t[20]=u,t[21]=d):d=t[21],d}function gt(e){return(0,V.jsxs)(`li`,{className:`rounded border border-amber-200 bg-white p-3`,"aria-label":`${e.component}: indeterminado`,children:[(0,V.jsx)(`strong`,{children:e.component===`RETENCOES`?`Retenções`:e.component}),(0,V.jsx)(`p`,{className:`text-sm`,children:`Indeterminado — sem valor calculado`}),(0,V.jsx)(`p`,{className:`text-xs text-slate-600`,children:`Falta regra aprovada, parâmetros vigentes e classificação aplicável.`})]},e.component)}var _t=`investmoz-simulation-draft-v1`,vt=`investmoz-simulation-token-v1`,yt=`investmoz-simulation-idempotency-v1`,bt=`investmoz-simulation-draft-create-key-v1`,xt=`investmoz-simulation-draft-id-v1`,St=()=>crypto.randomUUID();function Ct(){let e=sessionStorage.getItem(vt);return e||(e=crypto.randomUUID().replaceAll(`-`,``)+crypto.randomUUID().replaceAll(`-`,``),sessionStorage.setItem(vt,e)),e}function wt(){return decodeURIComponent(document.cookie.split(`; `).find(e=>e.startsWith(`XSRF-TOKEN=`))?.slice(11)??``)}function Tt(e,t=``){return typeof e==`string`||typeof e==`number`&&Number.isFinite(e)?String(e):t}function Et(e){return{simulate_only:`Apenas simular`,own_investment:`Investimento próprio`,seek_investor:`Procurar investidor`,personal:`Particular`,small_business:`Pequeno negócio`,company:`Empresa`,investor:`Investidor`,simple:`Simples`,advanced:`Avançado`,seek_partner:`Procurar parceiro`,present_opportunity:`Apresentar oportunidade`,request_facilitation:`Solicitar facilitação`,investment:`Investimento`,business:`Negócio`,singular:`Pessoa singular`,collective:`Pessoa colectiva`,sole_trader:`Empresário em nome individual`,consortium:`Consórcio`,national:`Nacional`,foreign:`Estrangeiro`,mixed:`Misto`,existing:`Existente`,being_formed:`Em constituição`,"pt-MZ":`Português (Moçambique)`,en:`English`,portal:`Portal`,email:`Correio electrónico`,phone:`Telefone`,new:`Novo projecto`,expansion:`Expansão`,acquisition:`Aquisição`,partnership:`Parceria`,concession:`Concessão`,supplier:`Fornecedor`,buyer:`Comprador`,other:`Outro`,idea:`Ideia`,concept:`Conceito`,pre_feasibility:`Pré-viabilidade`,feasibility:`Viabilidade`,financing:`Financiamento`,implementation:`Implementação`,operation:`Operação`,owned:`Propriedade`,irpc:`IRPC`,iva:`IVA`,ispc:`ISPC`,irps:`IRPS`,inss:`INSS`,withholding:`Retenções na fonte`,customs_ice:`ICE e direitos aduaneiros`,2025:`2025`,2026:`2026`,2027:`2027`,monthly:`Mensal`,quarterly:`Trimestral`,annual:`Anual`,one_off:`Operação pontual`,monthly_net_estimate:`Estimativa mensal líquida`,monthly_withholding:`Retenção mensal`,annual_assessment:`Apuramento anual`,employment:`Trabalho`,rental:`Predial`,digital:`Digital`,capital_gain:`Mais-valias`,self_reported_resident:`Indico que sou residente`,self_reported_non_resident:`Indico que não sou residente`,domestic:`Operação em Moçambique`,non_resident:`Operação com não residente`,import:`Importação`,export:`Exportação`,refund:`Crédito ou reembolso de IVA`,documented:`Documentada`,partly_documented:`Parcialmente documentada`,not_documented:`Sem documentação disponível`,estimate_only:`Crédito apenas estimado`,request_filed:`Pedido apresentado`,recognized:`Montante reconhecido`,received:`Montante recebido`,duat:`DUAT`,leased:`Arrendado`,requested:`Solicitado`,unknown:`Por determinar`,MZN:`MZN`,USD:`USD`,EUR:`EUR`,ZAR:`ZAR`,A:`Categoria A`,B:`Categoria B`,C:`Categoria C`,por_determinar:`Por determinar`,offer:`Oferta`,demand:`Procura`,both:`Oferta e procura`,capital:`Capital`,partner:`Parceiro`,land:`Terreno`,technology:`Tecnologia`,licence:`Licença`,services:`Serviços`,public:`Público`,registered_users:`Utilizadores registados`,restricted:`Restrito`,confidential:`Confidencial`,yes:`Sim`,no:`Não`,energy:`Energia`}[e]??e.replaceAll(`_`,` `)}function Dt(e,t,n,r){let[i,a]=(0,d.useState)([]),[o,s]=(0,d.useState)(!1),[c,l]=(0,d.useState)(``),u=(0,d.useMemo)(()=>e===`currency`?(Intl.supportedValuesOf?.(`currency`)??[]).map(e=>({id:e,label:e})):!e||[`country`,`province`,`district`,`admin_post`,`locality`,`sector`,`activity`].includes(e)?[]:(_[e]??[]).map(e=>({id:e,label:Et(e)})),[e]);return(0,d.useEffect)(()=>{if(!r||!e||![`country`,`province`,`district`,`admin_post`,`locality`,`sector`,`activity`].includes(e)){a(u),l(``);return}if([`district`,`admin_post`,`locality`,`activity`].includes(e)&&!n){a([]);return}let i=new AbortController,o=window.setTimeout(async()=>{s(!0),l(``);try{let r;e===`sector`?r=new URL(`/api/v1/sectors`,window.location.origin):(r=new URL(`/api/v1/catalogs/`+(e===`activity`?`economic-activities`:`jurisdictions`),window.location.origin),r.searchParams.set(`q`,t),r.searchParams.set(`per_page`,`50`),e===`activity`?r.searchParams.set(`sector_id`,n):(r.searchParams.set(`type`,e===`country`?`country`:e),n&&r.searchParams.set(`parent_id`,n)));let o=await fetch(r,{signal:i.signal,headers:{Accept:`application/json`},credentials:`same-origin`});if(!o.ok)throw Error(`Não foi possível carregar as opções. Tente novamente.`);let s=(await o.json()).data??[];a(s.map(e=>({id:Tt(e.id??e.value),label:Tt(e.label??e.name)})).filter(e=>e.id&&e.label))}catch(e){i.signal.aborted||l(e instanceof Error?e.message:`Erro ao carregar opções.`)}finally{i.signal.aborted||s(!1)}},180);return()=>{window.clearTimeout(o),i.abort()}},[e,t,n,r,u]),{choices:i,loading:o,error:c,retry:()=>l(``)}}function Ot({label:e,source:t,parent:n=``,value:r,selectedLabel:i,multiple:a,disabled:o,error:s,required:c,onChange:l}){let u=`choice-${(0,d.useId)()}`,f=`${u}-options`,p=(0,d.useRef)(null),[m,h]=(0,d.useState)(``),[g,_]=(0,d.useState)(!1),[y,b]=(0,d.useState)(-1),{choices:x,loading:S,error:C}=Dt(t,m,n,!o&&g),w=Array.isArray(r)?r:r?[r]:[],T=x.filter(e=>e.label.toLocaleLowerCase().includes(m.toLocaleLowerCase())||e.id.toLocaleLowerCase().includes(m.toLocaleLowerCase()));(0,d.useEffect)(()=>{g&&p.current?.scrollIntoView({block:`nearest`})},[y,g]);let E=[s?`${u}-error`:``,C?`${u}-load-error`:``].filter(Boolean).join(` `)||void 0,D=e=>{a?(w.includes(e.id)||l([...w,e.id],[...Array.isArray(i)?i:[],e.label]),h(``)):(l(e.id,e.label),h(``),_(!1))};return(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`label`,{htmlFor:u,className:`block text-sm font-medium`,children:e}),(0,V.jsx)(`input`,{id:u,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":g,"aria-controls":g&&!o?f:void 0,"aria-activedescendant":g&&T[y]?`${f}-${y}`:void 0,"aria-invalid":!!(s||C),"aria-required":c||void 0,"aria-describedby":E,autoComplete:`off`,className:`w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700 disabled:bg-slate-100`,value:g?m:a?``:i||(w[0]?x.find(e=>e.id===w[0])?.label??w[0]:``),placeholder:o?`Seleccione primeiro o campo anterior`:`Pesquisar opções…`,disabled:o,onFocus:()=>{_(!0),h(``),b(-1)},onBlur:()=>{window.setTimeout(()=>_(!1),120)},onChange:e=>{h(e.target.value),b(0),_(!0)},onKeyDown:e=>{e.key===`ArrowDown`&&(e.preventDefault(),_(!0),b(e=>v(e,1,T.length))),e.key===`ArrowUp`&&(e.preventDefault(),b(e=>v(e,-1,T.length))),e.key===`Enter`&&g&&T[y]&&(e.preventDefault(),D(T[y])),e.key===`Escape`&&(_(!1),h(``)),e.key===`Backspace`&&a&&m===``&&w.length&&l(w.slice(0,-1),Array.isArray(i)?i.slice(0,-1):[])}}),a&&w.length>0&&(0,V.jsx)(`ul`,{"aria-label":`Opções seleccionadas: ${e}`,className:`flex flex-wrap gap-2`,children:w.map((e,t)=>{let n=Array.isArray(i)?i[t]:x.find(t=>t.id===e)?.label??e;return(0,V.jsxs)(`li`,{className:`flex items-center gap-1 rounded bg-emerald-50 px-2 py-1 text-sm`,children:[n,(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remover ${n}`,onClick:()=>l(w.filter((e,n)=>n!==t),Array.isArray(i)?i.filter((e,n)=>n!==t):[]),className:`rounded px-1 focus-visible:outline-2`,children:`×`})]},e)})}),g&&!o&&(0,V.jsxs)(V.Fragment,{children:[S&&(0,V.jsx)(`output`,{className:`block p-3 text-sm`,"aria-live":`polite`,children:`A carregar opções…`}),!S&&T.length===0&&(0,V.jsx)(`p`,{className:`p-3 text-sm`,children:`Sem opções correspondentes.`}),(0,V.jsx)(`div`,{id:f,role:`listbox`,"aria-label":e,"aria-multiselectable":a||void 0,className:`max-h-56 overflow-auto rounded border bg-white shadow-lg`,children:!S&&T.map((e,t)=>(0,V.jsxs)(`div`,{id:`${f}-${t}`,role:`option`,tabIndex:-1,ref:y===t?p:void 0,"aria-selected":w.includes(e.id),className:`cursor-pointer p-3 text-sm hover:bg-emerald-50 ${y===t?`bg-emerald-50`:``}`,onMouseEnter:()=>b(t),onMouseDown:e=>e.preventDefault(),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),D(e))},onClick:()=>D(e),children:[e.label,w.includes(e.id)?` ✓`:``]},e.id))})]}),C&&(0,V.jsx)(`p`,{id:`${u}-load-error`,role:`alert`,className:`text-sm text-red-800`,children:C}),s&&(0,V.jsx)(`p`,{id:`${u}-error`,role:`alert`,className:`text-sm text-red-800`,children:s})]})}function kt(){let{auth:e}=s().props,t=!!e?.user,[n,r]=(0,d.useState)({}),[i,a]=(0,d.useState)(!1),[o,c]=(0,d.useState)(0),[l,u]=(0,d.useState)({}),[f,p]=(0,d.useState)(`Rascunho ainda não guardado.`),[m,_]=(0,d.useState)(``),[v,x]=(0,d.useState)(!1),[O,j]=(0,d.useState)(!1),[M,N]=(0,d.useState)(null),P=(0,d.useMemo)(()=>D(M?.result_snapshot),[M]),F=(0,d.useMemo)(()=>{let e=M?.result_snapshot;return e&&typeof e==`object`&&!Array.isArray(e)?e:null},[M]),I=(0,d.useMemo)(()=>k(M),[M]),L=P.integrity===`versioned`&&I===null,[R,z]=(0,d.useState)([]),[ee,te]=(0,d.useState)(!1),[ne,re]=(0,d.useState)(``),[ie,ae]=(0,d.useState)(!1),[oe,se]=(0,d.useState)([]),[ce,B]=(0,d.useState)(1),[le,ue]=(0,d.useState)(1),[de,H]=(0,d.useState)(``),[pe,me]=(0,d.useState)(!1),he=(0,d.useRef)(!1),ge=(0,d.useRef)(null),_e=(0,d.useRef)(null),ve=(0,d.useRef)(null),ye=(0,d.useRef)(Promise.resolve()),be=(0,d.useRef)(!1),U=h(n),W=U[Math.min(o,U.length-1)],G=(y[W.id]??[]).filter(e=>(!e.showWhen||e.showWhen(n))&&(n.detail_level===`advanced`||!g.has(e.key))),xe=M?.status===`completed`&&typeof M.id==`string`?M.id:``,Se=!!(xe&&R.some(e=>e.simulation_id===xe)),K=(0,d.useCallback)(async(e=1)=>{me(!0),H(``);try{let t=await fetch(`/api/v1/simulations/history?page=${e}&per_page=10`,{credentials:`same-origin`,headers:{Accept:`application/json`}});if(t.status===403)throw Error(`Verifique o correio electrónico para consultar o histórico.`);if(t.status===401)throw Error(`Inicie sessão para consultar o histórico.`);if(!t.ok)throw Error(`Não foi possível carregar o histórico da conta.`);let n=await t.json();se(Array.isArray(n.data)?n.data:[]),B(Number(n.meta?.current_page??e)),ue(Number(n.meta?.last_page??1))}catch(e){H(e instanceof Error?e.message:`Falha ao carregar o histórico.`)}finally{me(!1)}},[]);(0,d.useEffect)(()=>{t&&K()},[t,K]);async function we(e){H(``);try{let t=await fetch(`/api/v1/simulations/${encodeURIComponent(e)}`,{credentials:`same-origin`,headers:{Accept:`application/json`}});if(!t.ok)throw Error(`Não foi possível abrir esta simulação.`);let n=await t.json();N(n.data??null),document.getElementById(`simulator-step-title`)?.focus()}catch(e){H(e instanceof Error?e.message:`Falha ao abrir a simulação.`)}}(0,d.useEffect)(()=>{let e=!1;return(async()=>{let t={};try{let e=sessionStorage.getItem(_t);e&&(t=JSON.parse(e))}catch{p(`Não foi possível recuperar o rascunho desta sessão.`)}try{let e=await fetch(`/api/v1/simulation-drafts/current`,{credentials:`same-origin`,headers:{Accept:`application/json`,"X-Simulation-Token":Ct()}});if(e.ok){let n=await e.json();if(n.data){ge.current=n.data.id,_e.current=e.headers.get(`ETag`),sessionStorage.setItem(xt,n.data.id);let i=w(n.data.economic_snapshot,n.data.personal_snapshot);z(Array.isArray(n.data.simulation_sources)?n.data.simulation_sources:[]),ve.current=T(i),r({...i,...t}),p(`Rascunho recuperado do servidor.`)}else Object.keys(t).length&&(sessionStorage.getItem(xt)&&sessionStorage.removeItem(xt),r(t))}else Object.keys(t).length&&r(t)}catch{Object.keys(t).length&&r(t),p(`Sem ligação ao servidor; o rascunho desta sessão será mantido localmente.`)}e||a(!0)})(),()=>{e=!0}},[]),(0,d.useEffect)(()=>{if(!i||!n.purpose)return;let e=window.setTimeout(()=>{try{sessionStorage.setItem(_t,JSON.stringify(S(n)))}catch{p(`Não foi possível guardar o rascunho neste navegador.`)}if(be.current)return;let e=C(n,t),r=T(t?n:S(n));r!==ve.current&&(p(`A guardar o rascunho no servidor…`),ye.current=ye.current.then(async()=>{let t=Ct(),i={Accept:`application/json`,"Content-Type":`application/json`,"X-XSRF-TOKEN":wt(),"X-Simulation-Token":t};if(!ge.current){let e=await fetch(`/api/v1/simulation-drafts/current`,{credentials:`same-origin`,headers:{Accept:`application/json`,"X-Simulation-Token":t}}),n=e.ok?await e.json():{data:null};n.data&&(ge.current=n.data.id,_e.current=e.headers.get(`ETag`),sessionStorage.setItem(xt,n.data.id))}let a;if(ge.current&&_e.current)a=await fetch(`/api/v1/simulation-drafts/${ge.current}`,{method:`PUT`,credentials:`same-origin`,headers:{...i,"If-Match":_e.current},body:JSON.stringify(e)});else{let t=sessionStorage.getItem(bt);t||(t=St(),sessionStorage.setItem(bt,t)),a=await fetch(`/api/v1/simulation-drafts`,{method:`POST`,credentials:`same-origin`,headers:{...i,"Idempotency-Key":t},body:JSON.stringify(e)})}if(a.status===412||a.status===428){be.current=!0,j(!0),p(`O rascunho mudou noutro separador. Recarregue para rever a versão mais recente.`);return}let o=await a.json();if(!a.ok)throw Error(o.message??`Não foi possível guardar o rascunho no servidor.`);ge.current=o.data.id,_e.current=a.headers.get(`ETag`),ve.current=r,sessionStorage.setItem(xt,o.data.id),sessionStorage.removeItem(bt),n.reuse_simulation===`no`&&z([]),p(`Rascunho guardado no servidor às ${new Intl.DateTimeFormat(`pt-MZ`,{timeStyle:`short`}).format(new Date)}.`)}).catch(e=>{p(e instanceof Error?e.message:`Erro ao guardar o rascunho no servidor.`)}))},450);return()=>window.clearTimeout(e)},[n,i,t]);function q(e,t,n){r(r=>{let i=b(r,e,t);return n&&(i[`${e}_label`]=n),i}),u(t=>{let n={...t};return delete n[e],n}),e===`purpose`&&c(0),e!==`purpose`&&N(null)}async function Te(){if(await ye.current,ge.current&&_e.current&&!(await fetch(`/api/v1/simulation-drafts/${ge.current}`,{method:`DELETE`,credentials:`same-origin`,headers:{Accept:`application/json`,"X-XSRF-TOKEN":wt(),"X-Simulation-Token":Ct(),"If-Match":_e.current}})).ok){p(`Não foi possível remover o rascunho do servidor. Recarregue e tente novamente.`);return}for(let e of[_t,xt,bt,yt,vt])sessionStorage.removeItem(e);ge.current=null,_e.current=null,ve.current=null,be.current=!1,j(!1),r({}),N(null),u({}),c(0),p(`Rascunho removido do servidor e desta sessão.`)}function Ee(e){if(e>o)for(let t=o;t<e;t++){let e=E(n,U[t].id);if(Object.keys(e).length){c(t),u(e),window.requestAnimationFrame(()=>document.getElementById(`field-${Object.keys(e)[0]}`)?.focus());return}}c(e),u({}),document.getElementById(`simulator-step-title`)?.focus()}async function De(){if(he.current)return;let e=E(n,`tax`);if(u(e),_(``),n.tax_calculation===`yes`){if(Object.keys(e).length){document.getElementById(`field-${Object.keys(e)[0]}`)?.focus();return}he.current=!0,x(!0);try{let e=Ct(),r=wt(),i={base:n.base,rate:n.rate,reduction:n.reduction},a=JSON.stringify(i),o=sessionStorage.getItem(yt),s=``;if(o)try{let e=JSON.parse(o);e.payload===a&&e.key&&(s=e.key)}catch{}s||(s=St(),sessionStorage.setItem(yt,JSON.stringify({payload:a,key:s})));let c=await fetch(`/api/v1/simulations`,{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-XSRF-TOKEN":r,"Idempotency-Key":s,"X-Simulation-Token":e},body:a}),l=await c.json();if(!c.ok){if(c.status===429){let e=Number(c.headers.get(`Retry-After`)??60);throw Error(`Demasiadas tentativas. Aguarde ${e} segundos antes de voltar a calcular.`)}let e=l.errors?Object.values(l.errors).flat().join(` `):l.message;throw Error(typeof e==`string`?e:`Não foi possível validar o cenário no servidor.`)}let u=l.data?.id,d=l.data;if(u&&d?.status!==`completed`&&d?.status!==`failed`){p(`Cenário enviado. A aguardar o cálculo…`);for(let t=0;t<12;t++){await new Promise(e=>window.setTimeout(e,1e3));let t=await fetch(`/api/v1/simulations/${u}`,{credentials:`same-origin`,headers:{Accept:`application/json`,"X-Simulation-Token":e}});if(!t.ok||(d=(await t.json()).data,d?.status===`completed`||d?.status===`failed`))break}}JSON.stringify({base:n.base,rate:n.rate,reduction:n.reduction})===a&&N(d??null),t&&K(),sessionStorage.removeItem(yt)}catch(e){_(e instanceof Error?e.message:`Erro de ligação. Tente novamente.`)}finally{he.current=!1,x(!1)}}}async function J(){let e=typeof M?.id==`string`?M.id:``;if(!(!e||!ee||O||ie)){re(``),ae(!0);try{await ye.current;let t=Ct(),n={Accept:`application/json`,"Content-Type":`application/json`,"X-XSRF-TOKEN":wt(),"X-Simulation-Token":t},i=await fetch(`/api/v1/simulation-drafts/current`,{credentials:`same-origin`,headers:{Accept:`application/json`,"X-Simulation-Token":t}}),a=(i.ok?await i.json():{data:null}).data?.id;if(typeof a!=`string`||!a)throw Error(`Guarde primeiro o rascunho; depois poderá anexar a simulação.`);let o=a;if(ge.current=o,_e.current=i.headers.get(`ETag`),!_e.current)throw Error(`O servidor não devolveu a versão actual do rascunho. Recarregue e tente novamente.`);let s=await fetch(`/api/v1/simulation-drafts/${o}/conversions`,{method:`POST`,credentials:`same-origin`,headers:{...n,"If-Match":_e.current},body:JSON.stringify({simulation_id:e,consent_reuse:!0})}),c=await s.json();if(s.status===412||s.status===428)throw be.current=!0,j(!0),Error(`O rascunho mudou noutro separador. Recarregue antes de anexar a simulação.`);if(!s.ok)throw Error(c.message??`Não foi possível anexar a simulação ao rascunho.`);_e.current=s.headers.get(`ETag`);let l=c.data?.simulation_sources;Array.isArray(l)&&z(l),r(e=>({...e,reuse_simulation:`yes`})),sessionStorage.setItem(xt,o),te(!1),p(c.replayed?`Esta simulação já estava anexada ao rascunho.`:`Simulação anexada ao rascunho com o seu consentimento.`)}catch(e){re(e instanceof Error?e.message:`Não foi possível anexar a simulação.`)}finally{ae(!1)}}}return(0,V.jsxs)(`section`,{className:`space-y-6 rounded-xl border bg-white p-4 sm:p-6`,"aria-labelledby":`simulator-step-title`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h2`,{id:`simulator-step-title`,tabIndex:-1,className:`text-xl font-bold outline-none`,children:`Formulário de simulação e manifestação`}),(0,V.jsx)(`p`,{className:`mt-1 text-sm text-slate-700`,children:`Simulação informativa. Nenhuma taxa legal, elegibilidade ou moeda é presumida.`}),(0,V.jsx)(`p`,{className:`mt-1 text-xs text-slate-600`,children:`Sem sessão autenticada, identidade e contactos não são enviados nem guardados no servidor; só permanecem nesta página. Inicie sessão para guardar esses dados na sua conta e recuperar o rascunho mais tarde.`})]}),(0,V.jsx)(`output`,{"aria-live":`polite`,className:`block text-sm`,children:f})]}),t&&(0,V.jsxs)(`section`,{"aria-labelledby":`simulation-history-title`,className:`rounded-lg border bg-slate-50 p-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h3`,{id:`simulation-history-title`,className:`font-semibold`,children:`Histórico da sua conta`}),(0,V.jsx)(`p`,{className:`text-sm text-slate-700`,children:`Simulações pessoais e de organizações às quais tem acesso. Execuções anónimas não ficam associadas à conta.`})]}),(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2`,disabled:pe,onClick:()=>void K(ce),children:pe?`A carregar…`:`Actualizar histórico`})]}),de&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-red-800`,children:de}),oe.length===0&&!pe&&!de&&(0,V.jsx)(`p`,{className:`mt-3 text-sm`,children:`Ainda não existem simulações guardadas nesta conta.`}),oe.length>0&&(0,V.jsx)(`ul`,{className:`mt-3 divide-y`,children:oe.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center justify-between gap-3 py-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`p`,{className:`font-medium`,children:[e.status===`completed`?`Concluída`:e.status===`failed`?`Falhou`:e.status===`queued`?`Na fila`:`Em processamento`,e.scope===`organization`&&e.organization_name?` · ${e.organization_name}`:``]}),(0,V.jsxs)(`p`,{className:`text-sm text-slate-700`,children:[e.created_at?new Date(e.created_at).toLocaleString(`pt-MZ`):`Data indisponível`,` `,`· versão `,e.version_no,e.has_ready_report?` · relatório disponível`:``]})]}),(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2`,onClick:()=>void we(e.id),children:`Abrir resultado`})]},e.id))}),le>1&&(0,V.jsxs)(`div`,{className:`mt-3 flex items-center justify-end gap-2`,children:[(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2`,disabled:pe||ce<=1,onClick:()=>void K(ce-1),children:`Anterior`}),(0,V.jsxs)(`span`,{"aria-live":`polite`,className:`text-sm`,children:[ce,`/`,le]}),(0,V.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2`,disabled:pe||ce>=le,onClick:()=>void K(ce+1),children:`Seguinte`})]})]}),(0,V.jsx)(`nav`,{"aria-label":`Etapas do formulário`,className:`overflow-x-auto`,children:(0,V.jsx)(`ol`,{className:`flex min-w-max gap-2`,children:U.map((e,t)=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`button`,{type:`button`,"aria-current":o===t?`step`:void 0,onClick:()=>Ee(t),className:`rounded-full border px-3 py-2 text-sm focus-visible:outline-2 ${o===t?`border-emerald-800 bg-emerald-800 text-white`:`bg-white`}`,children:[t+1,`. `,e.title]})},e.id))})}),(0,V.jsx)(`progress`,{className:`h-2 w-full accent-emerald-800`,"aria-label":`Progresso do formulário`,max:100,value:Math.round((o+1)/U.length*100)}),(0,V.jsx)(`h3`,{className:`text-lg font-semibold`,children:W.title}),W.id===`purpose`&&n.journey_type&&(0,V.jsx)(`output`,{className:`block rounded bg-sky-50 p-3 text-sm`,children:n.journey_type===`personal`?`Percurso para planeamento pessoal. Pode explorar os valores sem criar conta.`:n.journey_type===`small_business`?`Percurso simplificado para pequenos negócios, com pressupostos financeiros editáveis.`:n.journey_type===`company`?`Percurso completo para projectos empresariais e estruturas de financiamento.`:`Percurso para investidores analisarem projectos e necessidades de negócio.`}),(0,V.jsx)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:G.map(e=>{let t=l[e.key];if(e.options){let r=e.key===`district_id`?`province_id`:e.key===`admin_post_id`?`district_id`:e.key===`locality_id`?`admin_post_id`:e.key===`activity_id`?`sector_id`:``;return(0,V.jsx)(`div`,{id:`field-${e.key}`,tabIndex:-1,children:(0,V.jsx)(Ot,{label:`${e.label}${e.required?` (obrigatório)`:``}`,source:e.options,parent:r?String(n[r]??``):``,value:n[e.key]??(e.multiple?[]:``),selectedLabel:n[`${e.key}_label`],multiple:e.multiple,disabled:!!(r&&!n[r]),error:t,required:e.required,onChange:(t,n)=>q(e.key,t,n)})},e.key)}let r=[`area_required`].includes(e.key);return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`label`,{htmlFor:`field-${e.key}`,className:`mb-1 block text-sm font-medium`,children:[e.label,e.required?` (obrigatório)`:``]}),e.type===`textarea`?(0,V.jsx)(`textarea`,{id:`field-${e.key}`,className:`min-h-28 w-full rounded-lg border border-slate-300 p-3 focus-visible:outline-2 focus-visible:outline-emerald-700`,value:String(n[e.key]??``),onChange:t=>q(e.key,t.target.value),"aria-invalid":!!t,"aria-required":e.required||void 0,"aria-describedby":t?`error-${e.key}`:void 0}):(0,V.jsx)(`input`,{id:`field-${e.key}`,type:e.type??(r?`number`:`text`),min:e.type===`number`?`0`:void 0,step:e.type===`number`?`any`:void 0,className:`w-full rounded-lg border border-slate-300 p-3 focus-visible:outline-2 focus-visible:outline-emerald-700`,value:String(n[e.key]??``),onChange:t=>q(e.key,t.target.value),"aria-invalid":!!t,"aria-required":e.required||void 0,"aria-describedby":t?`error-${e.key}`:void 0}),t&&(0,V.jsx)(`p`,{id:`error-${e.key}`,role:`alert`,className:`mt-1 text-sm text-red-800`,children:t}),e.key===`reduction`&&(0,V.jsx)(`p`,{className:`mt-1 text-sm text-slate-600`,children:`Hipótese sua, não representa um benefício fiscal aprovado.`})]},e.key)})}),W.id===`financial`&&(0,V.jsx)(`p`,{className:`rounded bg-amber-50 p-3 text-sm`,children:`Os montantes são introduzidos pelo utilizador. Confirme que capital, dívida e subvenções reconciliam com o investimento total.`}),(W.id===`financial`||n.purpose===`simulate_only`&&W.id===`tax`)&&(0,V.jsx)(fe,{currency:String(n.currency??``),snapshot:String(n.financial_tools_snapshot??``),onSnapshotChange:e=>q(`financial_tools_snapshot`,e),onCurrencyChange:e=>q(`currency`,e)}),(W.id===`financial`||n.purpose===`simulate_only`&&W.id===`tax`)&&(0,V.jsx)(Ce,{currency:String(n.currency??``),onCurrencyChange:e=>q(`currency`,e)}),W.id===`financial`&&n.detail_level===`advanced`&&n.purpose!==`simulate_only`&&(0,V.jsx)(He,{currency:String(n.currency??``),snapshot:String(n.business_plan_snapshot??``),onCurrencyChange:e=>q(`currency`,e),onSnapshotChange:e=>q(`business_plan_snapshot`,e)}),W.id===`tax`&&(0,V.jsx)(ht,{salaryView:String(n.irps_salary_view??``)}),W.id===`tax`&&(0,V.jsx)(`p`,{className:`rounded border border-amber-300 bg-amber-50 p-3 text-sm`,children:`O período e as respostas servem para encaminhar uma exploração informativa. A residência é auto-indicada ou fica por determinar; não é inferida por nacionalidade ou dias de presença. Regras de 2026 continuam pendentes de validação e este formulário não determina cumprimento fiscal. Um crédito estimado de IVA não significa pedido aprovado nem dinheiro disponível. Não carregue documentos nesta simulação exploratória.`}),W.id===`tax`&&(0,V.jsxs)(`div`,{className:`space-y-3 border-t pt-4`,children:[(0,V.jsx)(`h4`,{className:`font-semibold`,children:`Executar cenário aritmético`}),n.tax_calculation===`yes`&&(0,V.jsx)(`button`,{type:`button`,disabled:v,"aria-busy":v,className:`rounded-lg bg-emerald-800 px-4 py-3 font-semibold text-white focus-visible:outline-2 disabled:cursor-wait disabled:opacity-60`,onClick:()=>void De(),children:v?`A calcular…`:`Validar e calcular no servidor`}),m&&(0,V.jsx)(`p`,{role:`alert`,className:`text-red-800`,children:m}),M&&(0,V.jsxs)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:`rounded bg-emerald-50 p-4`,children:[(0,V.jsxs)(`p`,{children:[`Simulação`,` `,Tt(M.status,`recebida`),`.`]}),M.status===`completed`&&(0,V.jsxs)(`p`,{children:[`Resultado aritmético indicativo:`,` `,(0,V.jsx)(`strong`,{children:Tt(P.value??(P.integrity===`invalid`?`indisponível: snapshot inconsistente`:`disponível no relatório`),P.integrity===`invalid`?`indisponível: snapshot inconsistente`:`disponível no relatório`)})]}),M.status===`failed`&&(0,V.jsx)(`p`,{role:`alert`,children:`O cálculo não foi concluído. Reveja os valores e tente novamente.`}),M.status===`queued`||M.status===`running`?(0,V.jsx)(`p`,{className:`text-sm`,children:`O cálculo continua pendente. Pode consultar o histórico quando estiver disponível.`}):null,(0,V.jsx)(`p`,{className:`text-sm`,children:`O resultado é indicativo e não determina taxas legais, elegibilidade ou obrigação fiscal.`}),M.status===`completed`&&(0,V.jsxs)(`div`,{className:`mt-3 space-y-2 border-t pt-3`,children:[P.integrity!==`invalid`&&(0,V.jsxs)(`details`,{className:`rounded border p-3`,children:[(0,V.jsx)(`summary`,{className:`cursor-pointer font-semibold focus-visible:outline-2`,children:`Detalhes do cálculo e da versão`}),(0,V.jsxs)(`dl`,{className:`mt-3 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Base introduzida`}),(0,V.jsx)(`dd`,{children:Tt(F?.base,`não disponível`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Taxa introduzida (%)`}),(0,V.jsx)(`dd`,{children:Tt(F?.rate_percent,`não disponível`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Redução hipotética (%)`}),(0,V.jsx)(`dd`,{children:Tt(F?.reduction_percent,`não disponível`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Moeda`}),(0,V.jsx)(`dd`,{children:Tt(F?.currency,`não fornecida`)})]}),P.context&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Período`}),(0,V.jsx)(`dd`,{children:`Cálculo pontual; sem período fiscal atribuído`})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Data de referência`}),(0,V.jsx)(`dd`,{children:Tt(P.context.reference_date,`não disponível`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Versão do motor`}),(0,V.jsx)(`dd`,{children:Tt(P.context.engine_version,`não identificada`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Versão do cenário`}),(0,V.jsx)(`dd`,{children:Tt(P.context.scenario_version,`não identificada`)})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`Versão da fórmula`}),(0,V.jsx)(`dd`,{children:Tt(F?.formula_version,`não identificada`)})]})]}),P.integrity===`versioned`&&I&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`ID do relatório imutável`}),(0,V.jsx)(`dd`,{className:`break-all`,children:I.id})]}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`dt`,{className:`font-medium`,children:`SHA-256 do relatório`}),(0,V.jsx)(`dd`,{className:`break-all`,children:I.report_sha256})]})]})]}),(0,V.jsx)(`p`,{className:`mt-3 text-sm`,children:`Fórmula genérica: base × taxa percentual ÷ 100 × (1 − redução percentual ÷ 100). Não foram aplicadas regras fiscais nem associadas fontes legais; os parâmetros foram introduzidos pelo utilizador.`}),P.explanation&&(0,V.jsx)(`p`,{className:`mt-2 text-sm`,children:P.explanation})]}),(0,V.jsx)(`button`,{type:`button`,disabled:P.integrity===`invalid`||L,className:`rounded border px-3 py-2 text-sm focus-visible:outline-2`,onClick:()=>{let e=new Blob([A(M)],{type:`text/csv;charset=utf-8`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`simulacao-aritmetica-${Tt(M.id,`resultado`).slice(0,8)}.csv`,n.click(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3)},children:`Exportar resultado em CSV`}),P.integrity===`invalid`&&(0,V.jsx)(`p`,{role:`alert`,className:`text-sm text-red-800`,children:`O snapshot do resultado está inconsistente; exportação e conversão foram desactivadas.`}),L&&(0,V.jsx)(`p`,{role:`alert`,className:`text-sm text-amber-900`,children:`O relatório imutável ainda não está disponível ou não corresponde a esta revisão. Exportação e conversão estão desactivadas.`}),(0,V.jsx)(`p`,{className:`text-sm`,children:`Pode copiar este resultado versionado para o rascunho de investimento. A cópia preserva entradas, fórmula e relatório; não cria um projecto, não envia dados ao CRM e não valida uma obrigação fiscal.`}),n.purpose===`simulate_only`?(0,V.jsx)(`output`,{className:`block text-sm`,children:`Para converter, escolha uma finalidade de investimento no primeiro passo. O resultado continuará disponível enquanto não alterar os seus pressupostos.`}):Se?(0,V.jsxs)(`output`,{className:`block text-sm`,children:[`Este resultado já foi anexado ao rascunho (`,R.find(e=>e.simulation_id===xe)?.report_sha256.slice(0,12),`…).`]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,V.jsx)(`input`,{type:`checkbox`,checked:ee,onChange:e=>te(e.target.checked),className:`mt-1`}),`Autorizo copiar este resultado e os pressupostos associados para o rascunho cifrado desta sessão/conta.`]}),(0,V.jsx)(`button`,{type:`button`,disabled:!ee||ie||O||P.integrity===`invalid`||L,"aria-busy":ie,onClick:()=>void J(),className:`rounded border px-3 py-2 text-sm focus-visible:outline-2 disabled:opacity-50`,children:ie?`A anexar…`:`Converter e anexar ao rascunho`}),ne&&(0,V.jsx)(`p`,{role:`alert`,className:`text-sm text-red-800`,children:ne})]}),R.length>0&&(0,V.jsxs)(`details`,{className:`text-xs`,children:[(0,V.jsxs)(`summary`,{children:[`Resultados anexados (`,R.length,`)`]}),(0,V.jsx)(`ul`,{className:`mt-1 space-y-2 pl-5`,children:R.map(e=>{let t=D(e.result_snapshot);return(0,V.jsxs)(`li`,{className:`list-disc`,children:[`Execução`,` `,e.simulation_id,` `,`· versão`,` `,e.source_version_no,` `,`· fórmula`,` `,Tt(e.result_snapshot.formula_version??`não identificada`,`não identificada`),` `,`· resultado aritmético`,` `,Tt(t.value??(t.integrity===`invalid`?`oculto: snapshot inconsistente`:`indisponível`),t.integrity===`invalid`?`oculto: snapshot inconsistente`:`indisponível`),` `,t.integrity===`versioned`&&(0,V.jsxs)(V.Fragment,{children:[`· contrato v1 ·`,` `,Tt(t.context?.reference_date,`data indisponível`),` `,`·`,` `,Tt(t.context?.engine_version,`motor não identificado`),` `]}),`· hash`,` `,e.report_sha256]},e.simulation_id)})}),(0,V.jsx)(`p`,{className:`mt-2`,children:`O hash e a versão identificam a cópia preservada; este valor permanece indicativo e não é uma conclusão fiscal.`})]})]})]})]}),O&&(0,V.jsxs)(`p`,{role:`alert`,className:`rounded border border-amber-700 bg-amber-50 p-3`,children:[`Este rascunho foi alterado noutro separador.`,` `,(0,V.jsx)(`button`,{type:`button`,className:`font-semibold underline`,onClick:()=>window.location.reload(),children:`Recarregar a versão mais recente`})]}),(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-between gap-3 border-t pt-4`,children:[(0,V.jsx)(`button`,{type:`button`,disabled:o===0,onClick:()=>Ee(Math.max(0,o-1)),className:`rounded border px-4 py-3 focus-visible:outline-2 disabled:opacity-50`,children:`Anterior`}),o<U.length-1?(0,V.jsx)(`button`,{type:`button`,onClick:()=>Ee(o+1),className:`rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white focus-visible:outline-2`,children:`Guardar e continuar`}):(0,V.jsx)(`button`,{type:`button`,onClick:()=>void Te(),className:`rounded border px-4 py-3 focus-visible:outline-2`,children:`Limpar este rascunho`})]}),(0,V.jsx)(`p`,{className:`text-xs text-slate-600`,children:`Os pressupostos não identificativos podem ser guardados de forma cifrada para recuperar o rascunho. Os dados pessoais e contactos são guardados apenas quando existe sessão autenticada e ficam associados à conta. A submissão formal ainda não está disponível neste formulário.`})]})}var At=`w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900`,jt=`inline-block rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white disabled:opacity-50`,Mt={sectors:`Sectores Prioritários`,sector:`Sector prioritário`,procedures:`Como Investir / Procedimentos`,legislation:`Legislação e Incentivos`,documents:`Documentos e Formulários`,support:`Apoio ao Investidor`,partnerships:`Bolsa de Parcerias`,simulator:`Simulador Fiscal`,investor:`Formulário de investidor`,company:`Formulário de empresa`,desk:`Balcão Virtual`},Nt={received:`Recebido`,in_review:`Em análise`,contacted:`Contactado`,closed:`Encerrado`,pending:`A aguardar publicação`,published:`Publicado`,withdrawn:`Retirado`};function Pt(e){let n=(0,f.c)(10),{page:r}=e,i;n[0]===r.prev_page_url?i=n[1]:(i=r.prev_page_url&&(0,V.jsx)(t,{href:r.prev_page_url,children:`Anterior`}),n[0]=r.prev_page_url,n[1]=i);let a;n[2]===r.total?a=n[3]:(a=(0,V.jsxs)(`span`,{children:[r.total,` registos`]}),n[2]=r.total,n[3]=a);let o;n[4]===r.next_page_url?o=n[5]:(o=r.next_page_url&&(0,V.jsx)(t,{href:r.next_page_url,children:`Seguinte`}),n[4]=r.next_page_url,n[5]=o);let s;return n[6]!==i||n[7]!==a||n[8]!==o?(s=(0,V.jsxs)(`nav`,{"aria-label":`Paginação`,className:`flex gap-6 py-5`,children:[i,a,o]}),n[6]=i,n[7]=a,n[8]=o,n[9]=s):s=n[9],s}function Ft(e){let r=(0,f.c)(43),{kind:i,partnershipId:a}=e,{auth:o}=s().props,c=o.user?.name??``,l=o.user?.email??``,p=a??null,m;r[0]!==i||r[1]!==c||r[2]!==l||r[3]!==p?(m={kind:i,fullName:c,email:l,phone:``,country:`Moçambique`,company:``,sectorInterest:``,message:``,privacyConsent:!1,submission_key:``,partnership_id:p},r[0]=i,r[1]=c,r[2]=l,r[3]=p,r[4]=m):m=r[4];let h=n(m),[g,_]=(0,d.useState)(!1),v;r[5]===h?v=r[6]:(v=e=>{e.preventDefault();let t=h.data.submission_key||u();h.setData(`submission_key`,t),h.transform(e=>({...e,submission_key:t})),h.post(`/apoio`,{preserveScroll:!0,onSuccess:()=>_(!0)})},r[5]=h,r[6]=v);let y=i===`company`?`Dados da empresa e do representante`:`Enviar pedido`,b;r[7]===y?b=r[8]:(b=(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:y}),r[7]=y,r[8]=b);let x;r[9]===o.user?x=r[10]:(x=!o.user&&(0,V.jsxs)(`p`,{className:`text-sm`,children:[`Pode enviar sem conta. Para acompanhar no Balcão Virtual,`,` `,(0,V.jsx)(t,{href:`/login`,className:`underline`,children:`entre antes de enviar`}),`.`]}),r[9]=o.user,r[10]=x);let S;r[11]===i?S=r[12]:(S=[`fullName`,`email`,`phone`,`country`,`sectorInterest`,...i===`company`?[`company`]:[]],r[11]=i,r[12]=S);let C=S,w;r[13]!==h||r[14]!==C?(w=C.map(e=>{let t=e;return(0,V.jsxs)(`label`,{className:`block space-y-1`,children:[(0,V.jsx)(`span`,{children:{fullName:`Nome do representante`,email:`Email`,phone:`Telefone (opcional)`,country:`País`,sectorInterest:`Sector ou assunto`,company:`Nome da empresa`}[t]}),(0,V.jsx)(`input`,{className:At,type:t===`email`?`email`:`text`,required:t!==`phone`,maxLength:t===`phone`?30:150,value:h.data[t],onChange:e=>h.setData(t,e.target.value)})]},t)}),r[13]=h,r[14]=C,r[15]=w):w=r[15];let T;r[16]===h?T=r[17]:(T=e=>h.setData(`message`,e.target.value),r[16]=h,r[17]=T);let E;r[18]!==h.data.message||r[19]!==T?(E=(0,V.jsxs)(`label`,{className:`block`,children:[`Descreva o pedido`,(0,V.jsx)(`textarea`,{className:At,required:!0,minLength:20,maxLength:2e3,rows:5,value:h.data.message,onChange:T})]}),r[18]=h.data.message,r[19]=T,r[20]=E):E=r[20];let D;r[21]===h?D=r[22]:(D=e=>h.setData(`privacyConsent`,e.target.checked),r[21]=h,r[22]=D);let O;r[23]!==h.data.privacyConsent||r[24]!==D?(O=(0,V.jsx)(`input`,{type:`checkbox`,required:!0,checked:h.data.privacyConsent,onChange:D}),r[23]=h.data.privacyConsent,r[24]=D,r[25]=O):O=r[25];let k;r[26]===Symbol.for(`react.memo_cache_sentinel`)?(k=(0,V.jsx)(`span`,{children:`Autorizo o tratamento destes dados para responder e acompanhar este pedido. Os dados ficam acessíveis à equipa de atendimento; não serão publicados na bolsa.`}),r[26]=k):k=r[26];let A;r[27]===O?A=r[28]:(A=(0,V.jsxs)(`label`,{className:`flex items-start gap-3`,children:[O,k]}),r[27]=O,r[28]=A);let j;r[29]===h.errors?j=r[30]:(j=Object.entries(h.errors).map(It),r[29]=h.errors,r[30]=j);let M;r[31]!==h||r[32]!==g?(M=g?(0,V.jsxs)(`p`,{role:`status`,children:[`Pedido enviado. Guarde o protocolo apresentado acima.`,` `,(0,V.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{_(!1),h.setData(`submission_key`,``),h.setData(`message`,``)},children:`Enviar novo pedido`})]}):(0,V.jsx)(`button`,{className:jt,disabled:h.processing,children:`Enviar e obter protocolo`}),r[31]=h,r[32]=g,r[33]=M):M=r[33];let N;return r[34]!==w||r[35]!==E||r[36]!==A||r[37]!==j||r[38]!==M||r[39]!==v||r[40]!==b||r[41]!==x?(N=(0,V.jsxs)(`form`,{className:`space-y-4 rounded-xl border bg-white p-6`,onSubmit:v,children:[b,x,w,E,A,j,M]}),r[34]=w,r[35]=E,r[36]=A,r[37]=j,r[38]=M,r[39]=v,r[40]=b,r[41]=x,r[42]=N):N=r[42],N}function It(e){let[t,n]=e;return(0,V.jsx)(`p`,{role:`alert`,className:`text-red-700`,children:n},t)}function Lt(){let e=(0,f.c)(23),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t={title:``,sector:``,province:``,offer:``,seeking:``,publication_consent:!1},e[0]=t):t=e[0];let r=n(t),i;e[1]===r?i=e[2]:(i=e=>{e.preventDefault(),r.post(`/parcerias`,{preserveScroll:!0,onSuccess:()=>r.reset()})},e[1]=r,e[2]=i);let a,o,s;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:`Propor parceria`}),o=(0,V.jsx)(`p`,{children:`Descreva apenas informação destinada a publicação. Não inclua contactos pessoais ou documentos confidenciais.`}),s=[`title`,`sector`,`province`,`offer`,`seeking`],e[3]=a,e[4]=o,e[5]=s):(a=e[3],o=e[4],s=e[5]);let c;e[6]===r?c=e[7]:(c=s.map(e=>(0,V.jsxs)(`label`,{className:`block`,children:[{title:`Título`,sector:`Sector`,province:`Província`,offer:`O que oferece`,seeking:`Parceiro ou capacidade que procura`}[e],e===`province`?(0,V.jsx)(l,{value:r.data.province,onChange:e=>r.setData(`province`,e),className:At,required:!0,placeholder:`Seleccione uma província`,label:`Província`}):(0,V.jsx)(`textarea`,{className:At,required:!0,minLength:e===`offer`||e===`seeking`?20:1,maxLength:e===`offer`||e===`seeking`?2e3:100,value:r.data[e],onChange:t=>r.setData(e,t.target.value)})]},e)),e[6]=r,e[7]=c);let u;e[8]===r?u=e[9]:(u=e=>r.setData(`publication_consent`,e.target.checked),e[8]=r,e[9]=u);let d;e[10]!==r.data.publication_consent||e[11]!==u?(d=(0,V.jsxs)(`label`,{className:`flex gap-2`,children:[(0,V.jsx)(`input`,{type:`checkbox`,required:!0,checked:r.data.publication_consent,onChange:u}),`Autorizo a publicação dos dados desta proposta após revisão.`]}),e[10]=r.data.publication_consent,e[11]=u,e[12]=d):d=e[12];let p;e[13]===r.errors?p=e[14]:(p=Object.entries(r.errors).map(Rt),e[13]=r.errors,e[14]=p);let m;e[15]===r.processing?m=e[16]:(m=(0,V.jsx)(`button`,{disabled:r.processing,className:jt,children:`Submeter proposta`}),e[15]=r.processing,e[16]=m);let h;return e[17]!==i||e[18]!==c||e[19]!==d||e[20]!==p||e[21]!==m?(h=(0,V.jsxs)(`form`,{className:`space-y-4 rounded-xl border p-6`,onSubmit:i,children:[a,o,c,d,p,m]}),e[17]=i,e[18]=c,e[19]=d,e[20]=p,e[21]=m,e[22]=h):h=e[22],h}function Rt(e){let[t,n]=e;return(0,V.jsx)(`p`,{role:`alert`,children:n},t)}function zt(){let e=(0,f.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,V.jsx)(kt,{}),e[0]=t):t=e[0],t}function Bt(e){let r=(0,f.c)(62),{flash:a,auth:o}=s().props,u=e.filters?.q??``,p=e.filters?.category??``,m=e.filters?.topic??``,h=e.filters?.sector??``,g=e.filters?.province??``,_;r[0]!==u||r[1]!==p||r[2]!==m||r[3]!==h||r[4]!==g?(_={q:u,category:p,topic:m,sector:h,province:g},r[0]=u,r[1]=p,r[2]=m,r[3]=h,r[4]=g,r[5]=_):_=r[5];let v=n(_),[y,b]=(0,d.useState)(),x=e.sector?.name??Mt[e.section],S;r[6]===x?S=r[7]:(S=(0,V.jsx)(i,{title:x}),r[6]=x,r[7]=S);let C;r[8]===Symbol.for(`react.memo_cache_sentinel`)?(C=(0,V.jsx)(c,{}),r[8]=C):C=r[8];let w;r[9]===x?w=r[10]:(w=(0,V.jsx)(`h1`,{className:`text-3xl font-bold`,children:x}),r[9]=x,r[10]=w);let T;r[11]===a?T=r[12]:(T=a?.success&&(0,V.jsx)(`p`,{role:`status`,className:`rounded border border-emerald-700 bg-emerald-50 p-4`,children:a.success}),r[11]=a,r[12]=T);let E;r[13]!==e.section||r[14]!==e.sectors?(E=e.section===`sectors`&&(0,V.jsxs)(`div`,{className:`grid gap-5 md:grid-cols-3`,children:[e.sectors?.map(Yt),!e.sectors?.length&&(0,V.jsx)(`p`,{children:`Não existem sectores publicados.`})]}),r[13]=e.section,r[14]=e.sectors,r[15]=E):E=r[15];let D;r[16]!==e.opportunities||r[17]!==e.section||r[18]!==e.sector?(D=e.section===`sector`&&e.sector&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{className:`whitespace-pre-line`,children:e.sector.description||e.sector.short_description||`Descrição sectorial em preparação.`}),(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:`Oportunidades no sector`}),e.opportunities?.map(Jt),!e.opportunities?.length&&(0,V.jsx)(`p`,{children:`Sem oportunidades publicadas neste sector.`}),(0,V.jsx)(t,{className:jt,href:`/oportunidades?sector=${e.sector.slug}`,children:`Pesquisar todas as oportunidades do sector`}),(0,V.jsxs)(`p`,{children:[(0,V.jsx)(t,{href:`/como-investir`,className:`underline`,children:`Preparar o investimento`}),` `,`·`,` `,(0,V.jsx)(t,{href:`/apoio`,className:`underline`,children:`Pedir apoio sectorial`})]})]}),r[16]=e.opportunities,r[17]=e.section,r[18]=e.sector,r[19]=D):D=r[19];let O;r[20]===e.section?O=r[21]:(O=e.section===`procedures`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:`Roteiro de preparação e acompanhamento. Os requisitos concretos dependem da actividade e devem ser confirmados com a entidade competente.`}),(0,V.jsx)(`ol`,{className:`space-y-5`,children:[[`Definir o investimento`,`Descreva actividade, localização, dimensão, promotor e objectivos. Identifique as componentes que pretende financiar ou executar.`,`/oportunidades`,`Explorar oportunidades`],[`Preparar o perfil do promotor`,`Reúna os dados de contacto, identificação do representante e descrição da capacidade técnica e financeira. Utilize o formulário adequado ao seu perfil.`,`/formularios/empresa`,`Preencher perfil da empresa`],[`Confirmar procedimentos e enquadramento`,`Solicite à equipa a identificação dos procedimentos aplicáveis à localização e actividade, entidades intervenientes e documentos necessários.`,`/apoio`,`Solicitar orientação`],[`Organizar documentos`,`Consulte a biblioteca e confirme versões, formulários, anexos e referências antes da submissão à entidade competente.`,`/documentos`,`Consultar documentos`],[`Analisar parceiros e cenários`,`Identifique parceiros, necessidades de financiamento e cenários. Confirme as condições legais dos incentivos antes de os incorporar no plano.`,`/parcerias`,`Explorar parcerias`],[`Submeter e acompanhar o pedido`,`Entre na sua conta, envie o pedido e guarde o protocolo. Acompanhe o estado no Balcão Virtual e responda aos contactos da equipa.`,`/balcao-virtual`,`Abrir Balcão Virtual`]].map(qt)})]}),r[20]=e.section,r[21]=O);let k;r[22]!==v||r[23]!==e.categories||r[24]!==e.resources||r[25]!==e.section||r[26]!==e.topics?(k=(e.section===`documents`||e.section===`legislation`)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:`Documentos publicados pela gestão, organizados por categoria e tema. Cada download mantém a referência da fonte.`}),(0,V.jsxs)(`form`,{className:`grid gap-3 md:grid-cols-4`,onSubmit:t=>{t.preventDefault(),v.get(e.section===`documents`?`/documentos`:`/legislacao`)},children:[(0,V.jsxs)(`label`,{children:[`Pesquisar`,(0,V.jsx)(`input`,{className:At,value:v.data.q,onChange:e=>v.setData(`q`,e.target.value)})]}),(0,V.jsxs)(`label`,{children:[`Categoria`,(0,V.jsxs)(`select`,{className:At,value:v.data.category,onChange:e=>v.setData(`category`,e.target.value),children:[(0,V.jsx)(`option`,{value:``,children:`Todas`}),e.categories?.map(Kt)]})]}),(0,V.jsxs)(`label`,{children:[`Tema`,(0,V.jsxs)(`select`,{className:At,value:v.data.topic,onChange:e=>v.setData(`topic`,e.target.value),children:[(0,V.jsx)(`option`,{value:``,children:`Todos`}),e.topics?.map(Gt)]})]}),(0,V.jsx)(`button`,{className:jt,children:`Pesquisar`})]}),e.resources?.data.map(Wt),!e.resources?.data.length&&(0,V.jsxs)(`p`,{children:[`Não existem documentos publicados para esta pesquisa.`,` `,(0,V.jsx)(t,{href:`/apoio`,className:`underline`,children:`Solicitar documento ao apoio`}),`.`]}),e.resources&&(0,V.jsx)(Pt,{page:e.resources}),(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,V.jsx)(t,{className:jt,href:`/formularios/investidor`,children:`Formulário de investidor`}),(0,V.jsx)(t,{className:jt,href:`/formularios/empresa`,children:`Formulário de empresa`})]})]}),r[22]=v,r[23]=e.categories,r[24]=e.resources,r[25]=e.section,r[26]=e.topics,r[27]=k):k=r[27];let A;r[28]===e.section?A=r[29]:(A=[`support`,`investor`,`company`].includes(e.section)&&(0,V.jsx)(Ft,{kind:e.section===`support`?`support`:e.section},e.section),r[28]=e.section,r[29]=A);let j;r[30]!==e.contacts||r[31]!==e.section?(j=e.section===`support`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`section`,{className:`space-y-3`,children:[(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:`Contactos`}),e.contacts?.email&&(0,V.jsxs)(`p`,{children:[`Email:`,` `,(0,V.jsx)(`a`,{className:`underline`,href:`mailto:${e.contacts.email}`,children:e.contacts.email})]}),e.contacts?.phone&&(0,V.jsxs)(`p`,{children:[`Telefone: `,e.contacts.phone]}),e.contacts?.address&&(0,V.jsx)(`p`,{children:e.contacts.address}),e.contacts?.hours&&(0,V.jsxs)(`p`,{children:[`Horário: `,e.contacts.hours]}),!e.contacts?.email&&!e.contacts?.phone&&(0,V.jsx)(`p`,{children:`Utilize o formulário para contactar a equipa. Os contactos directos ainda não estão publicados.`})]}),(0,V.jsxs)(`section`,{className:`space-y-3`,children:[(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:`Perguntas frequentes`}),[[`Como acompanho um pedido?`,`Entre antes de enviar o pedido. O protocolo e o estado ficam disponíveis no Balcão Virtual. Para pedidos enviados sem conta, conserve o protocolo e indique-o nos contactos seguintes.`],[`Manifestar interesse garante financiamento ou aprovação?`,`O envio regista o interesse para análise e contacto da equipa. Não representa aprovação do investimento nem compromisso de financiamento.`],[`Como publico uma parceria?`,`Entre com email verificado, preencha a proposta na Bolsa de Parcerias e autorize a publicação. A gestão revê a proposta antes de a tornar pública.`],[`Onde obtenho documentos e formulários?`,`Consulte Documentos e Formulários. Se não encontrar o documento, indique o título ou assunto num pedido de apoio.`]].map(Ut)]})]}),r[30]=e.contacts,r[31]=e.section,r[32]=j):j=r[32];let M;r[33]===e.section?M=r[34]:(M=e.section===`simulator`&&(0,V.jsx)(zt,{}),r[33]=e.section,r[34]=M);let N;r[35]!==o||r[36]!==v||r[37]!==e.partnerships||r[38]!==e.section||r[39]!==y?(N=e.section===`partnerships`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:`Encontre capacidades e parceiros. O contacto é intermediado pelo apoio; os dados privados dos proponentes não são publicados.`}),(0,V.jsxs)(`form`,{className:`grid gap-3 md:grid-cols-4`,onSubmit:e=>{e.preventDefault(),v.get(`/parcerias`)},children:[[`q`,`sector`,`province`].map(e=>(0,V.jsxs)(`label`,{children:[{q:`Pesquisar`,sector:`Sector`,province:`Província`}[e],e===`province`?(0,V.jsx)(l,{value:v.data.province,onChange:e=>v.setData(`province`,e),className:At,placeholder:`Todas as províncias`,label:`Filtrar por província`}):(0,V.jsx)(`input`,{className:At,value:v.data[e],onChange:t=>v.setData(e,t.target.value)})]},e)),(0,V.jsx)(`button`,{className:jt,children:`Filtrar`})]}),e.partnerships?.data.map(e=>(0,V.jsxs)(`article`,{className:`space-y-3 rounded-xl border bg-white p-6`,children:[(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:e.title}),(0,V.jsxs)(`p`,{children:[e.sector,` · `,e.province]}),(0,V.jsx)(`h3`,{className:`font-bold`,children:`Oferece`}),(0,V.jsx)(`p`,{className:`whitespace-pre-line`,children:e.offer}),(0,V.jsx)(`h3`,{className:`font-bold`,children:`Procura`}),(0,V.jsx)(`p`,{className:`whitespace-pre-line`,children:e.seeking}),(0,V.jsx)(`button`,{className:jt,onClick:()=>b(e.id),children:`Pedir contacto sobre esta parceria`})]},e.id)),!e.partnerships?.data.length&&(0,V.jsx)(`p`,{children:`Ainda não existem propostas publicadas para esta pesquisa.`}),e.partnerships&&(0,V.jsx)(Pt,{page:e.partnerships}),y&&(0,V.jsx)(Ft,{kind:`partnership`,partnershipId:y},y),` `,o.user?(0,V.jsx)(Lt,{}):(0,V.jsx)(t,{className:jt,href:`/login`,children:`Entrar para propor parceria`})]}),r[35]=o,r[36]=v,r[37]=e.partnerships,r[38]=e.section,r[39]=y,r[40]=N):N=r[40];let P;r[41]!==e.myPartnerships||r[42]!==e.requests||r[43]!==e.section?(P=e.section===`desk`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`p`,{children:`Acompanhe os pedidos submetidos com esta conta. Os contactos da equipa continuam pelos dados fornecidos no pedido.`}),(0,V.jsx)(t,{className:jt,href:`/apoio`,children:`Novo pedido`}),(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:`Os meus pedidos`}),e.requests?.map(Ht),!e.requests?.length&&(0,V.jsx)(`p`,{children:`Ainda não existem pedidos de apoio enviados com esta conta.`}),(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:`As minhas propostas de parceria`}),e.myPartnerships?.map(Vt),(0,V.jsx)(t,{href:`/investidor`,className:`underline`,children:`Abrir fichas e manifestações de interesse da carteira`})]}),r[41]=e.myPartnerships,r[42]=e.requests,r[43]=e.section,r[44]=P):P=r[44];let F;r[45]!==E||r[46]!==D||r[47]!==O||r[48]!==k||r[49]!==A||r[50]!==j||r[51]!==M||r[52]!==N||r[53]!==P||r[54]!==w||r[55]!==T?(F=(0,V.jsxs)(`main`,{className:`mx-auto max-w-6xl space-y-8 px-5 py-10`,children:[w,T,E,D,O,k,A,j,M,N,P]}),r[45]=E,r[46]=D,r[47]=O,r[48]=k,r[49]=A,r[50]=j,r[51]=M,r[52]=N,r[53]=P,r[54]=w,r[55]=T,r[56]=F):F=r[56];let I;r[57]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,V.jsx)(t,{href:`/apoio`,className:`underline`,children:`Apoio ao Investidor`}),r[57]=I):I=r[57];let L;r[58]===Symbol.for(`react.memo_cache_sentinel`)?(L=(0,V.jsxs)(`footer`,{className:`border-t px-5 py-8 text-center text-sm`,children:[`Investe Moçambique ·`,` `,I,` `,`·`,` `,(0,V.jsx)(t,{href:`/documentos`,className:`underline`,children:`Documentos e Formulários`})]}),r[58]=L):L=r[58];let R;return r[59]!==F||r[60]!==S?(R=(0,V.jsxs)(`div`,{className:`min-h-screen bg-slate-50 text-slate-900`,children:[S,C,F,L]}),r[59]=F,r[60]=S,r[61]=R):R=r[61],R}function Vt(e){return(0,V.jsxs)(`p`,{children:[e.title,` — `,Nt[e.status]??e.status]},e.id)}function Ht(e){return(0,V.jsxs)(`article`,{className:`rounded border bg-white p-5`,children:[(0,V.jsx)(`strong`,{children:e.reference}),(0,V.jsx)(`p`,{children:Nt[e.status]??e.status}),(0,V.jsx)(`p`,{children:new Date(e.created_at).toLocaleDateString(`pt-MZ`)})]},e.reference)}function Ut(e){let[t,n]=e;return(0,V.jsxs)(`details`,{className:`rounded border bg-white p-4`,children:[(0,V.jsx)(`summary`,{className:`cursor-pointer font-semibold`,children:t}),(0,V.jsx)(`p`,{className:`mt-3`,children:n})]},t)}function Wt(e){return(0,V.jsxs)(`article`,{className:`rounded-xl border bg-white p-5`,children:[(0,V.jsxs)(`h2`,{className:`text-xl font-bold`,children:[e.title,e.essential?` · Essencial`:``]}),(0,V.jsxs)(`p`,{children:[e.category,` · `,e.topic]}),(0,V.jsxs)(`p`,{className:`my-3 text-sm`,children:[`Fonte: `,e.source_reference]}),(0,V.jsxs)(`a`,{href:`/documentos/${e.id}/download`,className:`underline`,children:[`Descarregar `,e.title]})]},e.id)}function Gt(e){return(0,V.jsx)(`option`,{children:e},e)}function Kt(e){return(0,V.jsx)(`option`,{children:e},e)}function qt(e,n){let[r,i,a,o]=e;return(0,V.jsxs)(`li`,{className:`rounded-xl border bg-white p-6`,children:[(0,V.jsxs)(`h2`,{className:`text-xl font-bold`,children:[n+1,`. `,r]}),(0,V.jsx)(`p`,{className:`my-3`,children:i}),(0,V.jsx)(t,{href:a,className:`underline`,children:o})]},r)}function Jt(e){return(0,V.jsxs)(`article`,{className:`rounded border bg-white p-5`,children:[(0,V.jsx)(t,{className:`text-lg font-bold underline`,href:`/oportunidades/${e.slug}`,children:e.title}),(0,V.jsx)(`p`,{children:e.province}),(0,V.jsx)(`p`,{children:e.summary})]},e.slug)}function Yt(e){return(0,V.jsxs)(`article`,{className:`rounded-xl border bg-white p-6`,children:[(0,V.jsx)(`h2`,{className:`text-xl font-bold`,children:(0,V.jsx)(t,{href:`/sectores/${e.slug}`,children:e.name})}),(0,V.jsx)(`p`,{className:`my-3`,children:e.short_description}),(0,V.jsxs)(`p`,{children:[e.opportunities_count,` oportunidades publicadas`]})]},e.slug)}export{Bt as default};