const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BxAy6Uji.js","assets/comparison-DdwL-fbx.js","assets/financial-core-C_85DMsm.js","assets/comparison-DdPMBm6V.css","assets/radix-CjQ3HxvQ.js","assets/router-Dd84Hcmg.js","assets/ui-modules-WwJBNQE9.js","assets/ui-shadcn-Ca3XP76Q.js","assets/icons-Bl8z16Px.js","assets/analytics-4lR5W04J.js","assets/firebase-pYufVIs9.js","assets/jspdf-BlKy7aSd.js","assets/html2canvas-OkJIQ-sN.js","assets/index-OvBp-vJi.css","assets/MaRetraite-CGhSz7VR.js","assets/senior-unified-styles-CAliiQge.css","assets/reports-DMq4J9x5.js","assets/date-lib-CsXqSDxo.js"])))=>i.map(i=>d[i]); var js=Object.defineProperty;var Vs=(c,e,t)=>e in c?js(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var L=(c,e,t)=>Vs(c,typeof e!="symbol"?e+"":e,t);import{E as ce}from"./jspdf-BlKy7aSd.js";import Ys from"./html2canvas-OkJIQ-sN.js";import{g as Ks,c as _t,a as Qs}from"./comparison-DdwL-fbx.js";import{F as Ie}from"./financial-core-C_85DMsm.js";const Js="modulepreload",Xs=function(c){return"/"+c},dr={},Ue=function(e,t,r){let s=Promise.resolve();if(t&&t.length>0){let l=function(o){return Promise.all(o.map(u=>Promise.resolve(u).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),i=a?.nonce||a?.getAttribute("nonce");s=l(t.map(o=>{if(o=Xs(o),o in dr)return;dr[o]=!0;const u=o.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${m}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Js,u||(d.as="script"),d.crossOrigin="",d.href=o,i&&d.setAttribute("nonce",i),document.head.appendChild(d),u)return new Promise((p,x)=>{d.addEventListener("load",p),d.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${o}`)))})}))}function n(a){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=a,window.dispatchEvent(i),!i.defaultPrevented)throw a}return s.then(a=>{for(const i of a||[])i.status==="rejected"&&n(i.reason);return e().catch(n)})},Zs=1e3,pr={"/":["../pages/MaRetraite","../pages/ComparisonPage"],"/ma-retraite":["../features/retirement/components/optimization/MonteCarloSimulator","../services/ProfessionalReportGenerator"],"/comparaison":["../services/ComparisonAnalytics","../components/comparison/SeniorsCompetitiveComparison"],"/hypotheses":["../pages/SimpleAssumptionsPage","../services/SimpleAssumptionsService"]};class Fi{static report(e,t,r){e&&e(t,r)}static schedule(e,t,r){return(r?.scheduleTask??((n,a)=>setTimeout(n,a)))(e,t)}static createHandle(e,t){return{cancel:()=>{(t?.cancelTask??(s=>clearTimeout(s)))(e)}}}static getDefaultMemoryEnvironment(){if(typeof performance>"u"||!performance.memory)return;const t=performance.memory?.usedJSHeapSize;if(typeof t!="number")return;const r=typeof globalThis.gc=="function"?()=>globalThis.gc():void 0;return{usedHeapMB:t/1024/1024,collectGarbage:r}}static preloadModules(e,t,r){const s=[],n=t?.delayMs??Zs;return e.forEach((a,i)=>{const l=async()=>{try{await a()}catch(u){const m={index:i,error:u,task:a};t?.onError?.(m),this.report(r,"Failed to preload module",u)}},o=this.schedule(()=>{l()},i*n,t);s.push(this.createHandle(o,t))}),s}static preloadCriticalModules(e,t){const r=[()=>Ue(()=>import("./index-BxAy6Uji.js").then(s=>s.A),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])),()=>Ue(()=>import("./MaRetraite-CGhSz7VR.js"),__vite__mapDeps([14,1,2,3,6,7,8,4,5,9,10,11,12,15])),()=>Ue(()=>import("./comparison-DdwL-fbx.js").then(s=>s.h),__vite__mapDeps([1,2,3])),()=>Ue(()=>import("./reports-DMq4J9x5.js"),__vite__mapDeps([16,2,17]))];return this.preloadModules(r,e,t)}static async preloadModule(e,t){try{await import(e)}catch(r){throw this.report(t,`Failed to preload module: ${e}`,r),r}}static preloadPredictedModules(e,t,r=pr,s){const n=this.getNavigationPredictions(e,r);if(n.length===0)return[];const a=n.map(i=>()=>this.preloadModule(i,s));return this.preloadModules(a,t,s)}static optimizedCalculation(e,t,r){const s=r?.timeoutMs??5e3;return new Promise(n=>{const a=setTimeout(()=>{this.report(r?.reporter,"Calculation timeout, using fallback"),n(t)},s);try{const i=e();clearTimeout(a),n(i)}catch(i){this.report(r?.reporter,"Calculation error, using fallback",i),clearTimeout(a),n(t)}})}static optimizedAsyncCalculation(e,t,r){const s=r?.timeoutMs??8e3;return new Promise(n=>{const a=setTimeout(()=>{this.report(r?.reporter,"Async calculation timeout, using fallback"),n(t)},s);e().then(i=>{clearTimeout(a),n(i)}).catch(i=>{this.report(r?.reporter,"Async calculation error, using fallback",i),clearTimeout(a),n(t)})})}static debounceCalculation(e,t=1e3){let r;return(...s)=>{r&&clearTimeout(r),r=setTimeout(()=>{e(...s)},t)}}static throttleCalculation(e,t=2e3){let r=!1;return(...s)=>{r||(e(...s),r=!0,setTimeout(()=>{r=!1},t))}}static async memoryOptimizedCalculation(e,t={}){const{maxMemoryMB:r=50,cleanup:s,environment:n}=t,a=n??this.getDefaultMemoryEnvironment();return a?.usedHeapMB!==void 0&&a.usedHeapMB>r&&(a.collectGarbage?.(),s?.()),e()}static getNavigationPredictions(e,t=pr){return t[e]??[]}static monitorPerformance(e=globalThis,t={}){const r=e??globalThis,s=r?.PerformanceObserver??globalThis.PerformanceObserver;if(typeof s!="function")return()=>{};const n=[],a=r?.console??globalThis.console;if(t.handleLongTask||a?.warn){const i=new s(l=>{for(const o of l.getEntries())t.handleLongTask?t.handleLongTask(o):a?.warn?.("Long task detected",o)});try{i.observe({entryTypes:["longtask"]}),n.push(i)}catch{i.disconnect()}}if(t.handleNavigation||a?.log){const i=new s(l=>{for(const o of l.getEntries()){const u=o;if(t.handleNavigation)t.handleNavigation(u);else if("loadEventEnd"in u&&"loadEventStart"in u){const m=u.loadEventEnd-u.loadEventStart,d="domContentLoadedEventEnd"in u&&"domContentLoadedEventStart"in u?u.domContentLoadedEventEnd-u.domContentLoadedEventStart:void 0;a?.log?.("Navigation timing",{loadTime:m,domContentLoaded:d})}else a?.log?.("Performance entry",u)}});try{i.observe({entryTypes:["navigation","paint"]}),n.push(i)}catch{i.disconnect()}}return()=>{n.forEach(i=>i.disconnect())}}}const Gt=2e5,As=new TextEncoder,en=new TextDecoder;function xr(c){const e=new Uint8Array(c);return crypto.getRandomValues(e),e}function Mt(c){const e=c instanceof Uint8Array?c:new Uint8Array(c);let t="";for(let r=0;r{const t=indexedDB.open(nn,an);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(ve)||r.createObjectStore(ve),r.objectStoreNames.contains(mr)||r.createObjectStore(mr)},t.onsuccess=()=>c(t.result),t.onerror=()=>e(t.error)})}async function gr(c,e,t){const r=await bs();return new Promise((s,n)=>{const a=r.transaction(c,"readwrite");a.objectStore(c).put(t,e),a.oncomplete=()=>s(),a.onerror=()=>n(a.error)})}async function kt(c,e){const t=await bs();return new Promise((r,s)=>{const a=t.transaction(c,"readonly").objectStore(c).get(e);a.onsuccess=()=>r(a.result),a.onerror=()=>s(a.error)})}function he(){try{const c=localStorage.getItem(Cs);if(c)return JSON.parse(c)}catch{}return{frequencyMin:15,clearLocalAfterBackup:!0,enableAutoBackup:!0,requireSecondBackupReminder:!0}}function ln(c){try{localStorage.setItem(Cs,JSON.stringify(c))}catch{}}function Le(){try{const c=localStorage.getItem(ys);if(c)return JSON.parse(c)}catch{}return{}}function Ot(c){try{localStorage.setItem(ys,JSON.stringify(c))}catch{}}async function vr(c,e){if(c&&await c.requestPermission?.({mode:"readwrite"})==="denied")throw new Error("Permission denied for backup file.");const t=await c.createWritable(),r=new Blob([JSON.stringify(e,null,2)],{type:"application/json"});await t.write(r),await t.close()}async function un(c){if(c&&await c.requestPermission?.({mode:"read"})==="denied")throw new Error("Permission denied for backup file.");const t=await(await c.getFile()).text();return JSON.parse(t)}class dn{static async init(){try{navigator?.storage?.persist&&await navigator.storage.persist()}catch{}const e=he();e.enableAutoBackup&&this.startLoop(e.frequencyMin)}static async linkFile(e){if(!on()){alert("Votre navigateur ne supporte pas la sauvegarde directe sur un fichier. Utilisez Edge/Chrome pour activer la sauvegarde automatique.");return}const t=window.showSaveFilePicker,r=await t({suggestedName:"MonPlanRetraite_backup.json",types:[{description:"Encrypted JSON",accept:{"application/json":[".json"]}}]});await gr(ve,e,r);const s=Le();e==="primary"&&(s.primaryLinked=!0),e==="secondary"&&(s.secondaryLinked=!0),Ot(s)}static async unlinkFile(e){await gr(ve,e,void 0);const t=Le();e==="primary"&&(t.primaryLinked=!1),e==="secondary"&&(t.secondaryLinked=!1),Ot(t)}static setSessionPassword(e){try{sessionStorage.setItem(fr,e||"")}catch{}}static getSessionPassword(){try{return sessionStorage.getItem(fr)||void 0}catch{return}}static updateConfig(e){const t={...he(),...e};ln(t),t.enableAutoBackup?this.startLoop(t.frequencyMin):this.stopLoop()}static getConfig(){return he()}static getMeta(){return Le()}static startLoop(e){this.stopLoop();const t=Math.max(1,e??he().frequencyMin)*6e4;this.intervalId=window.setInterval(()=>{this.tryAutoBackup().catch(r=>{})},t)}static stopLoop(){this.intervalId!=null&&(clearInterval(this.intervalId),this.intervalId=void 0)}static async tryAutoBackup(){if(!he().enableAutoBackup)return;const t=localStorage.getItem($e);if(!t)return;const r=cn(t);if(localStorage.getItem(hr)===r)return;const n=this.getSessionPassword();if(!n)return;await this.backupNow(n)&&localStorage.setItem(hr,r)}static async backupNow(e){const t=localStorage.getItem($e);if(!t)return!1;const r=JSON.parse(t),s=await tn(r,e),n=await kt(ve,"primary"),a=await kt(ve,"secondary");let i=!1;if(n&&(await vr(n,s),i=!0),a)try{await vr(a,s)}catch{}if(i){const l=Le();if(l.lastBackupISO=new Date().toISOString(),l.primaryLinked=!!n,l.secondaryLinked=!!a,Ot(l),he().clearLocalAfterBackup)try{localStorage.removeItem($e)}catch{}return!0}return!1}static async proposeRestoreIfNeeded(){if(localStorage.getItem($e))return!1;const t=await kt(ve,"primary");if(!t||!window.confirm(navigator.language?.startsWith("fr")?"Aucune donnée locale trouvée. Voulez-vous recharger vos données chiffrées depuis votre fichier de sauvegarde local ?":"No local data found. Would you like to reload your encrypted data from your local backup file?"))return!1;const s=prompt(navigator.language?.startsWith("fr")?"Entrez votre mot de passe de sauvegarde:":"Enter your backup password:")||"";if(!s)return!1;try{const n=await un(t);if(!sn(n))throw new Error("Invalid envelope file");const a=await rn(n,s);localStorage.setItem($e,JSON.stringify(a));try{window.mprNotifyDataChanged?.()}catch{}return!0}catch{return alert(navigator.language?.startsWith("fr")?"Échec du chargement de la sauvegarde. Mot de passe invalide ou fichier corrompu.":"Failed to load backup. Invalid password or corrupted file."),!1}}static shouldWarnSecondBackup(){return he().requireSecondBackupReminder?!Le().secondaryLinked:!1}}L(dn,"intervalId");const Ae=class Ae{static getInstance(){return Ae.instance||(Ae.instance=new Ae),Ae.instance}generatePersonalizedPath(e){const t=this.getBaseSteps(),r=this.filterStepsForProfile(t,e),s=this.orderStepsByPriority(r,e);return{id:`path-${Date.now()}`,name:this.getPathName(e),description:this.getPathDescription(e),estimatedDuration:s.reduce((n,a)=>n+a.estimatedTime,0),steps:s,targetAudience:this.getTargetAudience(e)}}getBaseSteps(){return[{id:"welcome",title:"Bienvenue sur MonPlanRetraite.ca",description:"Découvrez les fonctionnalités principales et la philosophie de sécurité de notre plateforme.",component:"WelcomeStep",estimatedTime:3,isCompleted:!1,isOptional:!1,category:"essential",helpText:"Cette étape vous familiarise avec l'interface et les principes de sécurité.",tips:["Toutes vos données restent sur votre appareil","Aucune information n'est transmise à nos serveurs","Vous pouvez sauvegarder vos données localement"]},{id:"security-overview",title:"Comprendre la sécurité de vos données",description:"Apprenez comment vos informations financières sont protégées.",component:"SecurityOverviewStep",estimatedTime:5,isCompleted:!1,isOptional:!1,category:"essential",helpText:"La sécurité est notre priorité absolue. Comprenez nos mesures de protection.",tips:["Chiffrement AES-256-GCM de niveau bancaire","Calculs 100 % locaux dans votre navigateur","Aucun stockage sur serveurs externes"]},{id:"profile-setup",title:"Configuration de votre profil",description:"Renseignez vos informations de base pour des conseils personnalisés.",component:"ProfileSetupStep",estimatedTime:7,isCompleted:!1,isOptional:!1,category:"essential",helpText:"Ces informations permettent de personnaliser vos calculs et conseils.",tips:["Soyez honnête pour des conseils précis","Vous pouvez modifier ces informations à tout moment","Plus d'informations = conseils plus pertinents"]},{id:"budget-basics",title:"Les bases du budget",description:"Apprenez les principes fondamentaux de la budgétisation.",component:"BudgetBasicsStep",estimatedTime:10,isCompleted:!1,isOptional:!1,category:"essential",helpText:"Le budget est la fondation de toute planification financière.",videoUrl:"/videos/budget-basics.mp4",tips:["Commencez par lister tous vos revenus","Catégorisez vos dépenses (fixes vs variables)","Visez un budget équilibré ou excédentaire"]},{id:"emergency-fund",title:"Constituer un fonds d'urgence",description:"Comprenez l'importance et comment créer votre coussin de sécurité.",component:"EmergencyFundStep",estimatedTime:8,isCompleted:!1,isOptional:!1,category:"essential",helpText:"Un fonds d'urgence vous protège des imprévus financiers.",tips:["Visez 3 mois de dépenses essentielles","Gardez cet argent facilement accessible","Constituez-le graduellement, même 25$/mois aide"]},{id:"savings-strategy",title:"Stratégie d'épargne",description:"Découvrez comment épargner efficacement selon vos objectifs.",component:"SavingsStrategyStep",estimatedTime:12,isCompleted:!1,isOptional:!1,category:"recommended",helpText:"L'épargne systématique est la clé de la réussite financière.",tips:["Automatisez vos épargnes","Commencez petit mais soyez constant","Augmentez graduellement votre taux d'épargne"]},{id:"registered-accounts",title:"Comptes enregistrés (REER, CELI)",description:"Comprenez les avantages fiscaux des comptes enregistrés.",component:"RegisteredAccountsStep",estimatedTime:15,isCompleted:!1,isOptional:!1,category:"recommended",helpText:"Les comptes enregistrés offrent des avantages fiscaux importants.",tips:["CELI : croissance libre d'impôt","REER : déduction fiscale immédiate","Maximisez vos cotisations selon votre situation"]},{id:"retirement-planning",title:"Planification de la retraite",description:"Apprenez les bases de la planification retraite.",component:"RetirementPlanningStep",estimatedTime:20,isCompleted:!1,isOptional:!1,category:"recommended",helpText:"Plus tôt vous commencez, plus facile sera votre retraite.",tips:["Utilisez la règle du 4% comme point de départ","Considérez l'inflation dans vos calculs","Diversifiez vos sources de revenus de retraite"]},{id:"investment-basics",title:"Bases de l'investissement",description:"Introduction aux concepts d'investissement pour débutants.",component:"InvestmentBasicsStep",estimatedTime:18,isCompleted:!1,isOptional:!0,category:"advanced",helpText:"L'investissement peut accélérer l'atteinte de vos objectifs.",tips:["Commencez par comprendre votre tolérance au risque","Diversifiez vos placements","Investissez régulièrement (dollar cost averaging)"]},{id:"debt-management",title:"Gestion des dettes",description:"Stratégies pour gérer et réduire vos dettes efficacement.",component:"DebtManagementStep",estimatedTime:12,isCompleted:!1,isOptional:!0,category:"recommended",prerequisites:["budget-basics"],helpText:"Réduire vos dettes libère de l'argent pour vos objectifs.",tips:["Listez toutes vos dettes avec taux d'intérêt","Priorisez les dettes à taux élevé","Considérez la méthode boule de neige ou avalanche"]},{id:"tax-optimization",title:"Optimisation fiscale de base",description:"Stratégies simples pour réduire votre fardeau fiscal.",component:"TaxOptimizationStep",estimatedTime:15,isCompleted:!1,isOptional:!0,category:"advanced",prerequisites:["registered-accounts"],helpText:"Payez votre juste part d'impôt, pas plus.",tips:["Maximisez vos déductions fiscales","Planifiez le timing de vos revenus","Utilisez les crédits d'impôt disponibles"]},{id:"tools-overview",title:"Tour des outils disponibles",description:"Découvrez tous les calculateurs et outils à votre disposition.",component:"ToolsOverviewStep",estimatedTime:10,isCompleted:!1,isOptional:!1,category:"essential",helpText:"Familiarisez-vous avec nos outils pour maximiser leur utilité.",tips:["Chaque outil a un objectif spécifique","Commencez par les outils de base","Sauvegardez régulièrement vos données"]}]}filterStepsForProfile(e,t){let r=[...e];if(t.hasFinancialExperience||(r=r.filter(s=>s.category==="essential"||s.category==="recommended")),t.timeAvailable==="quick"?r=r.filter(s=>s.category==="essential"&&s.estimatedTime<=10):t.timeAvailable==="moderate"&&(r=r.filter(s=>s.category==="essential"||s.category==="recommended"&&s.estimatedTime<=15)),t.primaryGoal==="debt"){const s=e.find(n=>n.id==="debt-management");s&&!r.includes(s)&&r.push(s)}if(t.primaryGoal==="retirement"){const s=e.find(n=>n.id==="retirement-planning");s&&!r.includes(s)&&r.push(s)}return r}orderStepsByPriority(e,t){const r=[...e];return r.sort((s,n)=>{const a={essential:0,recommended:1,advanced:2},i=a[s.category]-a[n.category];return i!==0?i:s.estimatedTime-n.estimatedTime}),t.primaryGoal==="budget"?this.moveStepToPosition(r,"budget-basics",3):t.primaryGoal==="retirement"?this.moveStepToPosition(r,"retirement-planning",4):t.primaryGoal==="debt"&&this.moveStepToPosition(r,"debt-management",4),r}moveStepToPosition(e,t,r){const s=e.findIndex(n=>n.id===t);if(s!==-1){const[n]=e.splice(s,1);e.splice(Math.min(r,e.length),0,n)}}getPathName(e){const t={budget:"Maîtrise du Budget",savings:"Stratégie d'Épargne",retirement:"Planification Retraite",debt:"Liberté Financière",investment:"Investissement Intelligent"},r=e.hasFinancialExperience?"Intermédiaire":"Débutant",s=t[e.primaryGoal]||"Planification Complète";return`Parcours ${r} - ${s}`}getPathDescription(e){const t={quick:"parcours express (15-20 minutes)",moderate:"parcours équilibré (30-45 minutes)",thorough:"parcours complet (60+ minutes)"},r={budget:"pour maîtriser votre budget et contrôler vos dépenses",savings:"pour développer une stratégie d'épargne efficace",retirement:"pour planifier sereinement votre retraite",debt:"pour vous libérer de vos dettes et retrouver la liberté financière",investment:"pour faire fructifier votre argent intelligemment"},s=t[e.timeAvailable],n=r[e.primaryGoal]||"pour une planification financière complète";return`Un ${s} personnalisé ${n}. Adapté à votre niveau d'expérience et vos objectifs spécifiques.`}getTargetAudience(e){const t=[];return e.hasFinancialExperience||t.push("débutants en finance"),e.age<35?t.push("jeunes professionnels"):e.age>=50&&t.push("pré-retraités"),e.hasChildren&&t.push("parents"),e.employmentStatus==="self-employed"&&t.push("travailleurs autonomes"),t.length>0?t.join(", "):"tous les utilisateurs"}completeStep(e,t){const r=this.getCompletedSteps(e);r.add(t),localStorage.setItem(`onboarding-${e}`,JSON.stringify([...r]))}getCompletedSteps(e){const t=localStorage.getItem(`onboarding-${e}`);return t?new Set(JSON.parse(t)):new Set}calculateProgress(e){const t=this.getCompletedSteps(e.id),r=e.steps.filter(a=>t.has(a.id)).length,s=e.steps.length,n=s>0?Math.round(r/s*100):0;return{completed:r,total:s,percentage:n}}getNextStep(e){const t=this.getCompletedSteps(e.id);for(const r of e.steps)if(!t.has(r.id)){if(r.prerequisites&&!r.prerequisites.every(n=>t.has(n)))continue;return r}return null}resetPath(e){localStorage.removeItem(`onboarding-${e}`)}saveUserProfile(e){localStorage.setItem("user-profile",JSON.stringify(e))}getUserProfile(){const e=localStorage.getItem("user-profile");return e?JSON.parse(e):null}};L(Ae,"instance");let Ar=Ae;const Te={free:{plan:"free",price:"0 $",badge:"Gratuit",description:"🔍 DÉCOUVREZ VOTRE POTENTIEL ! Inclut la trousse d’urgence complète (sauvegarde + impression) et 5 calculateurs de base — initiation professionnelle pour développer votre confiance. Parfait pour se familiariser avec MonPlanRetraite.ca",features:{maxSimulations:5,maxReports:1,maxProfiles:1,maxExpenseProjects:1,maxSavedScenarios:1,maxMonteCarloIterations:0,maxCompareScenarios:0,allowCSVExport:!1,exportWatermark:!1,hasAdvancedAnalytics:!1,hasExportPDF:!1,hasCashflowManagement:!0,hasExpensePlanning:!0,hasMonteCarloSimulations:!1,hasWithdrawalStrategies:!1,hasTaxOptimization:!1,hasFinancialAssistant:!0,hasBudgetModule:!1,hasCELISuccessionModule:!1,hasTaxImpactAt65Calculator:!1,hasTenEssentialTipsDashboard:!1,hasAssetConsolidationModule:!1,hasCashWedgeBucketModule:!1,hasTaxEducationCenter:!1,hasFourPercentRuleModule:!1,hasOptimalAllocationModule:!1,hasExcessLiquidityDetector:!1,hasInflationProtectionCenter:!1,hasBehavioralBiasEducator:!1,hasAIConsulting:!1,hasSuccessionPlanning:!1,hasEmergencyPlanning:!0,hasRealEstateOptimization:!1,hasRREGOPModule:!1,hasSRGModule:!1,hasRRQCPPOptimization:!1,hasOASGISAnalysis:!1,hasAdvancedCalculators:!1,hasCoastFIRECalculator:!1,hasMortgageCalculator:!1,hasRetirementProjections:!1,hasProfessionalReports:!1,hasComparativeAnalysis:!1,hasPredictiveAnalytics:!1,hasStressTestAnalysis:!1,hasSecureStorage:!0,hasAutomaticBackup:!1,hasDataEncryption:!0,hasAdvancedInterface:!0,hasMultiLanguageSupport:!0,hasMobileOptimization:!0,hasAccessibilityFeatures:!0,hasIntegrations:!1,hasPrioritySupport:!1,hasPersonalizedTraining:!1}},professional:{plan:"professional",price:"297 $/an",priceId:"price_professional_annual",badge:"Professionnel",description:"💪 OUTILS COMPLETS POUR COUPLES ! Tout ce qu’il faut pour planifier sérieusement à la maison: analyses avancées bornées, Monte Carlo (aperçu), PDF résumé. Idéal pour budgéter et comparer des scénarios simples.",features:{maxSimulations:50,maxReports:30,maxProfiles:2,maxExpenseProjects:-1,maxSavedScenarios:20,maxMonteCarloIterations:100,maxCompareScenarios:3,allowCSVExport:!1,exportWatermark:!0,hasAdvancedAnalytics:!0,hasExportPDF:!0,hasCashflowManagement:!0,hasExpensePlanning:!0,hasMonteCarloSimulations:!0,hasWithdrawalStrategies:!0,hasTaxOptimization:!0,hasFinancialAssistant:!0,hasBudgetModule:!0,hasCELISuccessionModule:!0,hasTaxImpactAt65Calculator:!0,hasTenEssentialTipsDashboard:!0,hasAssetConsolidationModule:!0,hasCashWedgeBucketModule:!0,hasTaxEducationCenter:!0,hasFourPercentRuleModule:!0,hasOptimalAllocationModule:!0,hasExcessLiquidityDetector:!0,hasInflationProtectionCenter:!0,hasBehavioralBiasEducator:!0,hasAIConsulting:!1,hasSuccessionPlanning:!1,hasEmergencyPlanning:!0,hasRealEstateOptimization:!1,hasRREGOPModule:!0,hasSRGModule:!0,hasRRQCPPOptimization:!0,hasOASGISAnalysis:!0,hasAdvancedCalculators:!0,hasCoastFIRECalculator:!0,hasMortgageCalculator:!0,hasRetirementProjections:!0,hasProfessionalReports:!1,hasComparativeAnalysis:!0,hasPredictiveAnalytics:!1,hasStressTestAnalysis:!1,hasSecureStorage:!0,hasAutomaticBackup:!0,hasDataEncryption:!0,hasAdvancedInterface:!0,hasMultiLanguageSupport:!0,hasMobileOptimization:!0,hasAccessibilityFeatures:!0,hasIntegrations:!1,hasPrioritySupport:!1,hasPersonalizedTraining:!1}},expert:{plan:"expert",price:"597 $/an",priceId:"price_expert_annual",badge:"Expert",description:"🚀 NIVEAU CONSULTANT SANS RENDEZ-VOUS. Simulations illimitées, Monte Carlo 2000 itérations, rapports professionnels, analyses de sensibilité et exports (PDF pro + CSV). Alternative au plan à 3 000 $ (sans conseil personnalisé).",features:{maxSimulations:-1,maxReports:-1,maxProfiles:-1,maxExpenseProjects:-1,maxSavedScenarios:-1,maxMonteCarloIterations:2e3,maxCompareScenarios:10,allowCSVExport:!0,exportWatermark:!1,hasAdvancedAnalytics:!0,hasExportPDF:!0,hasCashflowManagement:!0,hasExpensePlanning:!0,hasMonteCarloSimulations:!0,hasWithdrawalStrategies:!0,hasTaxOptimization:!0,hasFinancialAssistant:!0,hasBudgetModule:!0,hasCELISuccessionModule:!0,hasTaxImpactAt65Calculator:!0,hasTenEssentialTipsDashboard:!0,hasAssetConsolidationModule:!0,hasCashWedgeBucketModule:!0,hasTaxEducationCenter:!0,hasFourPercentRuleModule:!0,hasOptimalAllocationModule:!0,hasExcessLiquidityDetector:!0,hasInflationProtectionCenter:!0,hasBehavioralBiasEducator:!0,hasAIConsulting:!0,hasSuccessionPlanning:!0,hasEmergencyPlanning:!0,hasRealEstateOptimization:!0,hasRREGOPModule:!0,hasSRGModule:!0,hasRRQCPPOptimization:!0,hasOASGISAnalysis:!0,hasAdvancedCalculators:!0,hasCoastFIRECalculator:!0,hasMortgageCalculator:!0,hasRetirementProjections:!0,hasProfessionalReports:!0,hasComparativeAnalysis:!0,hasPredictiveAnalytics:!0,hasStressTestAnalysis:!0,hasSecureStorage:!0,hasAutomaticBackup:!0,hasDataEncryption:!0,hasAdvancedInterface:!0,hasMultiLanguageSupport:!0,hasMobileOptimization:!0,hasAccessibilityFeatures:!0,hasIntegrations:!1,hasPrioritySupport:!1,hasPersonalizedTraining:!1}}},pn=(c,e,t)=>{if(c==="professional"&&e==="expert"){const l=Math.max(0,t)*25,o=297+l,u=597-o;return{price:Math.round(l*100)/100,description:`Upgrade Expert pour ${t} mois restants`,savings:`Économisez ${u.toFixed(2)} $ vs achat séparé`,totalPaid:Math.round(o*100)/100}}return{price:120,description:"Upgrade standard",savings:"Prix fixe",totalPaid:120}},xn=(c,e,t)=>{const r=new Date,s=new Date(t),n=Math.floor((r.getTime()-s.getTime())/(1e3*60*60*24*30.44)),a=Math.max(12-n,0);if(a===0)return{price:"597,00 $",description:"Nouvel abonnement Expert",savings:"Prix standard",monthsRemaining:0,totalPaid:"597,00 $"};const i=pn(c,e,a);return{price:`${i.price.toFixed(2)} $`,description:i.description,savings:i.savings,monthsRemaining:a,totalPaid:`${i.totalPaid.toFixed(2)} $`}},Di=(c,e)=>{const r=Te[e].features[c];return typeof r=="boolean"?r:typeof r=="number"?r===-1||r>0:!1},Bi=c=>c==="hasAdvancedAnalytics"||c==="hasMonteCarloSimulations"||c==="hasBudgetModule"||c==="hasExportPDF"||c==="hasWithdrawalStrategies"||c==="hasTaxOptimization"||c==="hasRREGOPModule"||c==="hasSRGModule"||c==="hasRRQCPPOptimization"||c==="hasAdvancedCalculators"||c==="hasComparativeAnalysis"||c==="hasOASGISAnalysis"||c==="hasCoastFIRECalculator"||c==="hasMortgageCalculator"||c==="hasRetirementProjections"||c==="hasAutomaticBackup"?"professional":c==="hasAIConsulting"||c==="hasPredictiveAnalytics"||c==="hasSuccessionPlanning"||c==="hasRealEstateOptimization"||c==="hasStressTestAnalysis"||c==="hasProfessionalReports"?"expert":c==="hasEmergencyPlanning"||c==="hasCashflowManagement"||c==="hasExpensePlanning"||c==="hasFinancialAssistant"||c==="hasSecureStorage"||c==="hasDataEncryption"||c==="hasAdvancedInterface"||c==="hasMultiLanguageSupport"||c==="hasMobileOptimization"||c==="hasAccessibilityFeatures"?"free":"professional",Ii=(c,e)=>c==="free"?`Passez de la version gratuite à la version ${Te[e].badge} pour débloquer cette fonctionnalité`:c==="professional"&&e==="expert"?`Passez de la version ${Te.professional.badge} à la version ${Te.expert.badge} pour accéder aux fonctionnalités premium`:`Cette fonctionnalité nécessite le forfait ${Te[e].badge}`,Er={EARLYBIRD30:{code:"EARLYBIRD30",discount:30,description:"30 % de réduction - Lancement",validUntil:"2025-12-31",maxUses:100},SAVINGS40:{code:"SAVINGS40",discount:40,description:"40 % de réduction - Économies",validUntil:"2025-12-31",maxUses:50},FOUNDER50:{code:"FOUNDER50",discount:50,description:"50 % de réduction - Fondateurs",validUntil:"2025-12-31",maxUses:25},TESTER100:{code:"TESTER100",discount:100,description:"100 % gratuit - Tests et développement",validUntil:"2025-12-31",maxUses:999,unlimitedFeatures:!0,testMode:!0},Calvin2025:{code:"Calvin2025",discount:100,description:"100 % gratuit - Tests Calvin jusqu'au 31 décembre 2026",validUntil:"2026-12-31",maxUses:9999,unlimitedFeatures:!0,testMode:!0}},Ti=(c,e)=>{const t=Te[c];if(!t)return!1;const r=t.features[e];return typeof r=="boolean"?r:typeof r=="number"?r===-1||r>0:!1},Pi=[{key:"inflation-protection",labelFr:"Centre anti‑inflation — protéger le pouvoir d'achat",labelEn:"Inflation protection center — protect purchasing power",descFr:"Des idées simples pour garder votre pouvoir d’achat.",descEn:"Simple ideas to keep your purchasing power.",tier:"expert"},{key:"budget",labelFr:"Budget et dépenses — suivre votre argent chaque mois",labelEn:"Budget and expenses — track your money monthly",descFr:"Notez vos revenus et vos dépenses. Voyez où va votre argent chaque mois.",descEn:"Write down income and expenses. See where your money goes each month.",tier:"free"},{key:"basic-calcs",labelFr:"Calculateurs de base (5 outils) — réponses rapides",labelEn:"Basic calculators (5 tools) — quick answers",descFr:"Rendement simple, Comparateur d’achat, Budget (lite), Aperçu RRQ/CPP, Conseils essentiels (aperçu).",descEn:"Simple return, Purchase comparator, Budget (lite), RRQ/CPP preview, Essential tips (preview).",tier:"free"},{key:"blog-44",labelFr:"44+ articles de blog — bien vous préparer",labelEn:"44+ blog articles — get retirement-ready",descFr:"Accédez gratuitement à notre bibliothèque pour bien vous préparer à la retraite.",descEn:"Free access to our library to get ready for retirement.",tier:"free"},{key:"rrq-cpp",labelFr:"Revenus et RRQ/CPP — voir vos montants",labelEn:"Income and RRQ/CPP — see your amounts",descFr:"Entrez vos montants de retraite et voyez l’effet dans votre budget.",descEn:"Enter retirement amounts and see the impact in your budget.",tier:"free"},{key:"security",labelFr:"Sécurité bancaire (AES‑256) — vos données restent ici",labelEn:"Bank‑level security (AES‑256) — data stays here",descFr:"Vos données ne quittent pas votre appareil. Chiffrées comme une banque.",descEn:"Your data never leaves your device. Encrypted like a bank.",tier:"free"},{key:"adv-calcs",labelFr:"Comprendre vos rendements (aperçu Monte Carlo)",labelEn:"Understand your returns (Monte Carlo preview)",descFr:"Voyez simplement si votre argent progresse bien, sans jargon.",descEn:"See simply if your money is doing well, without jargon.",tier:"pro"},{key:"ai-assistant",labelFr:"Assistant IA — évite les grosses erreurs",labelEn:"AI Assistant — avoids big mistakes",descFr:"Avertit avant une mauvaise décision (impôts, retraits, dates clés).",descEn:"Warns you before a bad decision (tax, withdrawals, key dates).",tier:"pro"},{key:"tax-opt",labelFr:"Moins d’impôt: ordre de retraits plus intelligent",labelEn:"Pay less tax: smarter withdrawal order",descFr:"Aide à payer moins d’impôt sur plusieurs années, simplement.",descEn:"Helps pay less tax over the years, in simple terms.",tier:"pro"},{key:"rrq-cpp-optim",labelFr:"RRQ/CPP: meilleur moment pour commencer",labelEn:"RRQ/CPP: best time to start",descFr:"Vous guide pour choisir le moment qui vous avantage le plus.",descEn:"Guides you to pick the time that benefits you most.",tier:"pro"},{key:"oas-gis",labelFr:"SV/OAS & SRG: éviter les pertes",labelEn:"OAS & GIS: avoid losses",descFr:"Réduit les pertes liées aux seuils de revenu, simplement.",descEn:"Reduces losses from income thresholds, in simple terms.",tier:"pro"},{key:"rregop",labelFr:"Module RREGOP complet",labelEn:"Complete RREGOP module",tier:"pro"},{key:"srg",labelFr:"Module SRG complet",labelEn:"Complete GIS module",tier:"pro"},{key:"export-opt",labelFr:"Export Optimisation (résumé robuste) — PDF clair à partager",labelEn:"Optimization export (robust summary) — clear PDF to share",descFr:"Un PDF simple à montrer à votre conseiller ou votre famille.",descEn:"A clear PDF to show your advisor or family.",tier:"pro"},{key:"backup-auto",labelFr:"Sauvegarde automatique locale — copie de sécurité",labelEn:"Automatic local backup — safety copy",descFr:"Sauvegarde votre dossier sur votre clé USB ou disque, sans internet.",descEn:"Backs up your file on your USB or drive, no internet needed.",tier:"pro"},{key:"cash-wedge",labelFr:"Stratégie de seau (cash wedge) — coussin pour les dépenses",labelEn:"Cash wedge strategy — cushion for expenses",descFr:"Mets de côté quelques mois d’argent pour dormir tranquille.",descEn:"Set aside a few months of money so you can sleep well.",tier:"pro"},{key:"asset-consolidation",labelFr:"Consolidation d'actifs — tout voir en un endroit",labelEn:"Asset consolidation — see everything in one place",descFr:"Regroupez vos comptes pour avoir une vue simple et complète.",descEn:"Group your accounts for a simple, complete view.",tier:"pro"},{key:"tax-edu",labelFr:"Centre d'éducation fiscale — apprendre pas à pas",labelEn:"Tax education center — learn step by step",descFr:"Des explications claires pour comprendre vos impôts à la retraite.",descEn:"Clear explanations to understand retirement taxes.",tier:"pro"},{key:"four-percent",labelFr:"Règle des 4 % (modernisée) — repères simples",labelEn:"4% rule (modernized) — simple guideposts",descFr:"Un repère facile pour éviter de retirer trop d’argent trop vite.",descEn:"A simple guide to avoid taking out money too fast.",tier:"pro"},{key:"optimal-allocation",labelFr:"Allocation optimale — répartir l'argent simplement",labelEn:"Optimal allocation — simple asset mix",descFr:"Une recette simple pour choisir combien en actions, obligations, etc.",descEn:"A simple recipe to choose how much in stocks, bonds, etc.",tier:"pro"},{key:"excess-liquidity",labelFr:"Détecteur de sur‑liquidités — argent qui dort",labelEn:"Excess liquidity detector — idle cash finder",descFr:"Repère l’argent qui ne travaille pas pour vous.",descEn:"Finds money that isn’t working for you.",tier:"pro"},{key:"behavioral-bias",labelFr:"Biais comportementaux — éviter les pièges courants",labelEn:"Behavioral biases — avoid common pitfalls",descFr:"Explique les pièges fréquents qui font perdre de l’argent.",descEn:"Explains common traps that make people lose money.",tier:"pro"},{key:"longevity",labelFr:"Planification de longévité — vivre 25–35 ans en retraite",labelEn:"Longevity planning — plan for 25–35 years retired",descFr:"Planifiez sur 25–35 ans pour ne pas manquer d’argent.",descEn:"Plan for 25–35 years so you don’t run out of money.",tier:"pro"},{key:"mc-1000",labelFr:"Tester votre plan dans 1000 scénarios",labelEn:"Test your plan in 1000 scenarios",descFr:"Vérifie si votre plan tient la route quand la vie bouge.",descEn:"Checks if your plan holds up when life changes.",tier:"expert"},{key:"stress-tests",labelFr:"Stress tests (séquence, inflation, longévité) — résister aux chocs",labelEn:"Stress tests (sequence, inflation, longevity) — withstand shocks",descFr:"Vérifie si votre plan tient le coup si la vie bouscule vos finances.",descEn:"Checks if your plan holds up when life shakes your finances.",tier:"expert"},{key:"predictive-ai",labelFr:"IA — voir les tendances à venir",labelEn:"AI — see upcoming trends",descFr:"Apercevez les tendances possibles pour décider plus simplement.",descEn:"See possible trends to decide more simply.",tier:"expert"},{key:"consultant-reports",labelFr:"Rapports prêts à imprimer (niveau consultant)",labelEn:"Print‑ready reports (consultant level)",descFr:"Rapports clairs à montrer à un conseiller ou à la famille.",descEn:"Clear reports to show an advisor or family.",tier:"expert"},{key:"estate",labelFr:"Planification successorale complète",labelEn:"Complete estate planning",descFr:"Préparez votre héritage pour protéger vos proches.",descEn:"Prepare your legacy to protect your loved ones.",tier:"expert"},{key:"real-estate",labelFr:"Optimisation immobilière avancée",labelEn:"Advanced real estate optimization",descFr:"Choix immobiliers plus clairs (garder, vendre, louer).",descEn:"Clearer real‑estate choices (keep, sell, rent).",tier:"expert"},{key:"ai-consulting",labelFr:"Conseils IA avancés — suggestions plus poussées",labelEn:"Advanced AI consulting — deeper suggestions",descFr:"Des recommandations plus fines et adaptées à vos choix.",descEn:"Finer recommendations adapted to your choices.",tier:"expert"},{key:"dyn-withdrawal",labelFr:"Retraits dynamiques — adapter le rythme",labelEn:"Dynamic withdrawals — adapt the pace",descFr:"Ajuste les retraits selon les marchés et vos objectifs, avec règles avancées.",descEn:"Adjust withdrawals to markets and goals with advanced rules.",tier:"expert"},{key:"ferr-opt",labelFr:"Optimisation du FERR — réduire l’impôt sur la durée",labelEn:"RRIF optimization — reduce long‑term tax",descFr:"Planifie des retraits FERR efficaces pour limiter l’impôt futur.",descEn:"Plans effective RRIF withdrawals to limit future tax.",tier:"expert"},{key:"rrsp-meltdown",labelFr:"Fonte du REER — stratégie contrôlée",labelEn:"RRSP meltdown — controlled strategy",descFr:"Réduit prudemment vos REER pour lisser l’impôt et éviter les seuils.",descEn:"Carefully wind down RRSPs to smooth taxes and avoid thresholds.",tier:"expert"},{key:"tax-opt-multi",labelFr:"Optimisation fiscale multi‑sources — mieux coordonner",labelEn:"Multi‑source tax optimization — better coordination",descFr:"Coordonne retraits et revenus (REER/CELI/Non‑enreg.) pour payer moins.",descEn:"Coordinates withdrawals and income (RRSP/TFSA/Non‑registered) to pay less.",tier:"expert"},{key:"rvdaa",labelFr:"RVDAA — scénarios avancés",labelEn:"RVDAA — advanced scenarios",descFr:"Outil spécialisé pour tester des scénarios d’épargne et de décaissement.",descEn:"Specialized tool to test saving and decumulation scenarios.",tier:"expert"}],zt={},mn={publishableKey:zt?.VITE_STRIPE_PUBLISHABLE_KEY,secretKey:zt?.VITE_STRIPE_SECRET_KEY,webhookSecret:zt?.VITE_STRIPE_WEBHOOK_SECRET},yr={professional:"price_professional_annual",expert:"price_expert_annual"};class fn{constructor(){L(this,"stripe");this.initializeStripe()}initializeStripe(){if(typeof window<"u"&&window.Stripe)try{this.stripe=window.Stripe(mn.publishableKey)}catch{this.stripe=null}}ensureStripeInitialized(){return this.stripe||this.initializeStripe(),this.stripe}calculateUpgradePrice(e,t,r){return xn(e,t,r)}canUpgrade(e,t){return e==="free"&&t==="professional"||e==="free"&&t==="expert"||e==="professional"&&t==="expert"}getStripePlanId(e){switch(e){case"professional":return yr.professional;case"expert":return yr.expert;default:throw new Error(`Plan non supporté: ${e}`)}}async createUpgradeCheckoutSession(e,t,r,s,n){try{const a=this.calculateUpgradePrice(e,t,s),i=await fetch("/api/stripe/create-upgrade-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromPlan:e,toPlan:t,customerId:r,upgradePrice:a.price,monthsRemaining:a.monthsRemaining,totalPaid:a.totalPaid,currentSubscriptionId:n,metadata:{upgradeType:"time_adjusted",fromPlan:e,toPlan:t,monthsRemaining:a.monthsRemaining.toString()}})});if(!i.ok)throw new Error("Erreur lors de la création de la session de paiement");const{sessionId:l,url:o}=await i.json();return{sessionId:l,url:o}}catch{throw new Error("Impossible de créer la session de paiement")}}async processUpgradeAfterPayment(e,t){try{const r=await fetch(`/api/stripe/retrieve-session?sessionId=${e}`);if(!r.ok)throw new Error("Impossible de récupérer la session de paiement");const s=await r.json(),n=await fetch("/api/stripe/process-upgrade",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,currentSubscriptionId:t,customerId:s.customer,newPlan:s.metadata.toPlan})});if(!n.ok)throw new Error("Erreur lors du traitement de l'upgrade");return{success:!0,newSubscriptionId:(await n.json()).newSubscriptionId,message:"Upgrade réussi !"}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Erreur inconnue"}}}async redirectToCheckout(e){if(!this.stripe)throw new Error("Stripe non initialisé");const{error:t}=await this.stripe.redirectToCheckout({sessionId:e});if(t)throw new Error(`Erreur redirection Stripe: ${t.message}`)}async checkPaymentStatus(e){try{const t=await fetch(`/api/stripe/check-payment-status?sessionId=${e}`);if(!t.ok)throw new Error("Impossible de vérifier le statut du paiement");const{status:r}=await t.json();return r}catch{return"failed"}}async cancelUpgrade(e){try{return(await fetch("/api/stripe/cancel-upgrade",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e})})).ok}catch{return!1}}}const wi=new fn;class hn{static calculateFourPercentRule(e){const t=this.extractPortfolioData(e),r=this.extractExpenseData(e),s=this.extractAgeData(e),n=t.total,a=n*this.FOUR_PERCENT_PARAMS.SAFE_WITHDRAWAL_RATE,i=a/12,l=this.analyzeSafetyLevel(n,r.monthlyTotal,s.age),o=n>0?r.monthlyTotal*12/n:0,u=Math.max(this.FOUR_PERCENT_PARAMS.MIN_STOCK_ALLOCATION,Math.min(this.FOUR_PERCENT_PARAMS.MAX_STOCK_ALLOCATION,(this.FOUR_PERCENT_PARAMS.STOCK_ALLOCATION_FORMULA-s.age)/100)),m=this.calculateTrinityProbability(o*100,u,30),d=r.monthlyTotal>0?i/r.monthlyTotal*100:0,p=i-r.monthlyTotal,x=r.monthlyTotal*12/this.FOUR_PERCENT_PARAMS.SAFE_WITHDRAWAL_RATE,E=Math.max(0,x-n),v=this.estimateSavingsRate(e),f=E>0&&v>0?Math.ceil(E/(v*12)):0,g=this.calculateOptimizedRate(n,r.monthlyTotal,s.age),h=r.monthlyTotal*this.FOUR_PERCENT_PARAMS.INFLATION_ADJUSTMENT;return{totalPortfolio:n,annualWithdrawal:a,monthlyWithdrawal:i,withdrawalRate:o,safetyLevel:l.level,probabilityOfSuccess:m,yearsOfSafety:l.years,currentExpenses:r.monthlyTotal,expensesCoverage:d,monthlyShortfall:p,recommendedPortfolioSize:x,additionalSavingsNeeded:E,timeToReachTarget:f,optimizedWithdrawalRate:g,inflationAdjustment:h,sequenceRiskMitigation:this.getSequenceRiskStrategies(n,s.age)}}static extractPortfolioData(e){const t=e.savings??{},r=t.reer1||0,s=t.celi1||0,n=t.placements1||0,a=t.epargne1||0,i=t.cri1||0;return{total:r+s+n+a+i,breakdown:{reer:r,celi:s,placements:n,epargne:a,cri:i}}}static extractExpenseData(e){const t=e.cashflow??{},r=t.logement||0,s=t.servicesPublics||0,n=t.assurances||0,a=t.telecom||0,i=t.alimentation||0,l=t.transport||0,o=t.sante||0,u=t.loisirs||0;return{monthlyTotal:r+s+n+a+i+l+o+u,breakdown:{logement:r,servicesPublics:s,assurances:n,telecom:a,alimentation:i,transport:l,sante:o,loisirs:u}}}static extractAgeData(e){const t=e.personal?.naissance1;let r=65;if(t){const a=new Date(t),i=new Date;r=i.getFullYear()-a.getFullYear();const l=i.getMonth()-a.getMonth();(l<0||l===0&&i.getDate()70&&(i=Math.min(i+5,35),a=Math.min(a+.05,.99)),{level:n,probability:a,years:i}}static calculateOptimizedRate(e,t,r){let s=this.FOUR_PERCENT_PARAMS.SAFE_WITHDRAWAL_RATE;return r<55?s=.035:r>75&&(s=.045),e<25e4?s=Math.max(s-.005,.025):e>1e6&&(s=Math.min(s+.005,.05)),s}static estimateSavingsRate(e){const t=e.personal?.salaire1||0,r=this.extractExpenseData(e).monthlyTotal*12;if(t===0)return 0;const s=t*.75,n=Math.max(0,s-r)*.5;return Math.max(n/12,t*.05/12)}static getSequenceRiskStrategies(e,t){const r=[];return r.push("Garder 12-24 mois de dépenses en liquidités"),r.push("Diversifier géographiquement (Canada, É-U, International)"),e<5e5?(r.push("Privilégier les FNB à faible coût"),r.push("Reporter la retraite de 2-3 ans si possible")):(r.push("Considérer une stratégie bucket (compartiments)"),r.push("Utiliser des produits à revenu fixe de qualité")),t<60?(r.push("Maintenir 60-70% en actions pour la croissance"),r.push("Réinvestir les dividendes pendant l'accumulation")):(r.push("Réduire graduellement l'exposition aux actions"),r.push("Privilégier les dividendes et distributions stables")),r}static calculateTrinityProbability(e,t,r=30){const s={low:{3:.98,3.5:.96,4:.92,4.5:.86,5:.78,5.5:.7,6:.62,7:.45},medium:{3:.99,3.5:.98,4:.95,4.5:.9,5:.83,5.5:.76,6:.68,7:.55},high:{3:.99,3.5:.98,4:.96,4.5:.92,5:.87,5.5:.81,6:.74,7:.63}},n=t<.25?"low":t<.75?"medium":"high",a=Math.round(e*10)/10,i=Math.min(7,Math.max(3,a)),l=s[n][i]??.5;if(r!==30){const o=r-30,u=Math.max(-.05,Math.min(.05,o/5*.01));return Math.max(0,Math.min(1,l+u))}return l}static getWithdrawalStrategies(e){this.extractAgeData(e).age;const t=this.extractPortfolioData(e).total;return[{name:"Règle du 4% classique",description:"Retrait initial de 4%, ajusté annuellement pour l'inflation",rateYear1:.04,rateYear5:.042,rateYear10:.045,rateYear20:.05,rateYear30:.055,advantages:["Simple à comprendre","Historiquement fiable","Prévisible"],disadvantages:["Rigide","Ne s'adapte pas aux conditions de marché"],suitability:t>5e5?"high":"medium"},{name:"Stratégie dynamique",description:"Taux ajusté selon les performances du marché",rateYear1:.04,rateYear5:.035,rateYear10:.045,rateYear20:.04,rateYear30:.042,advantages:["S'adapte aux conditions","Réduit le risque de séquence"],disadvantages:["Plus complexe","Revenus variables"],suitability:"high"},{name:"Stratégie buckets (compartiments)",description:"Division en compartiments court/moyen/long terme",rateYear1:.03,rateYear5:.04,rateYear10:.045,rateYear20:.04,rateYear30:.035,advantages:["Sécurité élevée","Gestion du risque optimale"],disadvantages:["Complexe à gérer","Nécessite un gros portefeuille"],suitability:t>75e4?"high":"low"}]}static generateRecommendations(e,t){const r=this.getWithdrawalStrategies(t),s=r.find(i=>i.suitability==="high")||r[0],n=r.filter(i=>i!==s),a=[];return(e.safetyLevel==="dangerous"||e.safetyLevel==="risky")&&a.push({id:"increase-savings",priority:"high",category:"savings",action:`Épargner ${Math.round(e.additionalSavingsNeeded/1e3)}k$ supplémentaires`,impact:"Atteindre la sécurité financière pour la retraite",timeframe:`${e.timeToReachTarget} ans`,difficulty:"moderate"}),e.monthlyShortfall<0&&a.push({id:"reduce-expenses",priority:"medium",category:"expenses",action:`Réduire les dépenses de ${Math.round(Math.abs(e.monthlyShortfall))}$/mois`,impact:"Équilibrer le budget retraite avec la règle du 4%",timeframe:"6 mois",difficulty:"easy"}),{primaryStrategy:s,alternativeStrategies:n,portfolioAdjustments:["Diversifier entre REER, CELI et comptes non-enregistrés","Maintenir une allocation équilibrée actions/obligations","Privilégier les fonds à faible coût (FNB)"],taxOptimizations:["Utiliser le fractionnement de pension après 65 ans","Optimiser la séquence de décaissement (CELI en dernier)","Planifier les retraits REER/FERR avant 71 ans"],riskMitigations:e.sequenceRiskMitigation,actionItems:a}}}L(hn,"FOUR_PERCENT_PARAMS",{SAFE_WITHDRAWAL_RATE:.04,CONSERVATIVE_RATE:.035,AGGRESSIVE_RATE:.045,SUCCESS_PROBABILITY_4_PERCENT:.95,SUCCESS_PROBABILITY_3_5_PERCENT:.98,SUCCESS_PROBABILITY_5_PERCENT:.85,INFLATION_ADJUSTMENT:.025,SEQUENCE_RISK_BUFFER:.1,LONGEVITY_ADJUSTMENT:1.15,STOCK_ALLOCATION_FORMULA:110,MIN_STOCK_ALLOCATION:.3,MAX_STOCK_ALLOCATION:.8,MIN_PORTFOLIO_SIZE:1e5,MAX_WITHDRAWAL_RATE:.06,MIN_CASH_BUFFER:12});class Cr{static needsMigration(){return localStorage.getItem(this.MIGRATION_KEY)!==this.VERSION}static migrateUserData(e){const t={success:!0,migratedFields:[],errors:[]};try{e.personal||(e.personal={}),Array.isArray(e.personal.unifiedIncome1)||(e.personal.unifiedIncome1=[],t.migratedFields.push("unifiedIncome1")),Array.isArray(e.personal.unifiedIncome2)||(e.personal.unifiedIncome2=[],t.migratedFields.push("unifiedIncome2")),this.migrateIncomeEntries(e.personal.unifiedIncome1,t),this.migrateIncomeEntries(e.personal.unifiedIncome2,t),this.migrateDateFields(e.personal.unifiedIncome1,t),this.migrateDateFields(e.personal.unifiedIncome2,t);try{e.savings||(e.savings={});const r=e.cashflow&&e.cashflow.logementBreakdown?e.cashflow.logementBreakdown:{};if(e.savings.residencePaiementHypothecaireMensuel==null&&typeof r?.hypotheque=="number"){const s=Number(r.hypotheque)||0;e.savings.residencePaiementHypothecaireMensuel=s,t.migratedFields.push("savings.residencePaiementHypothecaireMensuel")}if(e.savings.residenceTaxesMunicipalesAnnuelles==null&&typeof r?.taxesMunicipales=="number"){const s=(Number(r.taxesMunicipales)||0)*12;e.savings.residenceTaxesMunicipalesAnnuelles=s,t.migratedFields.push("savings.residenceTaxesMunicipalesAnnuelles")}if(e.savings.residenceAssuranceHabitationAnnuelle==null&&typeof r?.assuranceHabitation=="number"){const s=(Number(r.assuranceHabitation)||0)*12;e.savings.residenceAssuranceHabitationAnnuelle=s,t.migratedFields.push("savings.residenceAssuranceHabitationAnnuelle")}}catch(r){t.errors.push(`Migration logementBreakdown→Savings: ${r}`)}localStorage.setItem(this.MIGRATION_KEY,this.VERSION)}catch(r){t.success=!1,t.errors.push(`Erreur lors de la migration: ${r}`)}return t}static migrateIncomeEntries(e,t){Array.isArray(e)&&e.forEach((r,s)=>{try{r.id||(r.id=`income-${Date.now()}-${s}`,t.migratedFields.push(`entry-${s}-id`)),["salaire","rentes","assurance-emploi","dividendes","revenus-location","travail-autonome","autres"].includes(r.type)||(r.type="autres",t.migratedFields.push(`entry-${s}-type`)),typeof r.isActive!="boolean"&&(r.isActive=!0,t.migratedFields.push(`entry-${s}-isActive`)),["salaryStartDate","salaryEndDate","salaryFirstPaymentDate","salaryRevisionDate","eiStartDate","eiFirstPaymentDate","eiRevisionDate","pensionStartDate","pensionFirstPaymentDate"].forEach(l=>{r[l]&&typeof r[l]!="string"&&(r[l]instanceof Date?r[l]=r[l].toISOString().split("T")[0]:r[l]="",t.migratedFields.push(`entry-${s}-${l}`))}),["annualAmount","monthlyAmount","weeklyAmount","salaryNetAmount","salaryRevisionAmount","weeklyGross","weeklyNet","eiRevisionAmount","pensionAmount"].forEach(l=>{r[l]!==void 0&&typeof r[l]!="number"&&(r[l]=parseFloat(r[l])||0,t.migratedFields.push(`entry-${s}-${l}`))})}catch(n){t.errors.push(`Erreur migration entrée ${s}: ${n}`)}})}static migrateDateFields(e,t){Array.isArray(e)&&e.forEach((r,s)=>{["salaryStartDate","salaryEndDate","salaryFirstPaymentDate","salaryRevisionDate","eiStartDate","eiFirstPaymentDate","eiRevisionDate","pensionStartDate","pensionFirstPaymentDate"].forEach(a=>{if(r[a]&&typeof r[a]=="string")try{const i=new Date(r[a]);if(!isNaN(i.getTime())){const l=i.toISOString().split("T")[0];r[a]!==l&&(r[a]=l,t.migratedFields.push(`entry-${s}-${a}-format`))}}catch{r[a]="",t.migratedFields.push(`entry-${s}-${a}-invalid`)}})})}static saveMigratedData(e){try{localStorage.setItem("retirement_data",JSON.stringify(e))}catch{}}}L(Cr,"VERSION","1.2.0"),L(Cr,"MIGRATION_KEY","data_migration_version");class _i{static synchronizeHouseholdIncome(e){const t=e.personal||{},r=t.salaire1||0,s=t.salaire2||0,n=r+s,a=n/12,i=n,l=n>0?Math.min(1.15,1+n/1e5*.05):1,o=this.calculateSectorLongevityImpact(t.secteurActivite1,t.secteurActivite2);return{totalHouseholdIncome:n,person1Income:r,person2Income:s,monthlyHouseholdIncome:a,annualHouseholdIncome:i,incomeMultiplier:l,sectorImpact:o}}static calculateSectorLongevityImpact(e,t){const r={sante:.5,education:.3,technologie:.2,finance:.1,services:0,commerce:-.1,construction:-.3,manufacturier:-.2,autre:0},s=e&&r[e]||0,n=t&&r[t]||0;return(s+n)/2}static calculateIncomeLongevityImpact(e){const{totalHouseholdIncome:t,incomeMultiplier:r,sectorImpact:s}=e;let n=0;t>15e4?n=2:t>1e5?n=1.5:t>75e3?n=1:t>5e4?n=.5:t>3e4?n=0:n=-.5;const a=r,i=Math.min(.3,t/2e5);return{lifeExpectancyAdjustment:n+s,healthMultiplier:a,stressReduction:i}}static updateUserDataWithSynchronizedIncome(e,t){const r=this.synchronizeHouseholdIncome(e);t("personal",{...e.personal,totalHouseholdIncome:r.totalHouseholdIncome,monthlyHouseholdIncome:r.monthlyHouseholdIncome,incomeMultiplier:r.incomeMultiplier,sectorLongevityImpact:r.sectorImpact})}}class J{static generateFingerprint(e){const t=e.personal?.prenom1?.trim().toLowerCase()||"",r=e.personal?.naissance1||"",s=e.personal?.prenom2?.trim().toLowerCase()||"",n=e.personal?.naissance2||"",a=`${t}|${r}|${s}|${n}`;let i=0;for(let l=0;l0&&r.length>0)}static hasMultiProfileCode(){try{return localStorage.getItem("promo-code")===this.MULTI_PROFILE_CODE}catch{return!1}}static activateMultiProfileCode(e){if(e===this.MULTI_PROFILE_CODE)try{return localStorage.setItem("promo-code",e),!0}catch{return!1}return!1}static getCurrentProfile(){try{const e=localStorage.getItem(this.PROFILE_STORAGE_KEY);if(e)return JSON.parse(e)}catch{}return null}static saveCurrentProfile(e){if(!this.isValidProfile(e))return null;try{const t={id:this.generateFingerprint(e),nom1:e.personal.prenom1.trim(),naissance1:e.personal.naissance1,nom2:e.personal.prenom2?.trim()||void 0,naissance2:e.personal.naissance2||void 0,createdAt:new Date().toISOString(),lastSavedAt:new Date().toISOString(),licenseKey:this.generateLicenseKey()};return localStorage.setItem(this.PROFILE_STORAGE_KEY,JSON.stringify(t)),t}catch{return null}}static updateLastSaved(){try{const e=this.getCurrentProfile();e&&(e.lastSavedAt=new Date().toISOString(),localStorage.setItem(this.PROFILE_STORAGE_KEY,JSON.stringify(e)))}catch{}}static checkLicense(e){return{isValid:!0,allowMultipleProfiles:!0,reason:"Blocage de licence temporairement désactivé"}}static clearCurrentProfile(){try{localStorage.removeItem(this.PROFILE_STORAGE_KEY)}catch{}}static generateLicenseKey(){const e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`LIC-${e}-${t}`.toUpperCase()}static getProfileInfo(){const e=this.getCurrentProfile();return e?{hasProfile:!0,profileName:e.nom2?`${e.nom1} et ${e.nom2}`:e.nom1,createdAt:e.createdAt}:{hasProfile:!1,profileName:""}}static hasProfileChanged(e){const t=this.getCurrentProfile();if(!t||!this.isValidProfile(e))return!1;const r=this.generateFingerprint(e);return t.id!==r}}L(J,"LICENSE_STORAGE_KEY","retirement-license-info"),L(J,"PROFILE_STORAGE_KEY","retirement-active-profile"),L(J,"MULTI_PROFILE_CODE","MULTIPLE2025");function gn(c){const e={à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",è:"e",é:"e",ê:"e",ë:"e",ì:"i",í:"i",î:"i",ï:"i",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ù:"u",ú:"u",û:"u",ü:"u",ý:"y",ÿ:"y",ñ:"n",ç:"c",À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",È:"E",É:"E",Ê:"E",Ë:"E",Ì:"I",Í:"I",Î:"I",Ï:"I",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ù:"U",Ú:"U",Û:"U",Ü:"U",Ý:"Y",Ÿ:"Y",Ñ:"N",Ç:"C"};return c.replace(/[àáâãäåèéêëìíîïòóôõöùúûüýÿñçÀÁÂÃÄÅÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝŸÑÇ]/g,t=>e[t]||t)}function br(c){let e=gn(c);return e=e.replace(/[^a-zA-Z0-9]/g,"-"),e=e.replace(/-+/g,"-"),e=e.replace(/^-+|-+$/g,""),e}function Sr(c,e=!0){let t="mon-plan-retraite";if(c.personal?.prenom1){const r=br(c.personal.prenom1),s=c.personal?.prenom2?br(c.personal.prenom2):"";s?t=`${r}-et-${s}-retraite`:t=`${r}-retraite`}if(e){const r=new Date().toISOString().split("T")[0];t+=`-${r}`}return t+".json"}function Mi(c){return!c||typeof c!="string"?"":c.trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function Ni(c){if(!c||typeof c!="string")return{firstName:"",lastName:""};const e=c.trim().split(" ");return e.length===1?{firstName:e[0],lastName:""}:e.length===2?{firstName:e[0],lastName:e[1]}:{firstName:e[0],lastName:e.slice(1).join(" ")}}class Rr{static async saveWithDialog(e,t={}){try{const r=this.generateFilename(e,t),s=this.prepareSaveData(e),n=JSON.stringify(s,null,2),a=new Blob([n],{type:"application/json"});if("showSaveFilePicker"in window)try{const i=await window.showSaveFilePicker({suggestedName:r,types:[{description:"Fichiers de plan de retraite",accept:{"application/json":[".json"]}}]}),l=await i.createWritable();return await l.write(a),await l.close(),J.saveCurrentProfile(e),J.updateLastSaved(),{success:!0,filename:i.name}}catch(i){if(i.name==="AbortError")return{success:!1,error:"Sauvegarde annulée par l'utilisateur"};throw i}else{const i=URL.createObjectURL(a),l=document.createElement("a");return l.href=i,l.download=r,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i),J.saveCurrentProfile(e),J.updateLastSaved(),{success:!0,filename:r}}}catch(r){return{success:!1,error:`Erreur lors de la sauvegarde: ${r instanceof Error?r.message:"Erreur inconnue"}`}}}static async loadWithDialog(){try{if("showOpenFilePicker"in window)try{const[e]=await window.showOpenFilePicker({types:[{description:"Fichiers de plan de retraite",accept:{"application/json":[".json"]}}],multiple:!1}),r=await(await e.getFile()).text(),s=JSON.parse(r),n=this.validateLoadedData(s),a=J.checkLicense(n);return a.isValid?{success:!0,data:n}:{success:!1,blocked:!0,reason:a.reason}}catch(e){if(e.name==="AbortError")return{success:!1,error:"Chargement annulé par l'utilisateur"};throw e}else return new Promise(e=>{const t=document.createElement("input");t.type="file",t.accept=".json",t.onchange=async r=>{const s=r.target.files?.[0];if(!s){e({success:!1,error:"Aucun fichier sélectionné"});return}try{const n=await s.text(),a=JSON.parse(n),i=this.validateLoadedData(a),l=J.checkLicense(i);if(!l.isValid){e({success:!1,blocked:!0,reason:l.reason});return}e({success:!0,data:i})}catch(n){e({success:!1,error:`Erreur lors du chargement: ${n instanceof Error?n.message:"Fichier invalide"}`})}},t.click()})}catch(e){return{success:!1,error:`Erreur lors du chargement: ${e instanceof Error?e.message:"Erreur inconnue"}`}}}static async saveDirectly(e,t={}){try{const r=J.checkLicense(e);if(!r.isValid)return{success:!1,blocked:!0,reason:r.reason,error:"Sauvegarde bloquée par la protection de licence"};const s=t.filename||Sr(e,t.includeTimestamp!==!1),n=this.prepareSaveData(e),a=JSON.stringify(n,null,2),i=new Blob([a],{type:"application/json"}),l=URL.createObjectURL(i),o=document.createElement("a");return o.href=l,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(l),J.saveCurrentProfile(e),J.updateLastSaved(),{success:!0,filename:s}}catch(r){return{success:!1,error:`Erreur lors de la sauvegarde: ${r instanceof Error?r.message:"Erreur inconnue"}`}}}static generateFilename(e,t){return t.filename||Sr(e,t.includeTimestamp!==!1)}static prepareSaveData(e){return{version:"2.0",createdAt:new Date().toISOString(),appName:"Mon Plan Retraite",licenseInfo:J.getProfileInfo(),data:e}}static validateLoadedData(e){if(!e||typeof e!="object")throw new Error("Format de fichier invalide");if(e.personal&&!e.data)return e;if(e.data&&e.version)return e.data;throw new Error("Format de fichier non reconnu")}static canSave(e){return{canSave:!0,reason:"Blocage de licence temporairement désactivé"}}static canLoad(){return{canLoad:!0,reason:"Blocage de licence temporairement désactivé"}}static activateTestMode(e){return J.activateMultiProfileCode(e)}static resetLicense(){J.clearCurrentProfile(),localStorage.removeItem("promo-code")}}L(Rr,"DEFAULT_FILENAME","mon-plan-retraite"),L(Rr,"FILE_EXTENSION",".json");class ki{static trackComparison(e,t){e.currentAge,e.gender,t.find(r=>r.category==="Capital de retraite")?.advantage,new Date().toISOString()}static trackConversion(e){new Date().toISOString()}}class vn{static getCurrentStep(e){return e.personal?.prenom1?e.personal?.salaire1?e.cashflow?.logement?!e.savings?.reer1&&e.savings?.reer1!==0?this.GUIDED_STEPS["expenses-overview"]:e.retirement?.rrqMontantActuel1?this.GUIDED_STEPS["benefits-check"]:this.GUIDED_STEPS["savings-overview"]:this.GUIDED_STEPS["income-overview"]:this.GUIDED_STEPS["personal-profile"]:this.GUIDED_STEPS.welcome}static getNavigationContext(e){const t=this.getCurrentStep(e),r=this.getCompletedSteps(e),s=r.length/Object.keys(this.GUIDED_STEPS).length*100;return{currentStep:t,completedSteps:r,availableSteps:Object.keys(this.GUIDED_STEPS),recommendedNextStep:t.nextSteps[0]||"",progressPercentage:Math.round(s),estimatedTimeRemaining:this.calculateRemainingTime(r),userProfile:this.detectUserProfile(e),assistantPersonality:"bienveillant"}}static getCompletedSteps(e){const t=[];return e.personal?.prenom1&&t.push("welcome"),e.personal?.salaire1&&t.push("personal-profile"),e.cashflow?.logement&&t.push("income-overview"),e.savings?.reer1!==void 0&&t.push("expenses-overview"),e.retirement?.rrqMontantActuel1&&t.push("savings-overview"),t}static calculateRemainingTime(e){const n=(Object.keys(this.GUIDED_STEPS).length-e.length)*3;return n<5?"< 5 minutes":n<10?"5-10 minutes":`${n} minutes`}static detectUserProfile(e){const t=(e.personal?.unifiedIncome1?.length||0)>2,r=(e.savings?.reer1||0)>5e4;return e.personal?.seasonalJobs1?.length||e.retirement?.rregopMembre1||r?"avance":t?"intermediaire":"debutant"}static getContextualAssistantMessage(e,t){const r=e.assistantMessage;this.detectUserProfile(t);const s=t.personal?.prenom1||"";let n=r;return s&&(n=n.replace("Bonjour !",`Bonjour ${s} !`)),{id:`${e.id}-message`,type:e.stepNumber===1?"welcome":"guidance",message:n,emoji:e.assistantAvatar,priority:"medium",actionButtons:this.getAssistantActions(e),dismissible:!1}}static getAssistantActions(e){const t=[];return e.previousStep&&t.push({label:"← Précédent",action:"previous",variant:"outline"}),e.nextSteps.length>0&&t.push({label:"Continuer →",action:"next",variant:"primary"}),e.isOptional&&t.push({label:"Passer",action:"skip",variant:"secondary"}),t}static validateStep(e,t){const r=this.GUIDED_STEPS[e];if(!r)return{isValid:!1,errors:["Étape introuvable"]};const s=[];return r.validationRules.forEach(n=>{const a=this.getFieldValue(t,n.field);switch(n.rule){case"required":(!a||a===""||a===null||a===void 0)&&s.push(n.message);break;case"numeric":a!=null&&a!==""&&isNaN(Number(a))&&s.push(n.message),n.minValue!==void 0&&Number(a)n.maxValue&&s.push(`${n.field} ne peut pas dépasser ${n.maxValue}`);break;case"date":a&&isNaN(Date.parse(a))&&s.push(n.message);break}}),{isValid:s.length===0,errors:s}}static getFieldValue(e,t){const r=t.split(".");let s=e;for(const n of r)if(s&&typeof s=="object"&&n in s)s=s[n];else return e.personal&&n in e.personal?e.personal[n]:e.cashflow&&n in e.cashflow?e.cashflow[n]:e.savings&&n in e.savings?e.savings[n]:e.retirement&&n in e.retirement?e.retirement[n]:void 0;return s}}L(vn,"GUIDED_STEPS",{welcome:{id:"welcome",title:"Bienvenue dans votre plan retraite",description:"Créons ensemble votre plan de retraite personnalisé en quelques étapes simples",estimatedTime:"1 minute",assistantMessage:"👋 Bonjour ! Je suis votre assistant financier personnel. En 7 étapes simples, nous allons créer votre plan de retraite sur mesure. Prêt à commencer ?",assistantAvatar:"🤖",actionRequired:"choice",currentProgress:0,totalSteps:7,stepNumber:1,nextSteps:["personal-profile"],isCompleted:!1,isOptional:!1,category:"profile",difficulty:"facile",requiredFields:[],validationRules:[]},"personal-profile":{id:"personal-profile",title:"Parlez-moi de vous",description:"Quelques informations de base pour personnaliser votre expérience",estimatedTime:"2 minutes",assistantMessage:"📝 Pour vous donner les meilleurs conseils, j'ai besoin de vous connaître un peu. Ces informations restent 100% confidentielles.",assistantAvatar:"📝",actionRequired:"input",currentProgress:14,totalSteps:7,stepNumber:2,nextSteps:["income-overview"],previousStep:"welcome",isCompleted:!1,isOptional:!1,category:"profile",difficulty:"facile",requiredFields:["prenom1","naissance1","province1"],validationRules:[{field:"prenom1",rule:"required",message:"Votre prénom est requis"},{field:"naissance1",rule:"date",message:"Date de naissance invalide"},{field:"province1",rule:"required",message:"Votre province est requise"}]},"income-overview":{id:"income-overview",title:"Vos revenus actuels",description:"Découvrons vos sources de revenus principales",estimatedTime:"3 minutes",assistantMessage:"💰 Maintenant, parlons de vos revenus. Pas d'inquiétude, nous procédons étape par étape !",assistantAvatar:"💰",actionRequired:"input",currentProgress:28,totalSteps:7,stepNumber:3,nextSteps:["expenses-overview"],previousStep:"personal-profile",isCompleted:!1,isOptional:!1,category:"income",difficulty:"facile",requiredFields:["salaire1"],validationRules:[{field:"salaire1",rule:"numeric",message:"Le salaire doit être un nombre",minValue:0}]},"expenses-overview":{id:"expenses-overview",title:"Vos dépenses mensuelles",description:"Estimons vos dépenses principales pour la retraite",estimatedTime:"3 minutes",assistantMessage:"🏠 Regardons maintenant vos dépenses. Cela nous aide à calculer vos besoins de retraite.",assistantAvatar:"🏠",actionRequired:"input",currentProgress:42,totalSteps:7,stepNumber:4,nextSteps:["savings-overview"],previousStep:"income-overview",isCompleted:!1,isOptional:!1,category:"expenses",difficulty:"facile",requiredFields:["logement","alimentation","transport"],validationRules:[{field:"logement",rule:"numeric",message:"Coût du logement requis",minValue:0},{field:"alimentation",rule:"numeric",message:"Coût alimentation requis",minValue:0}]},"savings-overview":{id:"savings-overview",title:"Vos épargnes actuelles",description:"REER, CELI et autres placements",estimatedTime:"2 minutes",assistantMessage:"🏦 Excellent ! Maintenant découvrons vos épargnes. Chaque dollar compte pour votre retraite.",assistantAvatar:"🏦",actionRequired:"input",currentProgress:56,totalSteps:7,stepNumber:5,nextSteps:["benefits-check"],previousStep:"expenses-overview",isCompleted:!1,isOptional:!1,category:"savings",difficulty:"facile",requiredFields:["reer1","celi1"],validationRules:[{field:"reer1",rule:"numeric",message:"Montant REER invalide",minValue:0},{field:"celi1",rule:"numeric",message:"Montant CELI invalide",minValue:0}]},"benefits-check":{id:"benefits-check",title:"Vos prestations gouvernementales",description:"RRQ, Sécurité de la Vieillesse et autres prestations",estimatedTime:"2 minutes",assistantMessage:"🍁 Presque terminé ! Vérifions vos droits aux prestations gouvernementales du Canada.",assistantAvatar:"🍁",actionRequired:"review",currentProgress:70,totalSteps:7,stepNumber:6,nextSteps:["final-summary"],previousStep:"savings-overview",isCompleted:!1,isOptional:!1,category:"benefits",difficulty:"moyen",requiredFields:[],validationRules:[]},"final-summary":{id:"final-summary",title:"Votre plan de retraite personnalisé",description:"Résumé complet avec recommandations et règle du 4%",estimatedTime:"5 minutes",assistantMessage:"🎉 Bravo ! Voici votre plan de retraite complet avec mes recommandations personnalisées.",assistantAvatar:"🎉",actionRequired:"review",currentProgress:100,totalSteps:7,stepNumber:7,nextSteps:[],previousStep:"benefits-check",isCompleted:!1,isOptional:!1,category:"summary",difficulty:"moyen",requiredFields:[],validationRules:[]}});var Ve={exports:{}};function An(c){throw new Error('Could not dynamically require "'+c+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ye={exports:{}};const En={},yn=Object.freeze(Object.defineProperty({__proto__:null,default:En},Symbol.toStringTag,{value:"Module"})),Cn=Ks(yn);var bn=Ye.exports,Fr;function z(){return Fr||(Fr=1,(function(c,e){(function(t,r){c.exports=r()})(bn,function(){var t=t||(function(r,s){var n;if(typeof window<"u"&&window.crypto&&(n=window.crypto),typeof self<"u"&&self.crypto&&(n=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(n=globalThis.crypto),!n&&typeof window<"u"&&window.msCrypto&&(n=window.msCrypto),!n&&typeof _t<"u"&&_t.crypto&&(n=_t.crypto),!n&&typeof An=="function")try{n=Cn}catch{}var a=function(){if(n){if(typeof n.getRandomValues=="function")try{return n.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof n.randomBytes=="function")try{return n.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},i=Object.create||(function(){function g(){}return function(h){var A;return g.prototype=h,A=new g,g.prototype=null,A}})(),l={},o=l.lib={},u=o.Base=(function(){return{extend:function(g){var h=i(this);return g&&h.mixIn(g),(!h.hasOwnProperty("init")||this.init===h.init)&&(h.init=function(){h.$super.init.apply(this,arguments)}),h.init.prototype=h,h.$super=this,h},create:function(){var g=this.extend();return g.init.apply(g,arguments),g},init:function(){},mixIn:function(g){for(var h in g)g.hasOwnProperty(h)&&(this[h]=g[h]);g.hasOwnProperty("toString")&&(this.toString=g.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),m=o.WordArray=u.extend({init:function(g,h){g=this.words=g||[],h!=s?this.sigBytes=h:this.sigBytes=g.length*4},toString:function(g){return(g||p).stringify(this)},concat:function(g){var h=this.words,A=g.words,y=this.sigBytes,C=g.sigBytes;if(this.clamp(),y%4)for(var S=0;S>>2]>>>24-S%4*8&255;h[y+S>>>2]|=F<<24-(y+S)%4*8}else for(var w=0;w>>2]=A[w>>>2];return this.sigBytes+=C,this},clamp:function(){var g=this.words,h=this.sigBytes;g[h>>>2]&=4294967295<<32-h%4*8,g.length=r.ceil(h/4)},clone:function(){var g=u.clone.call(this);return g.words=this.words.slice(0),g},random:function(g){for(var h=[],A=0;A>>2]>>>24-C%4*8&255;y.push((S>>>4).toString(16)),y.push((S&15).toString(16))}return y.join("")},parse:function(g){for(var h=g.length,A=[],y=0;y>>3]|=parseInt(g.substr(y,2),16)<<24-y%8*4;return new m.init(A,h/2)}},x=d.Latin1={stringify:function(g){for(var h=g.words,A=g.sigBytes,y=[],C=0;C>>2]>>>24-C%4*8&255;y.push(String.fromCharCode(S))}return y.join("")},parse:function(g){for(var h=g.length,A=[],y=0;y>>2]|=(g.charCodeAt(y)&255)<<24-y%4*8;return new m.init(A,h)}},E=d.Utf8={stringify:function(g){try{return decodeURIComponent(escape(x.stringify(g)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(g){return x.parse(unescape(encodeURIComponent(g)))}},v=o.BufferedBlockAlgorithm=u.extend({reset:function(){this._data=new m.init,this._nDataBytes=0},_append:function(g){typeof g=="string"&&(g=E.parse(g)),this._data.concat(g),this._nDataBytes+=g.sigBytes},_process:function(g){var h,A=this._data,y=A.words,C=A.sigBytes,S=this.blockSize,F=S*4,w=C/F;g?w=r.ceil(w):w=r.max((w|0)-this._minBufferSize,0);var b=w*S,R=r.min(b*4,C);if(b){for(var D=0;D>>2]|=l[m]<<24-m%4*8;a.call(this,u,o)}else a.apply(this,arguments)};i.prototype=n}})(),t.lib.WordArray})})(Qe)),Qe.exports}var Je={exports:{}},Dn=Je.exports,Ir;function Bn(){return Ir||(Ir=1,(function(c,e){(function(t,r){c.exports=r(z())})(Dn,function(t){return(function(){var r=t,s=r.lib,n=s.WordArray,a=r.enc;a.Utf16=a.Utf16BE={stringify:function(l){for(var o=l.words,u=l.sigBytes,m=[],d=0;d>>2]>>>16-d%4*8&65535;m.push(String.fromCharCode(p))}return m.join("")},parse:function(l){for(var o=l.length,u=[],m=0;m>>1]|=l.charCodeAt(m)<<16-m%2*16;return n.create(u,o*2)}},a.Utf16LE={stringify:function(l){for(var o=l.words,u=l.sigBytes,m=[],d=0;d>>2]>>>16-d%4*8&65535);m.push(String.fromCharCode(p))}return m.join("")},parse:function(l){for(var o=l.length,u=[],m=0;m>>1]|=i(l.charCodeAt(m)<<16-m%2*16);return n.create(u,o*2)}};function i(l){return l<<8&4278255360|l>>>8&16711935}})(),t.enc.Utf16})})(Je)),Je.exports}var Xe={exports:{}},In=Xe.exports,Tr;function Se(){return Tr||(Tr=1,(function(c,e){(function(t,r){c.exports=r(z())})(In,function(t){return(function(){var r=t,s=r.lib,n=s.WordArray,a=r.enc;a.Base64={stringify:function(l){var o=l.words,u=l.sigBytes,m=this._map;l.clamp();for(var d=[],p=0;p>>2]>>>24-p%4*8&255,E=o[p+1>>>2]>>>24-(p+1)%4*8&255,v=o[p+2>>>2]>>>24-(p+2)%4*8&255,f=x<<16|E<<8|v,g=0;g<4&&p+g*.75>>6*(3-g)&63));var h=m.charAt(64);if(h)for(;d.length%4;)d.push(h);return d.join("")},parse:function(l){var o=l.length,u=this._map,m=this._reverseMap;if(!m){m=this._reverseMap=[];for(var d=0;d>>6-p%4*2,v=x|E;m[d>>>2]|=v<<24-d%4*8,d++}return n.create(m,d)}})(),t.enc.Base64})})(Xe)),Xe.exports}var Ze={exports:{}},Tn=Ze.exports,Pr;function Pn(){return Pr||(Pr=1,(function(c,e){(function(t,r){c.exports=r(z())})(Tn,function(t){return(function(){var r=t,s=r.lib,n=s.WordArray,a=r.enc;a.Base64url={stringify:function(l,o){o===void 0&&(o=!0);var u=l.words,m=l.sigBytes,d=o?this._safe_map:this._map;l.clamp();for(var p=[],x=0;x>>2]>>>24-x%4*8&255,v=u[x+1>>>2]>>>24-(x+1)%4*8&255,f=u[x+2>>>2]>>>24-(x+2)%4*8&255,g=E<<16|v<<8|f,h=0;h<4&&x+h*.75>>6*(3-h)&63));var A=d.charAt(64);if(A)for(;p.length%4;)p.push(A);return p.join("")},parse:function(l,o){o===void 0&&(o=!0);var u=l.length,m=o?this._safe_map:this._map,d=this._reverseMap;if(!d){d=this._reverseMap=[];for(var p=0;p>>6-p%4*2,v=x|E;m[d>>>2]|=v<<24-d%4*8,d++}return n.create(m,d)}})(),t.enc.Base64url})})(Ze)),Ze.exports}var et={exports:{}},wn=et.exports,wr;function Re(){return wr||(wr=1,(function(c,e){(function(t,r){c.exports=r(z())})(wn,function(t){return(function(r){var s=t,n=s.lib,a=n.WordArray,i=n.Hasher,l=s.algo,o=[];(function(){for(var E=0;E<64;E++)o[E]=r.abs(r.sin(E+1))*4294967296|0})();var u=l.MD5=i.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(E,v){for(var f=0;f<16;f++){var g=v+f,h=E[g];E[g]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360}var A=this._hash.words,y=E[v+0],C=E[v+1],S=E[v+2],F=E[v+3],w=E[v+4],b=E[v+5],R=E[v+6],D=E[v+7],I=E[v+8],M=E[v+9],N=E[v+10],k=E[v+11],W=E[v+12],q=E[v+13],H=E[v+14],G=E[v+15],B=A[0],P=A[1],_=A[2],T=A[3];B=m(B,P,_,T,y,7,o[0]),T=m(T,B,P,_,C,12,o[1]),_=m(_,T,B,P,S,17,o[2]),P=m(P,_,T,B,F,22,o[3]),B=m(B,P,_,T,w,7,o[4]),T=m(T,B,P,_,b,12,o[5]),_=m(_,T,B,P,R,17,o[6]),P=m(P,_,T,B,D,22,o[7]),B=m(B,P,_,T,I,7,o[8]),T=m(T,B,P,_,M,12,o[9]),_=m(_,T,B,P,N,17,o[10]),P=m(P,_,T,B,k,22,o[11]),B=m(B,P,_,T,W,7,o[12]),T=m(T,B,P,_,q,12,o[13]),_=m(_,T,B,P,H,17,o[14]),P=m(P,_,T,B,G,22,o[15]),B=d(B,P,_,T,C,5,o[16]),T=d(T,B,P,_,R,9,o[17]),_=d(_,T,B,P,k,14,o[18]),P=d(P,_,T,B,y,20,o[19]),B=d(B,P,_,T,b,5,o[20]),T=d(T,B,P,_,N,9,o[21]),_=d(_,T,B,P,G,14,o[22]),P=d(P,_,T,B,w,20,o[23]),B=d(B,P,_,T,M,5,o[24]),T=d(T,B,P,_,H,9,o[25]),_=d(_,T,B,P,F,14,o[26]),P=d(P,_,T,B,I,20,o[27]),B=d(B,P,_,T,q,5,o[28]),T=d(T,B,P,_,S,9,o[29]),_=d(_,T,B,P,D,14,o[30]),P=d(P,_,T,B,W,20,o[31]),B=p(B,P,_,T,b,4,o[32]),T=p(T,B,P,_,I,11,o[33]),_=p(_,T,B,P,k,16,o[34]),P=p(P,_,T,B,H,23,o[35]),B=p(B,P,_,T,C,4,o[36]),T=p(T,B,P,_,w,11,o[37]),_=p(_,T,B,P,D,16,o[38]),P=p(P,_,T,B,N,23,o[39]),B=p(B,P,_,T,q,4,o[40]),T=p(T,B,P,_,y,11,o[41]),_=p(_,T,B,P,F,16,o[42]),P=p(P,_,T,B,R,23,o[43]),B=p(B,P,_,T,M,4,o[44]),T=p(T,B,P,_,W,11,o[45]),_=p(_,T,B,P,G,16,o[46]),P=p(P,_,T,B,S,23,o[47]),B=x(B,P,_,T,y,6,o[48]),T=x(T,B,P,_,D,10,o[49]),_=x(_,T,B,P,H,15,o[50]),P=x(P,_,T,B,b,21,o[51]),B=x(B,P,_,T,W,6,o[52]),T=x(T,B,P,_,F,10,o[53]),_=x(_,T,B,P,N,15,o[54]),P=x(P,_,T,B,C,21,o[55]),B=x(B,P,_,T,I,6,o[56]),T=x(T,B,P,_,G,10,o[57]),_=x(_,T,B,P,R,15,o[58]),P=x(P,_,T,B,q,21,o[59]),B=x(B,P,_,T,w,6,o[60]),T=x(T,B,P,_,k,10,o[61]),_=x(_,T,B,P,S,15,o[62]),P=x(P,_,T,B,M,21,o[63]),A[0]=A[0]+B|0,A[1]=A[1]+P|0,A[2]=A[2]+_|0,A[3]=A[3]+T|0},_doFinalize:function(){var E=this._data,v=E.words,f=this._nDataBytes*8,g=E.sigBytes*8;v[g>>>5]|=128<<24-g%32;var h=r.floor(f/4294967296),A=f;v[(g+64>>>9<<4)+15]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,v[(g+64>>>9<<4)+14]=(A<<8|A>>>24)&16711935|(A<<24|A>>>8)&4278255360,E.sigBytes=(v.length+1)*4,this._process();for(var y=this._hash,C=y.words,S=0;S<4;S++){var F=C[S];C[S]=(F<<8|F>>>24)&16711935|(F<<24|F>>>8)&4278255360}return y},clone:function(){var E=i.clone.call(this);return E._hash=this._hash.clone(),E}});function m(E,v,f,g,h,A,y){var C=E+(v&f|~v&g)+h+y;return(C<>>32-A)+v}function d(E,v,f,g,h,A,y){var C=E+(v&g|f&~g)+h+y;return(C<>>32-A)+v}function p(E,v,f,g,h,A,y){var C=E+(v^f^g)+h+y;return(C<>>32-A)+v}function x(E,v,f,g,h,A,y){var C=E+(f^(v|~g))+h+y;return(C<>>32-A)+v}s.MD5=i._createHelper(u),s.HmacMD5=i._createHmacHelper(u)})(Math),t.MD5})})(et)),et.exports}var tt={exports:{}},_n=tt.exports,_r;function Ss(){return _r||(_r=1,(function(c,e){(function(t,r){c.exports=r(z())})(_n,function(t){return(function(){var r=t,s=r.lib,n=s.WordArray,a=s.Hasher,i=r.algo,l=[],o=i.SHA1=a.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(u,m){for(var d=this._hash.words,p=d[0],x=d[1],E=d[2],v=d[3],f=d[4],g=0;g<80;g++){if(g<16)l[g]=u[m+g]|0;else{var h=l[g-3]^l[g-8]^l[g-14]^l[g-16];l[g]=h<<1|h>>>31}var A=(p<<5|p>>>27)+f+l[g];g<20?A+=(x&E|~x&v)+1518500249:g<40?A+=(x^E^v)+1859775393:g<60?A+=(x&E|x&v|E&v)-1894007588:A+=(x^E^v)-899497514,f=v,v=E,E=x<<30|x>>>2,x=p,p=A}d[0]=d[0]+p|0,d[1]=d[1]+x|0,d[2]=d[2]+E|0,d[3]=d[3]+v|0,d[4]=d[4]+f|0},_doFinalize:function(){var u=this._data,m=u.words,d=this._nDataBytes*8,p=u.sigBytes*8;return m[p>>>5]|=128<<24-p%32,m[(p+64>>>9<<4)+14]=Math.floor(d/4294967296),m[(p+64>>>9<<4)+15]=d,u.sigBytes=m.length*4,this._process(),this._hash},clone:function(){var u=a.clone.call(this);return u._hash=this._hash.clone(),u}});r.SHA1=a._createHelper(o),r.HmacSHA1=a._createHmacHelper(o)})(),t.SHA1})})(tt)),tt.exports}var rt={exports:{}},Mn=rt.exports,Mr;function Kt(){return Mr||(Mr=1,(function(c,e){(function(t,r){c.exports=r(z())})(Mn,function(t){return(function(r){var s=t,n=s.lib,a=n.WordArray,i=n.Hasher,l=s.algo,o=[],u=[];(function(){function p(f){for(var g=r.sqrt(f),h=2;h<=g;h++)if(!(f%h))return!1;return!0}function x(f){return(f-(f|0))*4294967296|0}for(var E=2,v=0;v<64;)p(E)&&(v<8&&(o[v]=x(r.pow(E,1/2))),u[v]=x(r.pow(E,1/3)),v++),E++})();var m=[],d=l.SHA256=i.extend({_doReset:function(){this._hash=new a.init(o.slice(0))},_doProcessBlock:function(p,x){for(var E=this._hash.words,v=E[0],f=E[1],g=E[2],h=E[3],A=E[4],y=E[5],C=E[6],S=E[7],F=0;F<64;F++){if(F<16)m[F]=p[x+F]|0;else{var w=m[F-15],b=(w<<25|w>>>7)^(w<<14|w>>>18)^w>>>3,R=m[F-2],D=(R<<15|R>>>17)^(R<<13|R>>>19)^R>>>10;m[F]=b+m[F-7]+D+m[F-16]}var I=A&y^~A&C,M=v&f^v&g^f&g,N=(v<<30|v>>>2)^(v<<19|v>>>13)^(v<<10|v>>>22),k=(A<<26|A>>>6)^(A<<21|A>>>11)^(A<<7|A>>>25),W=S+k+I+u[F]+m[F],q=N+M;S=C,C=y,y=A,A=h+W|0,h=g,g=f,f=v,v=W+q|0}E[0]=E[0]+v|0,E[1]=E[1]+f|0,E[2]=E[2]+g|0,E[3]=E[3]+h|0,E[4]=E[4]+A|0,E[5]=E[5]+y|0,E[6]=E[6]+C|0,E[7]=E[7]+S|0},_doFinalize:function(){var p=this._data,x=p.words,E=this._nDataBytes*8,v=p.sigBytes*8;return x[v>>>5]|=128<<24-v%32,x[(v+64>>>9<<4)+14]=r.floor(E/4294967296),x[(v+64>>>9<<4)+15]=E,p.sigBytes=x.length*4,this._process(),this._hash},clone:function(){var p=i.clone.call(this);return p._hash=this._hash.clone(),p}});s.SHA256=i._createHelper(d),s.HmacSHA256=i._createHmacHelper(d)})(Math),t.SHA256})})(rt)),rt.exports}var st={exports:{}},Nn=st.exports,Nr;function kn(){return Nr||(Nr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Kt())})(Nn,function(t){return(function(){var r=t,s=r.lib,n=s.WordArray,a=r.algo,i=a.SHA256,l=a.SHA224=i.extend({_doReset:function(){this._hash=new n.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=i._doFinalize.call(this);return o.sigBytes-=4,o}});r.SHA224=i._createHelper(l),r.HmacSHA224=i._createHmacHelper(l)})(),t.SHA224})})(st)),st.exports}var nt={exports:{}},On=nt.exports,kr;function Rs(){return kr||(kr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Tt())})(On,function(t){return(function(){var r=t,s=r.lib,n=s.Hasher,a=r.x64,i=a.Word,l=a.WordArray,o=r.algo;function u(){return i.create.apply(i,arguments)}var m=[u(1116352408,3609767458),u(1899447441,602891725),u(3049323471,3964484399),u(3921009573,2173295548),u(961987163,4081628472),u(1508970993,3053834265),u(2453635748,2937671579),u(2870763221,3664609560),u(3624381080,2734883394),u(310598401,1164996542),u(607225278,1323610764),u(1426881987,3590304994),u(1925078388,4068182383),u(2162078206,991336113),u(2614888103,633803317),u(3248222580,3479774868),u(3835390401,2666613458),u(4022224774,944711139),u(264347078,2341262773),u(604807628,2007800933),u(770255983,1495990901),u(1249150122,1856431235),u(1555081692,3175218132),u(1996064986,2198950837),u(2554220882,3999719339),u(2821834349,766784016),u(2952996808,2566594879),u(3210313671,3203337956),u(3336571891,1034457026),u(3584528711,2466948901),u(113926993,3758326383),u(338241895,168717936),u(666307205,1188179964),u(773529912,1546045734),u(1294757372,1522805485),u(1396182291,2643833823),u(1695183700,2343527390),u(1986661051,1014477480),u(2177026350,1206759142),u(2456956037,344077627),u(2730485921,1290863460),u(2820302411,3158454273),u(3259730800,3505952657),u(3345764771,106217008),u(3516065817,3606008344),u(3600352804,1432725776),u(4094571909,1467031594),u(275423344,851169720),u(430227734,3100823752),u(506948616,1363258195),u(659060556,3750685593),u(883997877,3785050280),u(958139571,3318307427),u(1322822218,3812723403),u(1537002063,2003034995),u(1747873779,3602036899),u(1955562222,1575990012),u(2024104815,1125592928),u(2227730452,2716904306),u(2361852424,442776044),u(2428436474,593698344),u(2756734187,3733110249),u(3204031479,2999351573),u(3329325298,3815920427),u(3391569614,3928383900),u(3515267271,566280711),u(3940187606,3454069534),u(4118630271,4000239992),u(116418474,1914138554),u(174292421,2731055270),u(289380356,3203993006),u(460393269,320620315),u(685471733,587496836),u(852142971,1086792851),u(1017036298,365543100),u(1126000580,2618297676),u(1288033470,3409855158),u(1501505948,4234509866),u(1607167915,987167468),u(1816402316,1246189591)],d=[];(function(){for(var x=0;x<80;x++)d[x]=u()})();var p=o.SHA512=n.extend({_doReset:function(){this._hash=new l.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(x,E){for(var v=this._hash.words,f=v[0],g=v[1],h=v[2],A=v[3],y=v[4],C=v[5],S=v[6],F=v[7],w=f.high,b=f.low,R=g.high,D=g.low,I=h.high,M=h.low,N=A.high,k=A.low,W=y.high,q=y.low,H=C.high,G=C.low,B=S.high,P=S.low,_=F.high,T=F.low,j=w,U=b,X=R,O=D,we=I,Fe=M,Pt=N,_e=k,se=W,Z=q,qe=H,Me=G,Ge=B,Ne=P,wt=_,ke=T,ne=0;ne<80;ne++){var te,xe,He=d[ne];if(ne<16)xe=He.high=x[E+ne*2]|0,te=He.low=x[E+ne*2+1]|0;else{var Zt=d[ne-15],De=Zt.high,Oe=Zt.low,_s=(De>>>1|Oe<<31)^(De>>>8|Oe<<24)^De>>>7,er=(Oe>>>1|De<<31)^(Oe>>>8|De<<24)^(Oe>>>7|De<<25),tr=d[ne-2],Be=tr.high,ze=tr.low,Ms=(Be>>>19|ze<<13)^(Be<<3|ze>>>29)^Be>>>6,rr=(ze>>>19|Be<<13)^(ze<<3|Be>>>29)^(ze>>>6|Be<<26),sr=d[ne-7],Ns=sr.high,ks=sr.low,nr=d[ne-16],Os=nr.high,ar=nr.low;te=er+ks,xe=_s+Ns+(te>>>0>>0?1:0),te=te+rr,xe=xe+Ms+(te>>>0>>0?1:0),te=te+ar,xe=xe+Os+(te>>>0>>0?1:0),He.high=xe,He.low=te}var zs=se&qe^~se&Ge,ir=Z&Me^~Z&Ne,$s=j&X^j&we^X&we,Ls=U&O^U&Fe^O&Fe,qs=(j>>>28|U<<4)^(j<<30|U>>>2)^(j<<25|U>>>7),or=(U>>>28|j<<4)^(U<<30|j>>>2)^(U<<25|j>>>7),Gs=(se>>>14|Z<<18)^(se>>>18|Z<<14)^(se<<23|Z>>>9),Hs=(Z>>>14|se<<18)^(Z>>>18|se<<14)^(Z<<23|se>>>9),cr=m[ne],Us=cr.high,lr=cr.low,ee=ke+Hs,me=wt+Gs+(ee>>>0>>0?1:0),ee=ee+ir,me=me+zs+(ee>>>0>>0?1:0),ee=ee+lr,me=me+Us+(ee>>>0>>0?1:0),ee=ee+te,me=me+xe+(ee>>>0>>0?1:0),ur=or+Ls,Ws=qs+$s+(ur>>>0>>0?1:0);wt=Ge,ke=Ne,Ge=qe,Ne=Me,qe=se,Me=Z,Z=_e+ee|0,se=Pt+me+(Z>>>0<_e>>>0?1:0)|0,Pt=we,_e=Fe,we=X,Fe=O,X=j,O=U,U=ee+ur|0,j=me+Ws+(U>>>0>>0?1:0)|0}b=f.low=b+U,f.high=w+j+(b>>>0>>0?1:0),D=g.low=D+O,g.high=R+X+(D>>>0>>0?1:0),M=h.low=M+Fe,h.high=I+we+(M>>>0>>0?1:0),k=A.low=k+_e,A.high=N+Pt+(k>>>0<_e>>>0?1:0),q=y.low=q+Z,y.high=W+se+(q>>>0>>0?1:0),G=C.low=G+Me,C.high=H+qe+(G>>>0>>0?1:0),P=S.low=P+Ne,S.high=B+Ge+(P>>>0>>0?1:0),T=F.low=T+ke,F.high=_+wt+(T>>>0>>0?1:0)},_doFinalize:function(){var x=this._data,E=x.words,v=this._nDataBytes*8,f=x.sigBytes*8;E[f>>>5]|=128<<24-f%32,E[(f+128>>>10<<5)+30]=Math.floor(v/4294967296),E[(f+128>>>10<<5)+31]=v,x.sigBytes=E.length*4,this._process();var g=this._hash.toX32();return g},clone:function(){var x=n.clone.call(this);return x._hash=this._hash.clone(),x},blockSize:1024/32});r.SHA512=n._createHelper(p),r.HmacSHA512=n._createHmacHelper(p)})(),t.SHA512})})(nt)),nt.exports}var at={exports:{}},zn=at.exports,Or;function $n(){return Or||(Or=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Tt(),Rs())})(zn,function(t){return(function(){var r=t,s=r.x64,n=s.Word,a=s.WordArray,i=r.algo,l=i.SHA512,o=i.SHA384=l.extend({_doReset:function(){this._hash=new a.init([new n.init(3418070365,3238371032),new n.init(1654270250,914150663),new n.init(2438529370,812702999),new n.init(355462360,4144912697),new n.init(1731405415,4290775857),new n.init(2394180231,1750603025),new n.init(3675008525,1694076839),new n.init(1203062813,3204075428)])},_doFinalize:function(){var u=l._doFinalize.call(this);return u.sigBytes-=16,u}});r.SHA384=l._createHelper(o),r.HmacSHA384=l._createHmacHelper(o)})(),t.SHA384})})(at)),at.exports}var it={exports:{}},Ln=it.exports,zr;function qn(){return zr||(zr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Tt())})(Ln,function(t){return(function(r){var s=t,n=s.lib,a=n.WordArray,i=n.Hasher,l=s.x64,o=l.Word,u=s.algo,m=[],d=[],p=[];(function(){for(var v=1,f=0,g=0;g<24;g++){m[v+5*f]=(g+1)*(g+2)/2%64;var h=f%5,A=(2*v+3*f)%5;v=h,f=A}for(var v=0;v<5;v++)for(var f=0;f<5;f++)d[v+5*f]=f+(2*v+3*f)%5*5;for(var y=1,C=0;C<24;C++){for(var S=0,F=0,w=0;w<7;w++){if(y&1){var b=(1<>>24)&16711935|(y<<24|y>>>8)&4278255360,C=(C<<8|C>>>24)&16711935|(C<<24|C>>>8)&4278255360;var S=g[A];S.high^=C,S.low^=y}for(var F=0;F<24;F++){for(var w=0;w<5;w++){for(var b=0,R=0,D=0;D<5;D++){var S=g[w+5*D];b^=S.high,R^=S.low}var I=x[w];I.high=b,I.low=R}for(var w=0;w<5;w++)for(var M=x[(w+4)%5],N=x[(w+1)%5],k=N.high,W=N.low,b=M.high^(k<<1|W>>>31),R=M.low^(W<<1|k>>>31),D=0;D<5;D++){var S=g[w+5*D];S.high^=b,S.low^=R}for(var q=1;q<25;q++){var b,R,S=g[q],H=S.high,G=S.low,B=m[q];B<32?(b=H<>>32-B,R=G<>>32-B):(b=G<>>64-B,R=H<>>64-B);var P=x[d[q]];P.high=b,P.low=R}var _=x[0],T=g[0];_.high=T.high,_.low=T.low;for(var w=0;w<5;w++)for(var D=0;D<5;D++){var q=w+5*D,S=g[q],j=x[q],U=x[(w+1)%5+5*D],X=x[(w+2)%5+5*D];S.high=j.high^~U.high&X.high,S.low=j.low^~U.low&X.low}var S=g[0],O=p[F];S.high^=O.high,S.low^=O.low}},_doFinalize:function(){var v=this._data,f=v.words;this._nDataBytes*8;var g=v.sigBytes*8,h=this.blockSize*32;f[g>>>5]|=1<<24-g%32,f[(r.ceil((g+1)/h)*h>>>5)-1]|=128,v.sigBytes=f.length*4,this._process();for(var A=this._state,y=this.cfg.outputLength/8,C=y/8,S=[],F=0;F>>24)&16711935|(b<<24|b>>>8)&4278255360,R=(R<<8|R>>>24)&16711935|(R<<24|R>>>8)&4278255360,S.push(R),S.push(b)}return new a.init(S,y)},clone:function(){for(var v=i.clone.call(this),f=v._state=this._state.slice(0),g=0;g<25;g++)f[g]=f[g].clone();return v}});s.SHA3=i._createHelper(E),s.HmacSHA3=i._createHmacHelper(E)})(Math),t.SHA3})})(it)),it.exports}var ot={exports:{}},Gn=ot.exports,$r;function Hn(){return $r||($r=1,(function(c,e){(function(t,r){c.exports=r(z())})(Gn,function(t){/** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */return(function(r){var s=t,n=s.lib,a=n.WordArray,i=n.Hasher,l=s.algo,o=a.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),u=a.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),m=a.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=a.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=a.create([0,1518500249,1859775393,2400959708,2840853838]),x=a.create([1352829926,1548603684,1836072691,2053994217,0]),E=l.RIPEMD160=i.extend({_doReset:function(){this._hash=a.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(C,S){for(var F=0;F<16;F++){var w=S+F,b=C[w];C[w]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360}var R=this._hash.words,D=p.words,I=x.words,M=o.words,N=u.words,k=m.words,W=d.words,q,H,G,B,P,_,T,j,U,X;_=q=R[0],T=H=R[1],j=G=R[2],U=B=R[3],X=P=R[4];for(var O,F=0;F<80;F+=1)O=q+C[S+M[F]]|0,F<16?O+=v(H,G,B)+D[0]:F<32?O+=f(H,G,B)+D[1]:F<48?O+=g(H,G,B)+D[2]:F<64?O+=h(H,G,B)+D[3]:O+=A(H,G,B)+D[4],O=O|0,O=y(O,k[F]),O=O+P|0,q=P,P=B,B=y(G,10),G=H,H=O,O=_+C[S+N[F]]|0,F<16?O+=A(T,j,U)+I[0]:F<32?O+=h(T,j,U)+I[1]:F<48?O+=g(T,j,U)+I[2]:F<64?O+=f(T,j,U)+I[3]:O+=v(T,j,U)+I[4],O=O|0,O=y(O,W[F]),O=O+X|0,_=X,X=U,U=y(j,10),j=T,T=O;O=R[1]+G+U|0,R[1]=R[2]+B+X|0,R[2]=R[3]+P+_|0,R[3]=R[4]+q+T|0,R[4]=R[0]+H+j|0,R[0]=O},_doFinalize:function(){var C=this._data,S=C.words,F=this._nDataBytes*8,w=C.sigBytes*8;S[w>>>5]|=128<<24-w%32,S[(w+64>>>9<<4)+14]=(F<<8|F>>>24)&16711935|(F<<24|F>>>8)&4278255360,C.sigBytes=(S.length+1)*4,this._process();for(var b=this._hash,R=b.words,D=0;D<5;D++){var I=R[D];R[D]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}return b},clone:function(){var C=i.clone.call(this);return C._hash=this._hash.clone(),C}});function v(C,S,F){return C^S^F}function f(C,S,F){return C&S|~C&F}function g(C,S,F){return(C|~S)^F}function h(C,S,F){return C&F|S&~F}function A(C,S,F){return C^(S|~F)}function y(C,S){return C<>>32-S}s.RIPEMD160=i._createHelper(E),s.HmacRIPEMD160=i._createHmacHelper(E)})(),t.RIPEMD160})})(ot)),ot.exports}var ct={exports:{}},Un=ct.exports,Lr;function Qt(){return Lr||(Lr=1,(function(c,e){(function(t,r){c.exports=r(z())})(Un,function(t){(function(){var r=t,s=r.lib,n=s.Base,a=r.enc,i=a.Utf8,l=r.algo;l.HMAC=n.extend({init:function(o,u){o=this._hasher=new o.init,typeof u=="string"&&(u=i.parse(u));var m=o.blockSize,d=m*4;u.sigBytes>d&&(u=o.finalize(u)),u.clamp();for(var p=this._oKey=u.clone(),x=this._iKey=u.clone(),E=p.words,v=x.words,f=0;f>>2]&255;b.sigBytes-=R}};n.BlockCipher=p.extend({cfg:p.cfg.extend({mode:v,padding:g}),reset:function(){var b;p.reset.call(this);var R=this.cfg,D=R.iv,I=R.mode;this._xformMode==this._ENC_XFORM_MODE?b=I.createEncryptor:(b=I.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==b?this._mode.init(this,D&&D.words):(this._mode=b.call(I,this,D&&D.words),this._mode.__creator=b)},_doProcessBlock:function(b,R){this._mode.processBlock(b,R)},_doFinalize:function(){var b,R=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(R.pad(this._data,this.blockSize),b=this._process(!0)):(b=this._process(!0),R.unpad(b)),b},blockSize:128/32});var h=n.CipherParams=a.extend({init:function(b){this.mixIn(b)},toString:function(b){return(b||this.formatter).stringify(this)}}),A=s.format={},y=A.OpenSSL={stringify:function(b){var R,D=b.ciphertext,I=b.salt;return I?R=i.create([1398893684,1701076831]).concat(I).concat(D):R=D,R.toString(u)},parse:function(b){var R,D=u.parse(b),I=D.words;return I[0]==1398893684&&I[1]==1701076831&&(R=i.create(I.slice(2,4)),I.splice(0,4),D.sigBytes-=16),h.create({ciphertext:D,salt:R})}},C=n.SerializableCipher=a.extend({cfg:a.extend({format:y}),encrypt:function(b,R,D,I){I=this.cfg.extend(I);var M=b.createEncryptor(D,I),N=M.finalize(R),k=M.cfg;return h.create({ciphertext:N,key:D,iv:k.iv,algorithm:b,mode:k.mode,padding:k.padding,blockSize:b.blockSize,formatter:I.format})},decrypt:function(b,R,D,I){I=this.cfg.extend(I),R=this._parse(R,I.format);var M=b.createDecryptor(D,I).finalize(R.ciphertext);return M},_parse:function(b,R){return typeof b=="string"?R.parse(b,this):b}}),S=s.kdf={},F=S.OpenSSL={execute:function(b,R,D,I,M){if(I||(I=i.random(64/8)),M)var N=d.create({keySize:R+D,hasher:M}).compute(b,I);else var N=d.create({keySize:R+D}).compute(b,I);var k=i.create(N.words.slice(R),D*4);return N.sigBytes=R*4,h.create({key:N,iv:k,salt:I})}},w=n.PasswordBasedCipher=C.extend({cfg:C.cfg.extend({kdf:F}),encrypt:function(b,R,D,I){I=this.cfg.extend(I);var M=I.kdf.execute(D,b.keySize,b.ivSize,I.salt,I.hasher);I.iv=M.iv;var N=C.encrypt.call(this,b,R,M.key,I);return N.mixIn(M),N},decrypt:function(b,R,D,I){I=this.cfg.extend(I),R=this._parse(R,I.format);var M=I.kdf.execute(D,b.keySize,b.ivSize,R.salt,I.hasher);I.iv=M.iv;var N=C.decrypt.call(this,b,R,M.key,I);return N}})})()})})(dt)),dt.exports}var pt={exports:{}},Kn=pt.exports,Ur;function Qn(){return Ur||(Ur=1,(function(c,e){(function(t,r,s){c.exports=r(z(),K())})(Kn,function(t){return t.mode.CFB=(function(){var r=t.lib.BlockCipherMode.extend();r.Encryptor=r.extend({processBlock:function(n,a){var i=this._cipher,l=i.blockSize;s.call(this,n,a,l,i),this._prevBlock=n.slice(a,a+l)}}),r.Decryptor=r.extend({processBlock:function(n,a){var i=this._cipher,l=i.blockSize,o=n.slice(a,a+l);s.call(this,n,a,l,i),this._prevBlock=o}});function s(n,a,i,l){var o,u=this._iv;u?(o=u.slice(0),this._iv=void 0):o=this._prevBlock,l.encryptBlock(o,0);for(var m=0;m>24&255)===255){var l=i>>16&255,o=i>>8&255,u=i&255;l===255?(l=0,o===255?(o=0,u===255?u=0:++u):++o):++l,i=0,i+=l<<16,i+=o<<8,i+=u}else i+=1<<24;return i}function n(i){return(i[0]=s(i[0]))===0&&(i[1]=s(i[1])),i}var a=r.Encryptor=r.extend({processBlock:function(i,l){var o=this._cipher,u=o.blockSize,m=this._iv,d=this._counter;m&&(d=this._counter=m.slice(0),this._iv=void 0),n(d);var p=d.slice(0);o.encryptBlock(p,0);for(var x=0;x>>2]|=i<<24-l%4*8,r.sigBytes+=i},unpad:function(r){var s=r.words[r.sigBytes-1>>>2]&255;r.sigBytes-=s}},t.pad.Ansix923})})(gt)),gt.exports}var vt={exports:{}},oa=vt.exports,Qr;function ca(){return Qr||(Qr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),K())})(oa,function(t){return t.pad.Iso10126={pad:function(r,s){var n=s*4,a=n-r.sigBytes%n;r.concat(t.lib.WordArray.random(a-1)).concat(t.lib.WordArray.create([a<<24],1))},unpad:function(r){var s=r.words[r.sigBytes-1>>>2]&255;r.sigBytes-=s}},t.pad.Iso10126})})(vt)),vt.exports}var At={exports:{}},la=At.exports,Jr;function ua(){return Jr||(Jr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),K())})(la,function(t){return t.pad.Iso97971={pad:function(r,s){r.concat(t.lib.WordArray.create([2147483648],1)),t.pad.ZeroPadding.pad(r,s)},unpad:function(r){t.pad.ZeroPadding.unpad(r),r.sigBytes--}},t.pad.Iso97971})})(At)),At.exports}var Et={exports:{}},da=Et.exports,Xr;function pa(){return Xr||(Xr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),K())})(da,function(t){return t.pad.ZeroPadding={pad:function(r,s){var n=s*4;r.clamp(),r.sigBytes+=n-(r.sigBytes%n||n)},unpad:function(r){for(var s=r.words,n=r.sigBytes-1,n=r.sigBytes-1;n>=0;n--)if(s[n>>>2]>>>24-n%4*8&255){r.sigBytes=n+1;break}}},t.pad.ZeroPadding})})(Et)),Et.exports}var yt={exports:{}},xa=yt.exports,Zr;function ma(){return Zr||(Zr=1,(function(c,e){(function(t,r,s){c.exports=r(z(),K())})(xa,function(t){return t.pad.NoPadding={pad:function(){},unpad:function(){}},t.pad.NoPadding})})(yt)),yt.exports}var Ct={exports:{}},fa=Ct.exports,es;function ha(){return es||(es=1,(function(c,e){(function(t,r,s){c.exports=r(z(),K())})(fa,function(t){return(function(r){var s=t,n=s.lib,a=n.CipherParams,i=s.enc,l=i.Hex,o=s.format;o.Hex={stringify:function(u){return u.ciphertext.toString(l)},parse:function(u){var m=l.parse(u);return a.create({ciphertext:m})}}})(),t.format.Hex})})(Ct)),Ct.exports}var bt={exports:{}},ga=bt.exports,ts;function va(){return ts||(ts=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Se(),Re(),fe(),K())})(ga,function(t){return(function(){var r=t,s=r.lib,n=s.BlockCipher,a=r.algo,i=[],l=[],o=[],u=[],m=[],d=[],p=[],x=[],E=[],v=[];(function(){for(var h=[],A=0;A<256;A++)A<128?h[A]=A<<1:h[A]=A<<1^283;for(var y=0,C=0,A=0;A<256;A++){var S=C^C<<1^C<<2^C<<3^C<<4;S=S>>>8^S&255^99,i[y]=S,l[S]=y;var F=h[y],w=h[F],b=h[w],R=h[S]*257^S*16843008;o[y]=R<<24|R>>>8,u[y]=R<<16|R>>>16,m[y]=R<<8|R>>>24,d[y]=R;var R=b*16843009^w*65537^F*257^y*16843008;p[S]=R<<24|R>>>8,x[S]=R<<16|R>>>16,E[S]=R<<8|R>>>24,v[S]=R,y?(y=F^h[h[h[b^F]]],C^=h[h[C]]):y=C=1}})();var f=[0,1,2,4,8,16,32,64,128,27,54],g=a.AES=n.extend({_doReset:function(){var h;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var A=this._keyPriorReset=this._key,y=A.words,C=A.sigBytes/4,S=this._nRounds=C+6,F=(S+1)*4,w=this._keySchedule=[],b=0;b6&&b%C==4&&(h=i[h>>>24]<<24|i[h>>>16&255]<<16|i[h>>>8&255]<<8|i[h&255]):(h=h<<8|h>>>24,h=i[h>>>24]<<24|i[h>>>16&255]<<16|i[h>>>8&255]<<8|i[h&255],h^=f[b/C|0]<<24),w[b]=w[b-C]^h);for(var R=this._invKeySchedule=[],D=0;D>>24]]^x[i[h>>>16&255]]^E[i[h>>>8&255]]^v[i[h&255]]}}},encryptBlock:function(h,A){this._doCryptBlock(h,A,this._keySchedule,o,u,m,d,i)},decryptBlock:function(h,A){var y=h[A+1];h[A+1]=h[A+3],h[A+3]=y,this._doCryptBlock(h,A,this._invKeySchedule,p,x,E,v,l);var y=h[A+1];h[A+1]=h[A+3],h[A+3]=y},_doCryptBlock:function(h,A,y,C,S,F,w,b){for(var R=this._nRounds,D=h[A]^y[0],I=h[A+1]^y[1],M=h[A+2]^y[2],N=h[A+3]^y[3],k=4,W=1;W>>24]^S[I>>>16&255]^F[M>>>8&255]^w[N&255]^y[k++],H=C[I>>>24]^S[M>>>16&255]^F[N>>>8&255]^w[D&255]^y[k++],G=C[M>>>24]^S[N>>>16&255]^F[D>>>8&255]^w[I&255]^y[k++],B=C[N>>>24]^S[D>>>16&255]^F[I>>>8&255]^w[M&255]^y[k++];D=q,I=H,M=G,N=B}var q=(b[D>>>24]<<24|b[I>>>16&255]<<16|b[M>>>8&255]<<8|b[N&255])^y[k++],H=(b[I>>>24]<<24|b[M>>>16&255]<<16|b[N>>>8&255]<<8|b[D&255])^y[k++],G=(b[M>>>24]<<24|b[N>>>16&255]<<16|b[D>>>8&255]<<8|b[I&255])^y[k++],B=(b[N>>>24]<<24|b[D>>>16&255]<<16|b[I>>>8&255]<<8|b[M&255])^y[k++];h[A]=q,h[A+1]=H,h[A+2]=G,h[A+3]=B},keySize:256/32});r.AES=n._createHelper(g)})(),t.AES})})(bt)),bt.exports}var St={exports:{}},Aa=St.exports,rs;function Ea(){return rs||(rs=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Se(),Re(),fe(),K())})(Aa,function(t){return(function(){var r=t,s=r.lib,n=s.WordArray,a=s.BlockCipher,i=r.algo,l=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],u=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],m=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],d=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=i.DES=a.extend({_doReset:function(){for(var f=this._key,g=f.words,h=[],A=0;A<56;A++){var y=l[A]-1;h[A]=g[y>>>5]>>>31-y%32&1}for(var C=this._subKeys=[],S=0;S<16;S++){for(var F=C[S]=[],w=u[S],A=0;A<24;A++)F[A/6|0]|=h[(o[A]-1+w)%28]<<31-A%6,F[4+(A/6|0)]|=h[28+(o[A+24]-1+w)%28]<<31-A%6;F[0]=F[0]<<1|F[0]>>>31;for(var A=1;A<7;A++)F[A]=F[A]>>>(A-1)*4+3;F[7]=F[7]<<5|F[7]>>>27}for(var b=this._invSubKeys=[],A=0;A<16;A++)b[A]=C[15-A]},encryptBlock:function(f,g){this._doCryptBlock(f,g,this._subKeys)},decryptBlock:function(f,g){this._doCryptBlock(f,g,this._invSubKeys)},_doCryptBlock:function(f,g,h){this._lBlock=f[g],this._rBlock=f[g+1],x.call(this,4,252645135),x.call(this,16,65535),E.call(this,2,858993459),E.call(this,8,16711935),x.call(this,1,1431655765);for(var A=0;A<16;A++){for(var y=h[A],C=this._lBlock,S=this._rBlock,F=0,w=0;w<8;w++)F|=m[w][((S^y[w])&d[w])>>>0];this._lBlock=S,this._rBlock=C^F}var b=this._lBlock;this._lBlock=this._rBlock,this._rBlock=b,x.call(this,1,1431655765),E.call(this,8,16711935),E.call(this,2,858993459),x.call(this,16,65535),x.call(this,4,252645135),f[g]=this._lBlock,f[g+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function x(f,g){var h=(this._lBlock>>>f^this._rBlock)&g;this._rBlock^=h,this._lBlock^=h<>>f^this._lBlock)&g;this._lBlock^=h,this._rBlock^=h<192.");var h=g.slice(0,2),A=g.length<4?g.slice(0,2):g.slice(2,4),y=g.length<6?g.slice(0,2):g.slice(4,6);this._des1=p.createEncryptor(n.create(h)),this._des2=p.createEncryptor(n.create(A)),this._des3=p.createEncryptor(n.create(y))},encryptBlock:function(f,g){this._des1.encryptBlock(f,g),this._des2.decryptBlock(f,g),this._des3.encryptBlock(f,g)},decryptBlock:function(f,g){this._des3.decryptBlock(f,g),this._des2.encryptBlock(f,g),this._des1.decryptBlock(f,g)},keySize:192/32,ivSize:64/32,blockSize:64/32});r.TripleDES=a._createHelper(v)})(),t.TripleDES})})(St)),St.exports}var Rt={exports:{}},ya=Rt.exports,ss;function Ca(){return ss||(ss=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Se(),Re(),fe(),K())})(ya,function(t){return(function(){var r=t,s=r.lib,n=s.StreamCipher,a=r.algo,i=a.RC4=n.extend({_doReset:function(){for(var u=this._key,m=u.words,d=u.sigBytes,p=this._S=[],x=0;x<256;x++)p[x]=x;for(var x=0,E=0;x<256;x++){var v=x%d,f=m[v>>>2]>>>24-v%4*8&255;E=(E+p[x]+f)%256;var g=p[x];p[x]=p[E],p[E]=g}this._i=this._j=0},_doProcessBlock:function(u,m){u[m]^=l.call(this)},keySize:256/32,ivSize:0});function l(){for(var u=this._S,m=this._i,d=this._j,p=0,x=0;x<4;x++){m=(m+1)%256,d=(d+u[m])%256;var E=u[m];u[m]=u[d],u[d]=E,p|=u[(u[m]+u[d])%256]<<24-x*8}return this._i=m,this._j=d,p}r.RC4=n._createHelper(i);var o=a.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var u=this.cfg.drop;u>0;u--)l.call(this)}});r.RC4Drop=n._createHelper(o)})(),t.RC4})})(Rt)),Rt.exports}var Ft={exports:{}},ba=Ft.exports,ns;function Sa(){return ns||(ns=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Se(),Re(),fe(),K())})(ba,function(t){return(function(){var r=t,s=r.lib,n=s.StreamCipher,a=r.algo,i=[],l=[],o=[],u=a.Rabbit=n.extend({_doReset:function(){for(var d=this._key.words,p=this.cfg.iv,x=0;x<4;x++)d[x]=(d[x]<<8|d[x]>>>24)&16711935|(d[x]<<24|d[x]>>>8)&4278255360;var E=this._X=[d[0],d[3]<<16|d[2]>>>16,d[1],d[0]<<16|d[3]>>>16,d[2],d[1]<<16|d[0]>>>16,d[3],d[2]<<16|d[1]>>>16],v=this._C=[d[2]<<16|d[2]>>>16,d[0]&4294901760|d[1]&65535,d[3]<<16|d[3]>>>16,d[1]&4294901760|d[2]&65535,d[0]<<16|d[0]>>>16,d[2]&4294901760|d[3]&65535,d[1]<<16|d[1]>>>16,d[3]&4294901760|d[0]&65535];this._b=0;for(var x=0;x<4;x++)m.call(this);for(var x=0;x<8;x++)v[x]^=E[x+4&7];if(p){var f=p.words,g=f[0],h=f[1],A=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360,y=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,C=A>>>16|y&4294901760,S=y<<16|A&65535;v[0]^=A,v[1]^=C,v[2]^=y,v[3]^=S,v[4]^=A,v[5]^=C,v[6]^=y,v[7]^=S;for(var x=0;x<4;x++)m.call(this)}},_doProcessBlock:function(d,p){var x=this._X;m.call(this),i[0]=x[0]^x[5]>>>16^x[3]<<16,i[1]=x[2]^x[7]>>>16^x[5]<<16,i[2]=x[4]^x[1]>>>16^x[7]<<16,i[3]=x[6]^x[3]>>>16^x[1]<<16;for(var E=0;E<4;E++)i[E]=(i[E]<<8|i[E]>>>24)&16711935|(i[E]<<24|i[E]>>>8)&4278255360,d[p+E]^=i[E]},blockSize:128/32,ivSize:64/32});function m(){for(var d=this._X,p=this._C,x=0;x<8;x++)l[x]=p[x];p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0>>0?1:0)|0,this._b=p[7]>>>0>>0?1:0;for(var x=0;x<8;x++){var E=d[x]+p[x],v=E&65535,f=E>>>16,g=((v*v>>>17)+v*f>>>15)+f*f,h=((E&4294901760)*E|0)+((E&65535)*E|0);o[x]=g^h}d[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,d[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,d[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,d[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,d[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,d[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,d[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,d[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}r.Rabbit=n._createHelper(u)})(),t.Rabbit})})(Ft)),Ft.exports}var Dt={exports:{}},Ra=Dt.exports,as;function Fa(){return as||(as=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Se(),Re(),fe(),K())})(Ra,function(t){return(function(){var r=t,s=r.lib,n=s.StreamCipher,a=r.algo,i=[],l=[],o=[],u=a.RabbitLegacy=n.extend({_doReset:function(){var d=this._key.words,p=this.cfg.iv,x=this._X=[d[0],d[3]<<16|d[2]>>>16,d[1],d[0]<<16|d[3]>>>16,d[2],d[1]<<16|d[0]>>>16,d[3],d[2]<<16|d[1]>>>16],E=this._C=[d[2]<<16|d[2]>>>16,d[0]&4294901760|d[1]&65535,d[3]<<16|d[3]>>>16,d[1]&4294901760|d[2]&65535,d[0]<<16|d[0]>>>16,d[2]&4294901760|d[3]&65535,d[1]<<16|d[1]>>>16,d[3]&4294901760|d[0]&65535];this._b=0;for(var v=0;v<4;v++)m.call(this);for(var v=0;v<8;v++)E[v]^=x[v+4&7];if(p){var f=p.words,g=f[0],h=f[1],A=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360,y=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,C=A>>>16|y&4294901760,S=y<<16|A&65535;E[0]^=A,E[1]^=C,E[2]^=y,E[3]^=S,E[4]^=A,E[5]^=C,E[6]^=y,E[7]^=S;for(var v=0;v<4;v++)m.call(this)}},_doProcessBlock:function(d,p){var x=this._X;m.call(this),i[0]=x[0]^x[5]>>>16^x[3]<<16,i[1]=x[2]^x[7]>>>16^x[5]<<16,i[2]=x[4]^x[1]>>>16^x[7]<<16,i[3]=x[6]^x[3]>>>16^x[1]<<16;for(var E=0;E<4;E++)i[E]=(i[E]<<8|i[E]>>>24)&16711935|(i[E]<<24|i[E]>>>8)&4278255360,d[p+E]^=i[E]},blockSize:128/32,ivSize:64/32});function m(){for(var d=this._X,p=this._C,x=0;x<8;x++)l[x]=p[x];p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0>>0?1:0)|0,this._b=p[7]>>>0>>0?1:0;for(var x=0;x<8;x++){var E=d[x]+p[x],v=E&65535,f=E>>>16,g=((v*v>>>17)+v*f>>>15)+f*f,h=((E&4294901760)*E|0)+((E&65535)*E|0);o[x]=g^h}d[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,d[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,d[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,d[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,d[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,d[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,d[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,d[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}r.RabbitLegacy=n._createHelper(u)})(),t.RabbitLegacy})})(Dt)),Dt.exports}var Bt={exports:{}},Da=Bt.exports,is;function Ba(){return is||(is=1,(function(c,e){(function(t,r,s){c.exports=r(z(),Se(),Re(),fe(),K())})(Da,function(t){return(function(){var r=t,s=r.lib,n=s.BlockCipher,a=r.algo;const i=16,l=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],o=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var u={pbox:[],sbox:[]};function m(v,f){let g=f>>24&255,h=f>>16&255,A=f>>8&255,y=f&255,C=v.sbox[0][g]+v.sbox[1][h];return C=C^v.sbox[2][A],C=C+v.sbox[3][y],C}function d(v,f,g){let h=f,A=g,y;for(let C=0;C1;--C)h=h^v.pbox[C],A=m(v,h)^A,y=h,h=A,A=y;return y=h,h=A,A=y,A=A^v.pbox[1],h=h^v.pbox[0],{left:h,right:A}}function x(v,f,g){for(let S=0;S<4;S++){v.sbox[S]=[];for(let F=0;F<256;F++)v.sbox[S][F]=o[S][F]}let h=0;for(let S=0;S=g&&(h=0);let A=0,y=0,C=0;for(let S=0;St.toString(16).padStart(2,"0")).join("")}generateIV(){const e=new Uint8Array(12);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}deriveKey(e,t){return ae.PBKDF2(e,t,{keySize:le.KEY_SIZE/32,iterations:le.PBKDF2_ITERATIONS}).toString()}encrypt(e,t){const r=this.generateSalt(),s=this.generateIV(),n=this.deriveKey(t,r);return{data:ae.AES.encrypt(e,n,{iv:ae.enc.Hex.parse(s),mode:ae.mode.GCM,padding:ae.pad.NoPadding}).toString(),iv:s,salt:r,version:this.version,timestamp:Date.now()}}decrypt(e,t){try{const r=this.deriveKey(t,e.salt);return ae.AES.decrypt(e.data,r,{iv:ae.enc.Hex.parse(e.iv),mode:ae.mode.GCM,padding:ae.pad.NoPadding}).toString(ae.enc.Utf8)}catch{throw new Error("Échec du déchiffrement: données corrompues ou clé incorrecte")}}setItem(e,t){try{const r=JSON.stringify(t),s=this.encrypt(r,this.key),n=this.prefix+e;localStorage.setItem(n,JSON.stringify(s))}catch{throw new Error("Impossible de chiffrer les données")}}getItem(e){try{const t=this.prefix+e,r=localStorage.getItem(t);if(!r)return null;const s=JSON.parse(r);s.version,this.version;const n=this.decrypt(s,this.key);return JSON.parse(n)}catch{return null}}removeItem(e){const t=this.prefix+e;localStorage.removeItem(t)}hasItem(e){const t=this.prefix+e;return localStorage.getItem(t)!==null}clear(){Object.keys(localStorage).forEach(t=>{t.startsWith(this.prefix)&&localStorage.removeItem(t)})}keys(){return Object.keys(localStorage).filter(t=>t.startsWith(this.prefix)).map(t=>t.substring(this.prefix.length))}migrateUnsecureData(e){const t=e;this.prefix+e;const r=localStorage.getItem(t);if(!r)return!1;try{const s=JSON.parse(r);return this.setItem(e,s),localStorage.removeItem(t),!0}catch{return!1}}getKey(){return this.key}setKey(e){this.key=e}};L(le,"DEFAULT_PREFIX","secure_"),L(le,"VERSION","1.0.0"),L(le,"PBKDF2_ITERATIONS",1e5),L(le,"KEY_SIZE",256);let Ht=le;const Y=new Ht,cs=["profil","revenus","actifs","prestations","depenses","budget","optimisations","plan","rapports"];class Fs{keyFor(e,t){return`scenario:${e}:${t}`}getProfile(e){const t=this.keyFor(e,"profile");return Y.getItem(t)??this.readLocalStorageFallback(t)}getRevenus(e){const t=this.keyFor(e,"revenus");return(Y.getItem(t)??this.readLocalStorageFallback(t))||[]}getActifs(e){const t=this.keyFor(e,"actifs");return(Y.getItem(t)??this.readLocalStorageFallback(t))||[]}getPrestations(e){const t=this.keyFor(e,"prestations");return Y.getItem(t)??this.readLocalStorageFallback(t)}getDepenses(e){const t=this.keyFor(e,"depenses");return(Y.getItem(t)??this.readLocalStorageFallback(t))||[]}readLocalStorageFallback(e){try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}}class wa{constructor(e=new Fs){this.provider=e}validateStep(e,t){switch(e){case"profil":return this.validateProfil(t);case"revenus":return this.validateRevenus(t);case"actifs":return this.validateActifs(t);case"prestations":return this.validatePrestations(t);case"depenses":return this.validateDepenses(t);case"budget":return[...this.validateProfil(t),...this.validateRevenus(t),...this.validateActifs(t),...this.validatePrestations(t),...this.validateDepenses(t)];case"optimisations":case"plan":case"rapports":return this.validateStep("budget",t)}}computeCompleteness(e,t){return e.map(r=>{const s=this.validateStep(r,t);return{step:r,complete:s.length===0,missing:s}})}validateProfil(e){const t=[],r=this.provider.getProfile(e);return r?(r.birthDate||t.push({path:"profil.birthDate",label:"Date de naissance",severity:"error",help:"Entrez votre date de naissance (AAAA-MM-JJ)"}),r.province||t.push({path:"profil.province",label:"Province de résidence",severity:"error",help:"Sélectionnez votre province"}),r.status||t.push({path:"profil.status",label:"Statut (actif/sans emploi/retraité)",severity:"error",help:"Choisissez votre statut actuel"}),r.hasSpouse&&!r.spouse?.birthDate&&t.push({path:"profil.spouse.birthDate",label:"Date de naissance du conjoint",severity:"warning",help:"Recommandé pour des calculs conjoints"}),t):(t.push({path:"profil",label:"Profil",severity:"error",help:"Renseignez votre profil de base"}),t)}validateRevenus(e){const t=[],r=this.provider.getRevenus(e);return(!r||r.length===0)&&t.push({path:"revenus",label:"Revenus",severity:"error",help:"Ajoutez au moins une source de revenu (salaire, autonome, AE, pensions, etc.)"}),t}validateActifs(e){const t=[],r=this.provider.getActifs(e);return r?(Array.isArray(r)&&r.length===0&&t.push({path:"actifs",label:"Actifs/Investissements (optionnel)",severity:"info",help:"Aucun actif déclaré. Vous pouvez passer à la suite si cela reflète votre situation."}),t):(t.push({path:"actifs",label:"Actifs/Investissements",severity:"error",help:"Initialisez vos comptes (REER, CELI, non-enregistré, etc.)"}),t)}validatePrestations(e){const t=[],r=this.provider.getPrestations(e);if(!r)return t.push({path:"prestations",label:"Prestations gouvernementales",severity:"error",help:"Renseignez la RRQ/CPP et SV/OAS (âge souhaité et/ou estimations)"}),t;const s=r.rrqTargetAge,n=r.rrqEstimates&&(r.rrqEstimates.at60||r.rrqEstimates.at65||r.rrqEstimates.at70||r.rrqEstimates.at72);!(typeof s=="number"&&s>=60&&s<=72)&&!n&&t.push({path:"prestations.rrqTargetAge",label:"Âge cible RRQ (60–72) ou estimation RRQ",severity:"error",help:"Sélectionnez un âge RRQ ou fournissez des estimations"});const a=r.oasTargetAge,i=r.oasEstimates&&(r.oasEstimates.baseAt65||r.oasEstimates.deferralIncreasePctPerMonth);return!(typeof a=="number"&&a>=65&&a<=70)&&!i&&t.push({path:"prestations.oasTargetAge",label:"Âge cible SV (65–70) ou estimation SV",severity:"error",help:"Sélectionnez un âge SV ou fournissez des estimations"}),t}validateDepenses(e){const t=[],r=this.provider.getDepenses(e);return!r||r.length===0?t.push({path:"depenses",label:"Dépenses",severity:"error",help:"Ajoutez au moins une dépense (logement, nourriture, assurances, etc.)"}):r.some(n=>["housing","groceries","utilities"].includes(n?.category))||t.push({path:"depenses",label:"Dépenses essentielles",severity:"warning",help:"Aucune dépense essentielle détectée (logement, épicerie, électricité). Vérifiez vos entrées."}),t}}const Ee=class Ee{constructor(){L(this,"validator");const e=new Fs;this.validator=new wa(e)}static getInstance(){return Ee.instance||(Ee.instance=new Ee),Ee.instance}stateKey(e){return`wizard:${e}:state`}getState(e){const t=this.stateKey(e);return Y.getItem(t)||{currentStep:"profil",scenarioId:e,lastSavedAt:Date.now(),mode:"guide"}}saveState(e){const t=this.stateKey(e.scenarioId);Y.setItem(t,{...e,lastSavedAt:Date.now()})}async getProgress(e){const t=cs,r=this.validator.computeCompleteness(t,e),s=r.filter(o=>o.complete).length,n=Math.round(s/t.length*100),a=r.find(o=>!o.complete)?.step,l=this.getState(e).currentStep||t[0];return{steps:r,current:l,nextIncomplete:a,percent:n}}async getNextIncompleteStep(e){const t=cs;return this.validator.computeCompleteness(t,e).find(s=>!s.complete)?.step||null}async canProceed(e,t){const r=this.validator.validateStep(e,t);return{ok:r.length===0,missing:r}}async markStepComplete(e,t){const r=this.getState(t);this.saveState({...r,currentStep:e})}async goTo(e,t){const r=this.getState(t);this.saveState({...r,currentStep:e})}async setMode(e,t){const r=this.getState(t);this.saveState({...r,mode:e})}prestationsKey(e){return`scenario:${e}:prestations`}async applyRRQAge(e,t){if(typeof e!="number"||e<60||e>72)throw new Error("Âge RRQ invalide (doit être 60–72)");const r=this.prestationsKey(t),n={...Y.getItem(r)||{},rrqTargetAge:e};Y.setItem(r,n);const a=this.getState(t);this.saveState({...a,currentStep:"budget"})}async applyOASAge(e,t){if(typeof e!="number"||e<65||e>70)throw new Error("Âge SV invalide (doit être 65–70)");const r=this.prestationsKey(t),n={...Y.getItem(r)||{},oasTargetAge:e};Y.setItem(r,n);const a=this.getState(t);this.saveState({...a,currentStep:"budget"})}withdrawalKey(e){return`scenario:${e}:withdrawal`}async applyWithdrawalOrder(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("Ordre de retrait invalide");const r=this.withdrawalKey(t),n={...Y.getItem(r)||{},order:e,appliedAt:Date.now()};Y.setItem(r,n);const a=this.getState(t);this.saveState({...a,currentStep:"optimisations"})}};L(Ee,"instance");let Ut=Ee;const Oi=Ut.getInstance(),Ds=c=>`scenario:${c}:notifications`;function ls(c){return c.toISOString().split("T")[0]}function _a(c){const[e,t,r]=c.split("-").map(Number);return new Date(e,(t||1)-1,r||1)}function us(){return`n-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function $t(c){const e=Ds(c);try{return Y.getItem(e)??JSON.parse(localStorage.getItem(e)||"[]")}catch{return[]}}function Lt(c,e){const t=Ds(c);Y.setItem(t,e);try{localStorage.setItem(t,JSON.stringify(e))}catch{}}class Wt{static list(e){return $t(e)}static clear(e){Lt(e,[])}static scheduleSeries(e){const t=e.leads&&e.leads.length>0?e.leads:[90,60,30],r=e.title||Wt.defaultTitle(e.type),s=e.message||Wt.defaultMessage(e.type),n=_a(e.targetDateISO),a=Date.now(),i=$t(e.scenarioId),l=[];return t.forEach(o=>{const u=new Date(n);u.setDate(u.getDate()-o);const m=ls(u),d={id:us(),scenarioId:e.scenarioId,type:e.type,title:`${r} — ${o} j`,message:s,dateISO:m,createdAt:a,meta:{...e.meta||{},leadDays:o,targetDateISO:e.targetDateISO}};l.push(d)}),Lt(e.scenarioId,[...i,...l]),l}static scheduleRRQ(e){return this.scheduleSeries({type:"RRQ_APPLICATION",scenarioId:e.scenarioId,targetDateISO:e.targetDateISO,title:e.title,message:e.message})}static scheduleSV(e){return this.scheduleSeries({type:"OAS_APPLICATION",scenarioId:e.scenarioId,targetDateISO:e.targetDateISO,title:e.title,message:e.message})}static scheduleFERRConversion(e){return this.scheduleSeries({type:"FERR_CONVERSION",scenarioId:e.scenarioId,targetDateISO:e.seventyOneBirthdayISO,title:e.title||"Conversion FERR (71 ans)",message:e.message||"Planifier la conversion du REER en FERR et revoir l’ordre de retraits."})}static scheduleWithdrawalNotice(e){return this.scheduleSeries({type:"WITHDRAWAL_NOTICE",scenarioId:e.scenarioId,targetDateISO:e.dateISO,title:e.title||"Préavis de retrait",message:e.message||"Préparer un retrait et vérifier les impacts fiscaux."})}static scheduleMonthEndSync(e){const t=Math.max(1,Math.min(12,Number(e.months||3))),r=new Date,s=[],n=$t(e.scenarioId),a="Rappel fin de mois",i="Synchroniser budget/dépenses et enregistrer un instantané.",l=Date.now();for(let o=0;o{const a=Q.yearFraction(r,n.date);return s+n.amount/Math.pow(1+t,a)},0)}static findBracket(e,t=-.999,r=10,s=[-.999,-.9,-.5,-.2,-.1,0,.05,.1,.2,.5,1,2,5,10]){let n=s[0],a=Q.npvAtRate(e,n);for(let i=1;ir)continue;const o=Q.npvAtRate(e,l);if(a===0)return[n,n];if(o===0)return[l,l];if(o*a<0)return[n,l];n=l,a=o}return null}static bisectionIRR(e,t,r,s){const n=s?.maxIterations??100,a=s?.tolerance??1e-7;let i=Q.npvAtRate(e,t),l=Q.npvAtRate(e,r);if(i===0)return t;if(l===0)return r;if(i*l>0)return 0;let o=t,u=r;for(let m=0;md.amount>0),s=e.some(d=>d.amount<0);if(!r||!s)return 0;const n=t?.guess??.1,a=t?.maxIterations??100,i=t?.tolerance??1e-7,l=t?.lowerBound??-.999,o=t?.upperBound??10;let u=n;for(let d=0;d=o)break;u=g}const m=Q.findBracket(e,l,o);return m?Q.bisectionIRR(e,m[0],m[1],t):0}static xirr(e,t){const r=[...e].sort((s,n)=>s.date.getTime()-n.date.getTime());return Q.irr(r,t)}static twr(e){if(!e.length)return{totalReturn:0};let t=1,r,s;e.forEach((i,l)=>{const o=i.startValue,u=i.endValue,m=i.netFlow??0;if(o<=0)return;const d=(u-m)/o;d>0&&(t*=d),l===0&&(r=i.startDate),l===e.length-1&&(s=i.endDate)});const n=t-1;let a;if(r&&s){const i=Q.yearFraction(r,s);i>0&&(a=Math.pow(1+n,1/i)-1)}return{totalReturn:n,annualizedReturn:a}}static mwr(e,t){return Q.xirr(e,t)}static annualize(e,t){return t<=0?e:Math.pow(1+e,1/t)-1}static buildTwrPeriods(e){if(!e||e.length<2)return[];const t=[...e].sort((s,n)=>s.date.getTime()-n.date.getTime()),r=[];for(let s=1;s{const s=new FileReader;s.onload=()=>{this.logoDataUrl=s.result||null,r(this.logoDataUrl)},s.onerror=()=>r(null),s.readAsDataURL(t)})}catch{return null}}static async generateLongevityReport(e,t,r={}){const{includeCharts:s=!0,includeComparisons:n=!0,includeCoupleAnalysis:a=!0,includeRecommendations:i=!0,language:l="fr",reportTitle:o,authorName:u}=r,m=new ce({unit:"mm",format:"letter"});let d=this.MARGIN;return d=this.addTitlePage(m,e,t,{title:o,author:u,language:l}),d=this.addExecutiveSummary(m,e,t,d,l),d=this.addPersonalAnalysis(m,e,t,d,l),s&&(d=this.addChartsSection(m,e,d,l)),n&&(d=this.addComparisonsSection(m,e,t,d,l)),a&&this.hasCoupleData(e)&&(d=this.addCoupleAnalysisSection(m,e,d,l)),i&&(d=this.addRecommendationsSection(m,e,t,d,l)),await this.addFooterWithLogo(m,l),m.output("blob")}static addTitlePage(e,t,r,s){const{title:n,author:a,language:i}=s,l=i==="fr";e.setFillColor(240,248,255),e.rect(0,0,this.PAGE_WIDTH,this.PAGE_HEIGHT,"F"),e.setFontSize(24),e.setTextColor(31,41,55);const o=n||(l?"Rapport d'Analyse de Longévité":"Longevity Analysis Report");e.text(o,this.PAGE_WIDTH/2,80,{align:"center"}),e.setFontSize(16),e.setTextColor(107,114,128);const u=l?"Analyse Personnalisée et Recommandations":"Personalized Analysis and Recommendations";e.text(u,this.PAGE_WIDTH/2,100,{align:"center"}),e.setFontSize(12),e.setTextColor(75,85,99);const m=this.getUserInfo(t,l);e.text(m,this.PAGE_WIDTH/2,130,{align:"center"}),e.setFontSize(18),e.setTextColor(16,185,129);const d=`${r.toFixed(1)} ${l?"ans d'espérance de vie":"years life expectancy"}`;e.text(d,this.PAGE_WIDTH/2,160,{align:"center"}),e.setFontSize(10),e.setTextColor(107,114,128);const p=new Date().toLocaleDateString(i==="fr"?"fr-CA":"en-CA");e.text(`${l?"Généré le":"Generated on"} ${p}`,this.PAGE_WIDTH/2,200,{align:"center"}),a&&e.text(`${l?"Par":"By"} ${a}`,this.PAGE_WIDTH/2,210,{align:"center"}),e.setFontSize(8),e.setTextColor(156,163,175);const x=l?"Rapport confidentiel - À usage personnel uniquement":"Confidential Report - For personal use only";return e.text(x,this.PAGE_WIDTH/2,280,{align:"center"}),this.MARGIN}static addExecutiveSummary(e,t,r,s,n){const a=n==="fr";e.addPage();let i=this.MARGIN;return e.setFontSize(18),e.setTextColor(31,41,55),e.text(a?"Résumé Exécutif":"Executive Summary",this.MARGIN,i),i+=15,e.setFontSize(12),this.generateExecutiveSummary(t,r,a).forEach(o=>{i>this.PAGE_HEIGHT-30&&(e.addPage(),i=this.MARGIN),e.setTextColor(75,85,99);const u=e.splitTextToSize(o,this.CONTENT_WIDTH);e.text(u,this.MARGIN,i),i+=u.length*5+5}),i+10}static addPersonalAnalysis(e,t,r,s,n){const a=n==="fr";e.addPage();let i=this.MARGIN;return e.setFontSize(18),e.setTextColor(31,41,55),e.text(a?"Analyse Personnelle":"Personal Analysis",this.MARGIN,i),i+=15,e.setFontSize(12),this.generatePersonalAnalysis(t,r,a).forEach(o=>{i>this.PAGE_HEIGHT-50&&(e.addPage(),i=this.MARGIN),e.setFontSize(14),e.setTextColor(31,41,55),e.text(o.title,this.MARGIN,i),i+=10,e.setFontSize(11),e.setTextColor(75,85,99),o.content.forEach(u=>{const m=e.splitTextToSize(u,this.CONTENT_WIDTH);e.text(m,this.MARGIN+5,i),i+=m.length*5+3}),i+=5}),i+10}static addChartsSection(e,t,r,s){const n=s==="fr";e.addPage();let a=this.MARGIN;e.setFontSize(18),e.setTextColor(31,41,55),e.text(n?"Visualisations et Graphiques":"Charts and Visualizations",this.MARGIN,a),a+=15,e.setFontSize(12),e.setTextColor(107,114,128);const i=n?"Les graphiques interactifs sont disponibles dans la version web de l'application.":"Interactive charts are available in the web version of the application.",l=e.splitTextToSize(i,this.CONTENT_WIDTH);return e.text(l,this.MARGIN,a),a+=l.length*5+10,a}static addComparisonsSection(e,t,r,s,n){const a=n==="fr";e.addPage();let i=this.MARGIN;e.setFontSize(18),e.setTextColor(31,41,55),e.text(a?"Comparaisons Provinciales":"Provincial Comparisons",this.MARGIN,i),i+=15;const l=this.generateComparisonData(t,r,a);return e.setFontSize(12),l.forEach(o=>{i>this.PAGE_HEIGHT-30&&(e.addPage(),i=this.MARGIN),e.setTextColor(75,85,99);const u=e.splitTextToSize(o,this.CONTENT_WIDTH);e.text(u,this.MARGIN,i),i+=u.length*5+5}),i+10}static addCoupleAnalysisSection(e,t,r,s){const n=s==="fr";e.addPage();let a=this.MARGIN;e.setFontSize(18),e.setTextColor(31,41,55),e.text(n?"Analyse de Couple":"Couple Analysis",this.MARGIN,a),a+=15;const i=this.generateCoupleAnalysisData(t,n);return e.setFontSize(12),i.forEach(l=>{a>this.PAGE_HEIGHT-30&&(e.addPage(),a=this.MARGIN),e.setTextColor(75,85,99);const o=e.splitTextToSize(l,this.CONTENT_WIDTH);e.text(o,this.MARGIN,a),a+=o.length*5+5}),a+10}static addRecommendationsSection(e,t,r,s,n){const a=n==="fr";e.addPage();let i=this.MARGIN;e.setFontSize(18),e.setTextColor(31,41,55),e.text(a?"Recommandations":"Recommendations",this.MARGIN,i),i+=15;const l=this.generateRecommendations(t,r,a);return e.setFontSize(12),l.forEach((o,u)=>{i>this.PAGE_HEIGHT-40&&(e.addPage(),i=this.MARGIN),e.setFontSize(14),e.setTextColor(16,185,129),e.text(`${u+1}.`,this.MARGIN,i),i+=8,e.setFontSize(11),e.setTextColor(75,85,99);const m=e.splitTextToSize(o,this.CONTENT_WIDTH-10);e.text(m,this.MARGIN+8,i),i+=m.length*5+8}),i+10}static addFooter(e,t){const r=t==="fr",s=e.getNumberOfPages?.()??1;for(let n=1;n<=s;n++){e.setPage(n),e.setDrawColor(229,231,235),e.line(this.MARGIN,this.PAGE_HEIGHT-15,this.PAGE_WIDTH-this.MARGIN,this.PAGE_HEIGHT-15),e.setFontSize(8),e.setTextColor(107,114,128);const a=`Page ${n} ${r?"de":"of"} ${s}`;e.text(a,this.PAGE_WIDTH/2,this.PAGE_HEIGHT-8,{align:"center"})}}static getUserInfo(e,t){const r=e.personal,s=r?.naissance1?new Date().getFullYear()-new Date(r.naissance1).getFullYear():65,n=r?.sexe1==="F"?t?"Femme":"Female":t?"Homme":"Male",a=r?.province||"QC";return`${s} ${t?"ans":"years old"}, ${n}, ${a}`}static generateExecutiveSummary(e,t,r){const s=[];return r?(s.push(`Votre espérance de vie estimée est de ${t.toFixed(1)} ans.`),s.push("Cette analyse est basée sur vos données personnelles, votre état de santé, et vos habitudes de vie."),s.push("Les résultats tiennent compte des dernières données démographiques canadiennes (CPM2014)."),s.push("Cette évaluation vous aidera à planifier votre retraite et vos besoins financiers futurs.")):(s.push(`Your estimated life expectancy is ${t.toFixed(1)} years.`),s.push("This analysis is based on your personal data, health status, and lifestyle habits."),s.push("Results account for the latest Canadian demographic data (CPM2014)."),s.push("This assessment will help you plan your retirement and future financial needs.")),s}static generatePersonalAnalysis(e,t,r){const s=e.personal||{},n=[],a={title:r?"Facteurs de Santé":"Health Factors",content:[]};s.etatSante1&&a.content.push(r?`État de santé: ${s.etatSante1}`:`Health status: ${s.etatSante1}`),s.modeVieActif1&&a.content.push(r?`Mode de vie actif: ${s.modeVieActif1}`:`Active lifestyle: ${s.modeVieActif1}`),n.push(a);const i={title:r?"Facteurs Socioéconomiques":"Socioeconomic Factors",content:[]};return s.niveauCompetences1&&i.content.push(r?`Niveau de compétences: ${s.niveauCompetences1}`:`Education level: ${s.niveauCompetences1}`),n.push(i),n}static generateComparisonData(e,t,r){const s=[];return r?(s.push(`Votre espérance de vie de ${t.toFixed(1)} ans est comparée aux moyennes provinciales.`),s.push("Cette comparaison vous situe par rapport à la population de votre province."),s.push("Les données provinciales tiennent compte des facteurs locaux de santé et de mortalité.")):(s.push(`Your life expectancy of ${t.toFixed(1)} years is compared to provincial averages.`),s.push("This comparison positions you relative to your province's population."),s.push("Provincial data accounts for local health and mortality factors.")),s}static generateCoupleAnalysisData(e,t){const r=[];return t?(r.push("L'analyse de couple évalue les probabilités de survie conjointe."),r.push("Elle aide à planifier les besoins financiers en cas de survie d'un conjoint."),r.push("Les calculs tiennent compte des différences d'espérance de vie entre conjoints.")):(r.push("Couple analysis evaluates joint survival probabilities."),r.push("It helps plan financial needs in case of spousal survival."),r.push("Calculations account for life expectancy differences between spouses.")),r}static generateRecommendations(e,t,r){const s=[];return r?(s.push("Consultez régulièrement votre médecin pour des bilans de santé préventifs."),s.push("Maintenez un mode de vie actif et équilibré."),s.push("Planifiez votre retraite financière en tenant compte de votre espérance de vie."),s.push("Envisagez des assurances adaptées à vos besoins spécifiques."),s.push("Préparez un plan successoral complet.")):(s.push("Consult your physician regularly for preventive health check-ups."),s.push("Maintain an active and balanced lifestyle."),s.push("Plan your financial retirement considering your life expectancy."),s.push("Consider insurance policies adapted to your specific needs."),s.push("Prepare a comprehensive estate plan.")),s}static hasCoupleData(e){const t=e.personal||{};return!!(t.sexe2&&t.naissance2)}static async exportChartAsImage(e){try{return(await Ys(e,{scale:2,useCORS:!0,allowTaint:!0,backgroundColor:"#ffffff"})).toDataURL("image/png")}catch{return""}}static async generateBudgetReport(e,t){const r=e==="fr",{netMonthlyIncome:s,allocations:n,targets:a,emergencyMonthsTarget:i=0,emergencySaved:l=0,sinkingFunds:o=[],debt:u,reportTitle:m,authorName:d}=t,p=new ce({unit:"mm",format:"letter"});let x=this.addTitleLikePage(p,{title:m||(r?"Budget personnel":"Personal Budget"),subtitle:r?"Résumé financier et objectifs":"Financial summary and goals",info:r?`Revenu net mensuel: ${s.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}`:`Net monthly income: ${s.toLocaleString("en-CA",{style:"currency",currency:"CAD"})}`,author:d,language:e});p.addPage(),x=this.MARGIN,p.setFontSize(18),p.setTextColor(31,41,55),p.text(r?"Règle 50/30/20":"50/30/20 Rule",this.MARGIN,x),x+=10;const E=[r?`Cibles: Besoins ${a.needsPct} %, Envies ${a.wantsPct} %, Épargne/Dettes ${a.savingsDebtPct} %`:`Targets: Needs ${a.needsPct}%, Wants ${a.wantsPct}%, Savings/Debt ${a.savingsDebtPct}%`,r?`Réalisé: Besoins ${n.pctNeeds.toFixed(1)} %, Envies ${n.pctWants.toFixed(1)} %, Épargne/Dettes ${n.pctSavingsDebt.toFixed(1)} %`:`Actual: Needs ${n.pctNeeds.toFixed(1)}%, Wants ${n.pctWants.toFixed(1)}%, Savings/Debt ${n.pctSavingsDebt.toFixed(1)}%`,r?`Montants mensuels: Besoins ${n.totalNeeds.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}, Envies ${n.totalWants.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}, Épargne/Dettes ${n.totalSavingsDebt.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}`:`Monthly amounts: Needs ${n.totalNeeds.toLocaleString("en-CA",{style:"currency",currency:"CAD"})}, Wants ${n.totalWants.toLocaleString("en-CA",{style:"currency",currency:"CAD"})}, Savings/Debt ${n.totalSavingsDebt.toLocaleString("en-CA",{style:"currency",currency:"CAD"})}`];x=this.writeBulletPoints(p,E,x),p.addPage(),x=this.MARGIN,p.setFontSize(18),p.setTextColor(31,41,55),p.text(r?"Fonds d’urgence":"Emergency Fund",this.MARGIN,x),x+=10;const v=Math.max(0,n.totalNeeds),f=v>0?l/v:0,g=[r?`Cible: ${i} mois de besoins essentiels`:`Target: ${i} months of essential needs`,r?`Montant épargné: ${l.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})} (${f.toFixed(1)} mois)`:`Amount saved: ${l.toLocaleString("en-CA",{style:"currency",currency:"CAD"})} (${f.toFixed(1)} months)`,r?`Besoins essentiels mensuels estimés: ${v.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}`:`Estimated essential needs (monthly): ${v.toLocaleString("en-CA",{style:"currency",currency:"CAD"})}`];if(x=this.writeBulletPoints(p,g,x),p.addPage(),x=this.MARGIN,p.setFontSize(18),p.setTextColor(31,41,55),p.text(r?"Objectifs planifiés":"Planned goals",this.MARGIN,x),x+=10,o.length===0)p.setFontSize(12),p.setTextColor(107,114,128),p.text(r?"Aucun objectif enregistré.":"No goals recorded.",this.MARGIN,x),x+=8;else{p.setFontSize(12),p.setTextColor(75,85,99);for(const y of o){const C=r?`• ${y.name}: cible ${y.goalAmount.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}, échéance ${y.dueDate}, mensualité requise ~ ${Math.max(0,y.monthlyRequired||0).toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}, épargné ${Math.max(0,y.saved||0).toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}`:`• ${y.name}: target ${y.goalAmount.toLocaleString("en-CA",{style:"currency",currency:"CAD"})}, due ${y.dueDate}, required monthly ~ ${Math.max(0,y.monthlyRequired||0).toLocaleString("en-CA",{style:"currency",currency:"CAD"})}, saved ${Math.max(0,y.saved||0).toLocaleString("en-CA",{style:"currency",currency:"CAD"})}`,S=p.splitTextToSize(C,this.CONTENT_WIDTH);x>this.PAGE_HEIGHT-20&&(p.addPage(),x=this.MARGIN),p.text(S,this.MARGIN,x),x+=S.length*5+3}}p.addPage(),x=this.MARGIN,p.setFontSize(18),p.setTextColor(31,41,55),p.text(r?"Dettes — stratégie “boule de neige”":"Debts — snowball strategy",this.MARGIN,x),x+=10;const h=[],A=u?.debts?.length||0;return h.push(r?`Nombre de dettes: ${A}`:`Debts count: ${A}`),h.push(r?`Méthode: ${u?.method==="rate"?"par plus haut taux":"par plus petit solde"}`:`Method: ${u?.method==="rate"?"highest rate":"lowest balance"}`),h.push(r?`Montant additionnel mensuel: ${(u?.extraPerMonth||0).toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}`:`Extra per month: ${(u?.extraPerMonth||0).toLocaleString("en-CA",{style:"currency",currency:"CAD"})}`),x=this.writeBulletPoints(p,h,x),await this.addFooterWithLogo(p,e),p.output("blob")}static addTitleLikePage(e,t){const{title:r,subtitle:s,info:n,author:a,language:i}=t;e.setFillColor(245,247,255),e.rect(0,0,this.PAGE_WIDTH,this.PAGE_HEIGHT,"F"),e.setFontSize(24),e.setTextColor(31,41,55),e.text(r,this.PAGE_WIDTH/2,80,{align:"center"}),e.setFontSize(14),e.setTextColor(107,114,128),e.text(s,this.PAGE_WIDTH/2,95,{align:"center"}),e.setFontSize(12),e.setTextColor(55,65,81),e.text(n,this.PAGE_WIDTH/2,115,{align:"center"}),e.setFontSize(10),e.setTextColor(107,114,128);const l=new Date().toLocaleDateString(i==="fr"?"fr-CA":"en-CA");return e.text(`${i==="fr"?"Généré le":"Generated on"} ${l}`,this.PAGE_WIDTH/2,135,{align:"center"}),a&&e.text(`${i==="fr"?"Par":"By"} ${a}`,this.PAGE_WIDTH/2,145,{align:"center"}),this.MARGIN}static writeBulletPoints(e,t,r){let s=r;e.setFontSize(12),e.setTextColor(75,85,99);for(const n of t){s>this.PAGE_HEIGHT-20&&(e.addPage(),s=this.MARGIN);const a=`• ${n}`,i=e.splitTextToSize(a,this.CONTENT_WIDTH);e.text(i,this.MARGIN,s),s+=i.length*5+3}return s+4}static async addFooterWithLogo(e,t){const r=t==="fr",s=e.getNumberOfPages?.()??1,n=await this.ensureLogoDataUrl();for(let a=1;a<=s;a++){if(e.setPage(a),e.setDrawColor(229,231,235),e.line(this.MARGIN,this.PAGE_HEIGHT-15,this.PAGE_WIDTH-this.MARGIN,this.PAGE_HEIGHT-15),n)try{const u=this.MARGIN,m=this.PAGE_HEIGHT-14;e.addImage(n,"PNG",u,m,24,6,void 0,"FAST")}catch{}e.setFontSize(8),e.setTextColor(107,114,128);const i=`Page ${a} ${r?"de":"of"} ${s}`;e.text(i,this.PAGE_WIDTH/2,this.PAGE_HEIGHT-8,{align:"center"})}}static async generateQuickSummary(e,t,r="fr"){const s=new ce({unit:"mm",format:"letter"});s.setFontSize(20),s.setTextColor(31,41,55);const n=r==="fr"?"Résumé de Longévité":"Longevity Summary";s.text(n,this.PAGE_WIDTH/2,30,{align:"center"}),s.setFontSize(16),s.setTextColor(16,185,129);const a=`${t.toFixed(1)} ${r==="fr"?"ans":"years"}`;s.text(a,this.PAGE_WIDTH/2,60,{align:"center"}),s.setFontSize(10),s.setTextColor(107,114,128);const i=new Date().toLocaleDateString(r==="fr"?"fr-CA":"en-CA");return s.text(i,this.PAGE_WIDTH/2,80,{align:"center"}),s.output("blob")}static async generateScenarioComparisonReport(e,t,r){const s=e==="fr",n=new ce({unit:"mm",format:"letter"}),a=r?.reportTitle||(s?"Comparaison de Scénarios":"Scenario Comparison");n.setFontSize(22),n.setTextColor(31,41,55),n.text(a,this.PAGE_WIDTH/2,26,{align:"center"}),n.setFontSize(12),n.setTextColor(75,85,99);let i=40;return n.text(s?"Scénarios inclus:":"Included scenarios:",this.MARGIN,i),i+=8,t.scenarios.forEach(l=>{const o=`• ${l.name}${l.description?" — "+l.description:""}`,u=n.splitTextToSize(o,this.CONTENT_WIDTH);n.text(u,this.MARGIN,i),i+=u.length*5+2}),i+=6,n.setFontSize(14),n.setTextColor(31,41,55),n.text(s?"Métriques clés":"Key metrics",this.MARGIN,i),i+=8,n.setFontSize(11),n.setTextColor(55,65,81),t.metrics.forEach(l=>{i>this.PAGE_HEIGHT-30&&(n.addPage(),i=this.MARGIN);const o=l.label+":";n.text(o,this.MARGIN,i),i+=6;const u=l.values.map(d=>{const p=t.scenarios.find(v=>v.id===d.scenarioId),x=p?p.name:d.scenarioId;let E;switch(l.type){case"currency":E=new Intl.NumberFormat(s?"fr-CA":"en-CA",{style:"currency",currency:"CAD",maximumFractionDigits:0}).format(d.value);break;case"percentage":E=`${d.value.toFixed(1)}%`;break;case"years":E=`${d.value}`;break;default:E=`${d.value}`}return`${x}: ${E}`}),m=n.splitTextToSize("• "+u.join(" | "),this.CONTENT_WIDTH);n.text(m,this.MARGIN+4,i),i+=m.length*5+4}),t.recommendations&&t.recommendations.length&&(i>this.PAGE_HEIGHT-40&&(n.addPage(),i=this.MARGIN),n.setFontSize(14),n.setTextColor(31,41,55),n.text(s?"Recommandations":"Recommendations",this.MARGIN,i),i+=8,n.setFontSize(11),n.setTextColor(75,85,99),t.recommendations.forEach(l=>{const o=n.splitTextToSize("• "+l,this.CONTENT_WIDTH);n.text(o,this.MARGIN,i),i+=o.length*5+3})),await this.addFooterWithLogo(n,e),n.output("blob")}static async generateBankerReport(e,t={}){const r=e==="fr",s=new ce({unit:"mm",format:"letter"});this.addTitleLikePage(s,{title:r?"Résumé bancaire — Retraite":"Banker summary — Retirement",subtitle:r?t.scenarioName||"Scénario personnel":t.scenarioName||"Personal scenario",info:`Client: ${t.clientName||(r?"Non précisé":"Unspecified")}`,author:t.authorName,language:e}),s.addPage();let n=this.MARGIN;s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Synthèse financière":"Financial summary",this.MARGIN,n),n+=12;const a=[],i=(t.netMonthlyNeed||0).toLocaleString(r?"fr-CA":"en-CA",{style:"currency",currency:"CAD"});return a.push(r?`Besoin net mensuel à couvrir: ${i}`:`Net monthly need to cover: ${i}`),t.withdrawalOrder&&t.withdrawalOrder.length&&a.push((r?"Ordre de retraits recommandé: ":"Recommended withdrawal order: ")+t.withdrawalOrder.join(" → ")),typeof t.monthsCoveredOp=="number"&&a.push(r?`Coussin opérationnel: ${t.monthsCoveredOp} mois de dépenses essentielles`:`Operational buffer: ${t.monthsCoveredOp} months of essential needs`),typeof t.yearsCoveredShort=="number"&&a.push(r?`Horizon court terme couvert: ${t.yearsCoveredShort} an(s)`:`Short-term horizon covered: ${t.yearsCoveredShort} year(s)`),n=this.writeBulletPoints(s,a,n),s.addPage(),n=this.MARGIN,s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Hypothèses":"Assumptions",this.MARGIN,n),n+=10,t.assumptions&&t.assumptions.length?n=this.writeBulletPoints(s,t.assumptions,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text(r?"Aucune hypothèse détaillée fournie.":"No detailed assumptions provided.",this.MARGIN,n),n+=8),n+=6,s.setFontSize(18),s.setTextColor(31,41,55),s.text("Notes",this.MARGIN,n),n+=10,t.notes&&t.notes.length?this.writeBulletPoints(s,t.notes,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text("—",this.MARGIN,n)),await this.addFooterWithLogo(s,e),s.output("blob")}static async generatePlannerReport(e,t={}){const r=e==="fr",s=new ce({unit:"mm",format:"letter"});this.addTitleLikePage(s,{title:r?"Planificateur financier — Synthèse":"Financial planner — Summary",subtitle:t.scenarioName||(r?"Scénario personnel":"Personal scenario"),info:`Client: ${t.clientName||(r?"Non précisé":"Unspecified")}`,author:t.authorName,language:e}),s.addPage();let n=this.MARGIN;if(s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Recommandations":"Recommendations",this.MARGIN,n),n+=10,t.recommendations&&t.recommendations.length?n=this.writeBulletPoints(s,t.recommendations,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text(r?"Aucune recommandation fournie.":"No recommendations provided.",this.MARGIN,n),n+=8),s.addPage(),n=this.MARGIN,s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Comparaisons clés":"Key comparisons",this.MARGIN,n),n+=10,s.setFontSize(12),s.setTextColor(75,85,99),t.comparisons&&t.comparisons.length)for(const a of t.comparisons){const i=`• ${a.label}: ${a.value}`,l=s.splitTextToSize(i,this.CONTENT_WIDTH);s.text(l,this.MARGIN,n),n+=l.length*5+3,n>this.PAGE_HEIGHT-20&&(s.addPage(),n=this.MARGIN)}else s.text("—",this.MARGIN,n),n+=6;return s.addPage(),n=this.MARGIN,s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Plan d'action":"Action plan",this.MARGIN,n),n+=10,t.actionPlan&&t.actionPlan.length?this.writeBulletPoints(s,t.actionPlan,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text("—",this.MARGIN,n)),await this.addFooterWithLogo(s,e),s.output("blob")}static async generatePerformanceReport(e,t){const r=e==="fr",s=new ce({unit:"mm",format:"letter"}),n=t.title||(r?"Rapport de performance — Investissements":"Performance Report — Investments"),a=r?"IRR (MWR), TWR et métriques clés":"IRR (MWR), TWR and key metrics",i=r?`Comptes analysés: ${t.accounts.length}`:`Accounts analyzed: ${t.accounts.length}`;this.addTitleLikePage(s,{title:n,subtitle:a,info:i,author:t.authorName,language:e}),s.addPage();let l=this.MARGIN;s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Résultats par compte":"Results by account",this.MARGIN,l),l+=10,s.setFontSize(11),s.setTextColor(55,65,81);const o=p=>`${(p*100).toFixed(2)}%`,u=p=>new Intl.NumberFormat(r?"fr-CA":"en-CA",{style:"currency",currency:"CAD"}).format(p);for(const p of t.accounts){l>this.PAGE_HEIGHT-40&&(s.addPage(),l=this.MARGIN),s.setFontSize(14),s.setTextColor(31,41,55),s.text(`${p.accountType}`,this.MARGIN,l),l+=7,s.setFontSize(11),s.setTextColor(55,65,81);const x=[`${r?"Rendement total":"Total return"}: ${o(p.totalReturn)}`,`${r?"Rendement annualisé":"Annualized return"}: ${o(p.annualizedReturn)}`,`${r?"TWR (pondéré dans le temps)":"TWR (time-weighted)"}: ${o(p.timeWeightedReturn)}`,`${r?"MWR (IRR, pondéré par l’argent)":"MWR (IRR, money-weighted)"}: ${o(p.moneyWeightedReturn)}`,`${r?"Contributions nettes":"Net contributions"}: ${u(p.netContributions)}`,`${r?"Gain en capital":"Capital gain"}: ${u(p.capitalGain)}`];for(const E of x){const v=s.splitTextToSize(`• ${E}`,this.CONTENT_WIDTH);s.text(v,this.MARGIN,l),l+=v.length*5+2}l+=2}l>this.PAGE_HEIGHT-40&&(s.addPage(),l=this.MARGIN),s.setFontSize(14),s.setTextColor(31,41,55),s.text(r?"Légende":"Legend",this.MARGIN,l),l+=8,s.setFontSize(11),s.setTextColor(75,85,99);const m=[r?"TWR — performance du gestionnaire (indépendante des flux).":"TWR — manager performance (independent of cashflows).",r?"MWR (IRR) — performance de l’investisseur (sensible aux flux).":"MWR (IRR) — investor performance (sensitive to cashflows).",r?"Ce rapport est éducatif et destiné à être partagé avec un spécialiste de votre choix.":"This report is educational and intended to be shared with an independent professional of your choice."];for(const p of m){const x=s.splitTextToSize(`• ${p}`,this.CONTENT_WIDTH);s.text(x,this.MARGIN,l),l+=x.length*5+2}if((t.level||"essential")==="complete"){s.addPage(),l=this.MARGIN,s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Analyse détaillée":"Detailed analysis",this.MARGIN,l),l+=10,s.setFontSize(11),s.setTextColor(75,85,99);const p=[r?"Comparaison avant/après frais (TER) si fournis dans l’interface avancée.":"Before/after fees (TER) comparison if provided in the advanced interface.",r?"Benchmarks pédagogiques (ex.: 60/40) pour situer la performance.":"Educational benchmarks (e.g., 60/40) to contextualize performance.",r?"Export généré par MonPlanRetraite.ca — données 100 % locales; logo inclus.":"Export generated by MonPlanRetraite.ca — 100% local data; logo included."];for(const x of p){const E=s.splitTextToSize(`• ${x}`,this.CONTENT_WIDTH);s.text(E,this.MARGIN,l),l+=E.length*5+2}}return await this.addFooterWithLogo(s,e),s.output("blob")}static async generateNotaryReport(e,t={}){const r=e==="fr",s=new ce({unit:"mm",format:"letter"});this.addTitleLikePage(s,{title:r?"Dossier notaire — Synthèse":"Notary dossier — Summary",subtitle:t.scenarioName||(r?"Patrimoine et dispositions":"Estate and dispositions"),info:`Client: ${t.clientName||(r?"Non précisé":"Unspecified")}`,author:t.authorName,language:e}),s.addPage();let n=this.MARGIN;return s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Notes successorales":"Estate notes",this.MARGIN,n),n+=10,t.estateNotes&&t.estateNotes.length?n=this.writeBulletPoints(s,t.estateNotes,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text("—",this.MARGIN,n),n+=6),s.addPage(),n=this.MARGIN,s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Bénéficiaires":"Beneficiaries",this.MARGIN,n),n+=10,t.beneficiaries&&t.beneficiaries.length?n=this.writeBulletPoints(s,t.beneficiaries,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text("—",this.MARGIN,n),n+=6),s.addPage(),n=this.MARGIN,s.setFontSize(18),s.setTextColor(31,41,55),s.text(r?"Liste de documents":"Document checklist",this.MARGIN,n),n+=10,t.documentChecklist&&t.documentChecklist.length?this.writeBulletPoints(s,t.documentChecklist,n):(s.setFontSize(12),s.setTextColor(107,114,128),s.text("—",this.MARGIN,n)),await this.addFooterWithLogo(s,e),s.output("blob")}};L(de,"PAGE_WIDTH",215.9),L(de,"PAGE_HEIGHT",279.4),L(de,"MARGIN",20),L(de,"CONTENT_WIDTH",de.PAGE_WIDTH-2*de.MARGIN),L(de,"logoDataUrl",null);let jt=de;const zi=Object.freeze(Object.defineProperty({__proto__:null,PDFExportService:jt},Symbol.toStringTag,{value:"Module"}));class Ma{static saveCriticalData(e){try{sessionStorage.setItem(this.STORAGE_KEYS.SESSION,JSON.stringify(e)),localStorage.setItem(this.STORAGE_KEYS.LOCAL,JSON.stringify(e)),localStorage.setItem(this.STORAGE_KEYS.CRITICAL,JSON.stringify(e)),e.personal?.unifiedIncome1&&(sessionStorage.setItem("unifiedIncome1",JSON.stringify(e.personal.unifiedIncome1)),localStorage.setItem("unifiedIncome1",JSON.stringify(e.personal.unifiedIncome1))),e.personal?.unifiedIncome2&&(sessionStorage.setItem("unifiedIncome2",JSON.stringify(e.personal.unifiedIncome2)),localStorage.setItem("unifiedIncome2",JSON.stringify(e.personal.unifiedIncome2))),e.retirement&&(sessionStorage.setItem("retirementData",JSON.stringify(e.retirement)),localStorage.setItem("retirementData",JSON.stringify(e.retirement)))}catch{}}static loadCriticalData(){try{let e=this.tryLoadFromStorage(this.STORAGE_KEYS.SESSION);return e?this.cleanData(e):(e=this.tryLoadFromStorage(this.STORAGE_KEYS.LOCAL),e?this.cleanData(e):(e=this.tryLoadFromStorage(this.STORAGE_KEYS.CRITICAL),e?this.cleanData(e):(e=this.reconstructFromPartialData(),e?this.cleanData(e):this.getDefaultData())))}catch{return this.getDefaultData()}}static tryLoadFromStorage(e){try{const t=sessionStorage.getItem(e)||localStorage.getItem(e);if(t)return JSON.parse(t)}catch{}return null}static reconstructFromPartialData(){try{const e=this.tryLoadFromStorage("unifiedIncome1")||[],t=this.tryLoadFromStorage("unifiedIncome2")||[],r=this.tryLoadFromStorage("retirementData")||{};if(e.length>0||t.length>0||Object.keys(r).length>0)return{personal:{unifiedIncome1:e,unifiedIncome2:t,...this.getDefaultData().personal},retirement:{...this.getDefaultData().retirement,...r}}}catch{}return null}static getDefaultData(){return{personal:{prenom1:"",prenom2:"",naissance1:"",naissance2:"",sexe1:"",sexe2:"",salaire1:0,salaire2:0,statutProfessionnel1:"",statutProfessionnel2:"",ageRetraiteSouhaite1:0,ageRetraiteSouhaite2:0,depensesRetraite:0,unifiedIncome1:[],unifiedIncome2:[],soldeREER1:0,dateREER1:"",soldeCELI1:0,dateCELI1:"",soldeCRI1:0,dateCRI1:"",soldeREER2:0,dateREER2:"",soldeCELI2:0,dateCELI2:"",soldeCRI2:0,dateCRI2:""},retirement:{rrqAgeActuel1:0,rrqMontantActuel1:null,rrqMontant70_1:0,esperanceVie1:0,rrqAgeActuel2:0,rrqMontantActuel2:null,rrqMontant70_2:0,esperanceVie2:0,svBiannual1:{periode1:{montant:null,date:""},periode2:{montant:null,date:""}},svBiannual2:{periode1:{montant:null,date:""},periode2:{montant:null,date:""}}}}}static cleanData(e){if(!e)return e;const t={...e};return t.retirement?.rrqMontantActuel1===0&&(t.retirement.rrqMontantActuel1=null),t.retirement?.rrqMontantActuel2===0&&(t.retirement.rrqMontantActuel2=null),t.retirement?.svBiannual1&&(t.retirement.svBiannual1.periode1?.montant===0&&(t.retirement.svBiannual1.periode1.montant=null),t.retirement.svBiannual1.periode2?.montant===0&&(t.retirement.svBiannual1.periode2.montant=null)),t.retirement?.svBiannual2&&(t.retirement.svBiannual2.periode1?.montant===0&&(t.retirement.svBiannual2.periode1.montant=null),t.retirement.svBiannual2.periode2?.montant===0&&(t.retirement.svBiannual2.periode2.montant=null)),t}static startAutoSave(e){setInterval(()=>{this.saveCriticalData(e)},5e3)}}L(Ma,"STORAGE_KEYS",{SESSION:"retirement-session-data",LOCAL:"retirement-backup-data",CRITICAL:"critical-retirement-data"});const $={AGE_RETRAITE_NORMALE:65,AGE_RETRAITE_ANTICIPEE_MIN:55,AGE_RETRAITE_INVALIDITE_MIN:50,HEURES_INVALIDITE_MIN:21e3,REDUCTION_ANNUELLE:.03,TAUX_RENTE_ANNUEL_2025:28.5,FACTEURS_ACTUARIELS:{55:.0045,56:.0048,57:.0051,58:.0054,59:.0057,60:.006,61:.0063,62:.0066,63:.0069,64:.0072,65:.0075,66:.0078,67:.0081,68:.0084,69:.0087,70:.009,71:.0093},COORDINATION_RRQ_FACTEUR:.7,COORDINATION_PSV_FACTEUR:1,TAUX_INDEXATION:.025,ESPERANCE_VIE_HOMME:82,ESPERANCE_VIE_FEMME:85,TAUX_ACTUALISATION:.03};class Na{static calculateCCQPension(e){try{const t=this.validateCCQData(e);if(!t.isValid)throw new Error(`Données CCQ invalides: ${t.errors.join(", ")}`);const r=this.calculateGeneralAccount(e),s=this.calculateComplementaryAccount(e),n=r.renteAnnuelle+s.renteAnnuelle,a=n/12,{facteurReduction:i,montantReduction:l}=this.calculateEarlyRetirementReduction(e.ageRetraiteSouhaite,a),o=this.calculateRenteNivelee(a,i),u=this.calculateRenteMajoreeReduite(a,i),m=this.checkEligibility(e),d=this.calculateLifetimeProjection(a,e.ageRetraiteSouhaite,"M"),p=this.calculatePresentValue(d,e.ageRetraiteSouhaite),x=this.calculateRRQCoordination(e),E=this.calculatePSVCoordination(e),v=this.calculateSRGCoordination(e),f=this.calculateOptimalRetirementAge(e),g=this.generateRecommendedStrategy(e,f),h=this.generateOptimizationSuggestions(e);return{compteGeneral:r,compteComplementaire:s,renteAnnuelleTotale:n,renteMensuelleTotale:a,facteurReduction:i,montantReduction:l,renteNivelee:o,renteMajoreeReduite:u,admissibilite:m,projectionViagere:d,valeurActualisee:p,coordinationRRQ:x,coordinationPSV:E,coordinationSRG:v,ageOptimalRetraite:f,strategieRecommandee:g,optimisationSuggestions:h}}catch(t){throw new Error(`Impossible de calculer la pension CCQ: ${t.message}`)}}static calculateGeneralAccount(e){const t=e.heuresAjusteesAvant2005||0,r=$.TAUX_RENTE_ANNUEL_2025,s=t*r,n=s/12;return{heuresAjustees:t,tauxRenteAnnuel:r,renteAnnuelle:s,renteMensuelle:n,description:`Compte Général basé sur ${t.toLocaleString()} heures ajustées à ${r} $/heure`}}static calculateComplementaryAccount(e){const t=e.valeurCompteComplementaire||0,r=e.ageRetraiteSouhaite||$.AGE_RETRAITE_NORMALE,s=$.FACTEURS_ACTUARIELS[r]||$.FACTEURS_ACTUARIELS[65],n=t*s,a=n/12;return{valeurAccumulee:t,facteurActuariel:s,renteAnnuelle:n,renteMensuelle:a,description:`Compte Complémentaire: ${t.toLocaleString()} $ × facteur ${s}`}}static calculateEarlyRetirementReduction(e,t){if(e>=$.AGE_RETRAITE_NORMALE)return{};const s=($.AGE_RETRAITE_NORMALE-e)*$.REDUCTION_ANNUELLE,n=t*s;return{facteurReduction:s,montantReduction:n}}static calculateRenteNivelee(e,t){const r=t?e*(1-t):e;return{type:"nivelee",montantAvant65:r,montantApres65:r,avantages:["Montant constant tout au long de la retraite","Simplicité de planification budgétaire","Aucune surprise à 65 ans"],inconvenients:["Montant plus faible avant 65 ans","Ne profite pas des prestations RRQ/PSV"],valeurViagere:this.calculateLifetimeValue(r,65),recommande:!1}}static calculateRenteMajoreeReduite(e,t){const r=t?e*(1-t):e,s=r*1.3,n=r*.7;return{type:"majoree-reduite",montantAvant65:s,montantApres65:n,avantages:["Montant plus élevé avant 65 ans","Compensation pour absence RRQ/PSV","Meilleur flux de trésorerie initial"],inconvenients:["Réduction permanente après 65 ans","Planification plus complexe","Risque si RRQ/PSV changent"],valeurViagere:this.calculateLifetimeValue(s,65,n),recommande:!0}}static checkEligibility(e){const t=this.calculateCurrentAge(e.dateEntreeIndustrie),r=new Date(Date.now()-t*365.25*24*60*60*1e3),s={eligible:t>=$.AGE_RETRAITE_NORMALE,ageRequis:$.AGE_RETRAITE_NORMALE,dateAdmissibilite:new Date(r.getTime()+$.AGE_RETRAITE_NORMALE*365.25*24*60*60*1e3),description:"Retraite normale sans conditions particulières"},n={eligible:t>=$.AGE_RETRAITE_ANTICIPEE_MIN&&this.meetsEarlyRetirementConditions(e),ageRequis:$.AGE_RETRAITE_ANTICIPEE_MIN,conditionsSpeciales:["Conditions d'heures spécifiques selon l'année d'entrée"],dateAdmissibilite:new Date(r.getTime()+$.AGE_RETRAITE_ANTICIPEE_MIN*365.25*24*60*60*1e3),description:"Retraite anticipée sans pénalité si conditions remplies"},a={eligible:t>=$.AGE_RETRAITE_ANTICIPEE_MIN,ageRequis:$.AGE_RETRAITE_ANTICIPEE_MIN,dateAdmissibilite:new Date(r.getTime()+$.AGE_RETRAITE_ANTICIPEE_MIN*365.25*24*60*60*1e3),description:"Retraite anticipée avec réduction de 3% par année d'anticipation"},i={eligible:t>=$.AGE_RETRAITE_INVALIDITE_MIN&&e.heuresTotales>=$.HEURES_INVALIDITE_MIN,ageRequis:$.AGE_RETRAITE_INVALIDITE_MIN,heuresRequises:$.HEURES_INVALIDITE_MIN,conditionsSpeciales:["Invalidité totale reconnue","Payable à partir de la 53e semaine"],dateAdmissibilite:new Date(r.getTime()+$.AGE_RETRAITE_INVALIDITE_MIN*365.25*24*60*60*1e3),description:"Retraite pour invalidité avec conditions strictes"},l={eligible:t>=$.AGE_RETRAITE_ANTICIPEE_MIN&&e.dateEntreeIndustrie{const a={...e,ageRetraiteSouhaite:n},i=this.calculateCCQPension(a);i.valeurActualisee>s&&(s=i.valeurActualisee,r=n)}),r}static generateRecommendedStrategy(e,t){return t===$.AGE_RETRAITE_NORMALE?"Retraite normale à 65 ans recommandée - Équilibre optimal entre pension et durée de perception":t<$.AGE_RETRAITE_NORMALE?"Retraite anticipée avantageuse - Situation permet l'anticipation malgré les réductions":"Report de retraite avantageux - Accumulation supplémentaire compense l'attente"}static generateOptimizationSuggestions(e){const t=[];return t.push({strategie:"Optimisation de l'âge de retraite",description:"Analyser l'impact de différents âges de retraite sur vos revenus totaux",impact:this.calculateAgeOptimizationImpact(e),requisits:["Flexibilité d'emploi","Analyse des besoins financiers"],delaiImplementation:"Planification 2-5 ans avant la retraite",avantages:["Maximisation des revenus viagers","Optimisation fiscale"],inconvenients:["Incertitude sur l'espérance de vie","Contraintes d'emploi"],priorite:"haute"}),t.push({strategie:"Optimisation de l'option de rente",description:"Choisir entre rente nivelée et majorée-réduite selon votre situation",impact:this.calculateRenteOptionImpact(e),requisits:["Analyse des revenus RRQ/PSV","Planification budgétaire"],delaiImplementation:"Au moment de la demande de retraite",avantages:["Optimisation du flux de trésorerie","Coordination avec régimes publics"],inconvenients:["Complexité de planification","Risques réglementaires"],priorite:"haute"}),t.push({strategie:"Coordination avec REER/CELI",description:"Optimiser l'épargne privée en fonction de la pension CCQ",impact:this.calculatePrivateSavingsImpact(e),requisits:["Capacité d'épargne","Horizon de placement"],delaiImplementation:"Dès maintenant",avantages:["Diversification des revenus","Optimisation fiscale"],inconvenients:["Gestion plus complexe","Risques de placement"],priorite:"moyenne"}),t}static calculateLifetimeProjection(e,t,r="M"){const a=((r==="F"?$.ESPERANCE_VIE_FEMME:$.ESPERANCE_VIE_HOMME)-t)*12;let i=0,l=e;for(let o=0;o0&&(l*=1+$.TAUX_INDEXATION);return i}static calculatePresentValue(e,t){const s=Math.max(0,t-55);return e/Math.pow(1+$.TAUX_ACTUALISATION,s)}static calculateRRQCoordination(e){return 1200*$.COORDINATION_RRQ_FACTEUR}static calculatePSVCoordination(e){return 717.15*$.COORDINATION_PSV_FACTEUR}static calculateSRGCoordination(e){return 0}static calculateCurrentAge(e){const r=Math.abs(new Date().getTime()-e.getTime()),s=Math.ceil(r/(1e3*60*60*24*365.25));return Math.min(s+25,70)}static meetsEarlyRetirementConditions(e){return e.heuresTotales>=15e3}static calculateLifetimeValue(e,t,r){let n=0;for(let a=t;a<83;a++){const i=r&&a>=65?r:e;n+=i*12}return n}static calculateAgeOptimizationImpact(e){return 5e4}static calculateRenteOptionImpact(e){return 25e3}static calculatePrivateSavingsImpact(e){return 75e3}static validateCCQData(e){const t=[],r=[],s=[];if(e.certificatCompetence||t.push("Certificat de compétence CCQ requis"),e.dateEntreeIndustrie||t.push("Date d'entrée dans l'industrie requise"),(!e.heuresTotales||e.heuresTotales<=0)&&t.push("Heures totales travaillées requises"),e.heuresTravaileesAvant2005&&e.heuresTravaileesDepuis2005){const n=e.heuresTravaileesAvant2005+e.heuresTravaileesDepuis2005;Math.abs(n-(e.heuresTotales||0))>100&&r.push("Incohérence dans le total des heures travaillées")}return e.valeurCompteGeneral||s.push("Valeur du compte général (du Relevé annuel CCQ)"),e.valeurCompteComplementaire||s.push("Valeur du compte complémentaire (du Relevé annuel CCQ)"),{isValid:t.length===0,errors:t,warnings:r,missingData:s}}static generateProjectionScenarios(e){const t=[];return t.push({nom:"Retraite anticipée (55 ans)",ageRetraite:55,heuresSupplementaires:0,typeRetraite:"anticipee-avec-reduction",optionRente:"majoree-reduite",resultat:this.calculateCCQPension({...e,ageRetraiteSouhaite:55}),avantages:["Liberté plus tôt","Profiter de la retraite en santé"],risques:["Réduction de 30% de la pension","Revenus insuffisants"]}),t.push({nom:"Retraite normale (65 ans)",ageRetraite:65,heuresSupplementaires:0,typeRetraite:"normale",optionRente:"nivelee",resultat:this.calculateCCQPension({...e,ageRetraiteSouhaite:65}),avantages:["Pension complète","Coordination optimale RRQ/PSV"],risques:["Travailler plus longtemps","Risques de santé"]}),t.push({nom:"Retraite différée (70 ans)",ageRetraite:70,heuresSupplementaires:e.heuresAnnuellesEstimees*5,typeRetraite:"normale",optionRente:"nivelee",resultat:this.calculateCCQPension({...e,ageRetraiteSouhaite:70,heuresTravaileesDepuis2005:e.heuresTravaileesDepuis2005+e.heuresAnnuellesEstimees*5}),avantages:["Pension maximale","Accumulation supplémentaire"],risques:["Incertitude santé","Moins d'années de retraite"]}),t}}class $i{static calculateEIDetails(e,t,r=new Date().toISOString().split("T")[0]){const s=e.filter(C=>C.type==="ei"),n=this.calculateAge(t,r);let a=0,i=0,l=0,o=35;s.forEach(C=>{const S=this.calculateWeeksBetweenDates(C.startDate,C.endDate);a+=S,C.details?.weeklyRate&&(i=C.details.weeklyRate),C.deductions&&(l=(C.deductions.federalTax||0)+(C.deductions.provincialTax||0))});const u=Math.max(0,o-a),m=i-l,d=u,p=this.addWeeksToDate(r,d),x=this.calculateRemainingWeeksInYear(r),v=Math.min(u,x)*m,h=e.filter(C=>C.type==="employment").reduce((C,S)=>C+S.grossAmount,0)+v,A=n>=60,y=this.generateTransitionRecommendations(n,u,p,h,m);return{totalWeeksUsed:a,weeksRemaining:u,estimatedEndDate:p,canExtendWithIncome:u>0,vacationWeeksAvailable:Math.min(2,u),netWeeklyAmount:m,grossWeeklyAmount:i,totalDeductions:l,projectedAnnualIncome:h,eligibleForTransition:A,transitionRecommendations:y}}static generateTransitionRecommendations(e,t,r,s,n){const a=[],i=new Date(r);if(e>=60){const l=new Date(i);l.setDate(l.getDate()+1);const u=1364.6*.36,m=Math.min(u,s*.25/12);a.push({type:"rrq",priority:t<=4?"high":"medium",timing:l.toISOString().split("T")[0],reason:"Transition fluide après la fin de l'assurance emploi. Évite une période sans revenu.",impact:{monthlyIncome:m,annualIncome:m*12,taxImplications:"Revenu imposable, mais généralement plus avantageux que l'AE"},requirements:["Avoir cotisé au RRQ pendant au moins 1 an","Faire la demande 3 mois avant la date souhaitée","Cesser ou réduire substantiellement le travail"],nextSteps:["Contacter Retraite Québec pour une estimation personnalisée","Préparer les documents requis (relevés d'emploi, T4)","Planifier la transition financière"]})}return e>=65&&a.push({type:"sv",priority:"high",timing:"Immédiatement (si pas déjà fait)",reason:"Prestation universelle disponible dès 65 ans",impact:{monthlyIncome:707.68,annualIncome:707.68*12,taxImplications:"Récupération possible si revenu total > 90 997$"},requirements:["Résidence au Canada pendant 40 ans après 18 ans (pension complète)","Minimum 10 ans de résidence (pension partielle)"],nextSteps:["Demande automatique à 64 ans, vérifier le statut","Considérer le report si revenus élevés"]}),e<65&&t>8&&a.push({type:"employment",priority:"medium",timing:"Dès maintenant",reason:"Maximiser les revenus et prolonger la période d'assurance emploi",impact:{taxImplications:"Revenus d'emploi peuvent prolonger l'AE si < 90% du taux hebdomadaire"},requirements:["Recherche active d'emploi","Déclaration des revenus à Service Canada"],nextSteps:["Utiliser les services d'aide à l'emploi","Considérer l'emploi à temps partiel pour prolonger l'AE","Calculer l'impact sur les prestations"]}),e<60&&t>12&&a.push({type:"training",priority:"low",timing:"Pendant la période d'AE",reason:"Améliorer l'employabilité pendant la période de prestations",impact:{taxImplications:"Certaines formations permettent de maintenir l'AE"},requirements:["Approbation de Service Canada","Formation approuvée"],nextSteps:["Explorer les programmes de formation subventionnés","Vérifier l'éligibilité avec Service Canada"]}),a.sort((l,o)=>{const u={high:3,medium:2,low:1};return u[o.priority]-u[l.priority]})}static simulateVacationImpact(e,t){const r=new Date(e.estimatedEndDate),s=new Date(r);return s.setDate(s.getDate()+t*7),{newEndDate:s.toISOString().split("T")[0],weeksExtended:t}}static calculateIncomeImpact(e,t){let n=0,a="";if(t<=90)a="Aucune déduction - revenu sous l'exemption de 90$";else{const o=t-90;n=o*.5,a=`Déduction de ${n.toFixed(2)}$ (50% de ${o.toFixed(2)}$ excédentaire)`}const i=Math.max(0,e-n),l=i>0;return{deduction:n,netEI:i,canExtend:l,explanation:a}}static integrateConstructionWorkerIncome(e,t,r,s=new Date().toISOString().split("T")[0]){const n=Na.calculateCCQPension(t),a=this.calculateEIDetails(e,r,s),i=this.calculateAge(r,s),l=this.generateConstructionTransitionStrategy(i,n,a,t);return{totalProjectedIncome:this.calculateTotalConstructionIncome(a.projectedAnnualIncome,n,i),ccqPension:n,eiDetails:a,transitionStrategy:l}}static generateConstructionTransitionStrategy(e,t,r,s){const n=[];let a=65,i=0;if(t.admissibilite.retraiteNormale.eligible&&(a=65,i=t.renteMensuelleTotale,n.push("✅ Éligible à la retraite normale CCQ à 65 ans sans réduction")),t.admissibilite.retraiteAnticipeeSansReduction.eligible){const l=t.admissibilite.retraiteAnticipeeSansReduction.ageRequis;l&&l=55&&(n.push("🏗️ Secteur construction: Considérer la retraite partielle si éligible"),n.push("📞 Contacter CCQ au 1-888-842-8282 pour validation des heures")),s.heuresAjusteesAvant2005>0&&n.push("📋 Vérifier les heures ajustées pré-2005 avec la CCQ"),e>=60&&n.push("🔄 Coordonner la prise du RRQ avec la rente CCQ pour optimiser les revenus"),t.renteMajoreeReduite.recommande&&n.push("💰 Analyser l'option rente majorée-réduite pour maximiser les revenus avant 65 ans"),{optimalRetirementAge:a,monthlyIncomeAtRetirement:i,recommendations:n}}static calculateTotalConstructionIncome(e,t,r){let s=e;return(r>=55&&t.admissibilite.retraiteAnticipeeAvecReduction.eligible||r>=65)&&(s+=t.renteAnnuelleTotale),s}static calculateAge(e,t){const r=new Date(e),s=new Date(t);let n=s.getFullYear()-r.getFullYear();const a=s.getMonth()-r.getMonth();return(a<0||a===0&&s.getDate()r.isActive).map(r=>({type:r.type,description:r.description,annualAmount:r.projectedAnnual||0,monthlyAmount:this.getMonthlyAmount(r),frequency:this.getFrequency(r.type),isTemporary:r.type==="assurance-emploi",toDateAmount:r.toDateAmount}))},person2:{name:"Person 2",totalAnnual:this.calculateTotalAnnualIncome(t),totalMonthly:this.calculateTotalMonthlyIncome(t),sources:t.filter(r=>r.isActive).map(r=>({type:r.type,description:r.description,annualAmount:r.projectedAnnual||0,monthlyAmount:this.getMonthlyAmount(r),frequency:this.getFrequency(r.type),isTemporary:r.type==="assurance-emploi",toDateAmount:r.toDateAmount}))}},riskAnalysis:{temporaryIncomeRisk:this.assessTemporaryIncomeRisk(e,t),incomeConcentrationRisk:this.assessIncomeConcentration(e,t),eiDependencyRisk:this.assessEIDependency(e,t)},recommendations:this.generateIncomeRecommendations(e,t)}}static calculateTotalMonthlyIncome(e){return e.filter(t=>t.isActive).reduce((t,r)=>t+this.getMonthlyAmount(r),0)}static calculateTotalAnnualIncome(e){return e.filter(t=>t.isActive).reduce((t,r)=>t+(r.projectedAnnual||0),0)}static getMonthlyAmount(e){switch(e.type){case"salaire":case"dividendes":case"travail-autonome":case"autres":return(e.projectedAnnual||0)/12;case"rentes":case"revenus-location":return e.monthlyAmount||0;case"assurance-emploi":return(e.weeklyNet||0)*4.33;default:return 0}}static getFrequency(e){return{salaire:"annual",rentes:"monthly","assurance-emploi":"weekly",dividendes:"annual","revenus-location":"monthly","travail-autonome":"annual",autres:"annual"}[e]||"annual"}static getIncomeByType(e,t){const r=e.find(s=>s.type===t&&s.isActive);return r&&r.projectedAnnual||0}static getIncomeBreakdown(e){const t={};return e.filter(r=>r.isActive).forEach(r=>{t[r.type]=(t[r.type]||0)+(r.projectedAnnual||0)}),t}static getTemporaryIncomeInfo(e,t){const s=[...e,...t].filter(n=>n.isActive&&n.type==="assurance-emploi");return{hasTemporaryIncome:s.length>0,totalTemporaryAnnual:s.reduce((n,a)=>n+(a.projectedAnnual||0),0),temporaryEntries:s.map(n=>({description:n.description,weeklyAmount:n.weeklyNet||0,startDate:n.startDate,endDate:n.endDate,weeksUsed:n.weeksUsed,maxWeeks:n.maxWeeks,toDateAmount:n.toDateAmount||0}))}}static getEIToDateAmounts(e,t){const s=[...e,...t].filter(n=>n.isActive&&n.type==="assurance-emploi"&&n.toDateAmount);return{person1ToDate:e.filter(n=>n.isActive&&n.type==="assurance-emploi").reduce((n,a)=>n+(a.toDateAmount||0),0),person2ToDate:t.filter(n=>n.isActive&&n.type==="assurance-emploi").reduce((n,a)=>n+(a.toDateAmount||0),0),totalToDate:s.reduce((n,a)=>n+(a.toDateAmount||0),0),details:s.map(n=>({description:n.description,toDateAmount:n.toDateAmount||0,weeklyNet:n.weeklyNet||0,weeksUsed:n.weeksUsed||0}))}}static assessTemporaryIncomeRisk(e,t){const r=this.calculateTotalAnnualIncome([...e,...t]),s=[...e,...t].filter(a=>a.isActive&&a.type==="assurance-emploi").reduce((a,i)=>a+(i.projectedAnnual||0),0);if(r===0)return"low";const n=s/r;return n>.5?"high":n>.25?"medium":"low"}static assessIncomeConcentration(e,t){const r=[...e,...t].filter(i=>i.isActive),s=this.calculateTotalAnnualIncome(r);if(s===0||r.length===0)return"low";const a=Math.max(...r.map(i=>i.projectedAnnual||0))/s;return a>.8?"high":a>.6?"medium":"low"}static assessEIDependency(e,t){const r=this.calculateTotalAnnualIncome([...e,...t]),s=this.getIncomeByType([...e,...t],"assurance-emploi");if(s===0)return"none";if(r===0)return"high";const n=s/r;return n>.7?"high":n>.4?"medium":"low"}static generateIncomeRecommendations(e,t){const r=[],s=this.assessTemporaryIncomeRisk(e,t),n=this.assessIncomeConcentration(e,t),a=this.assessEIDependency(e,t);return s==="high"&&r.push("Risque élevé de revenus temporaires - Planifiez une transition vers des revenus permanents"),n==="high"&&r.push("Concentration élevée des revenus - Diversifiez vos sources de revenus"),a==="high"?r.push("Forte dépendance à l'assurance emploi - Considérez demander votre RRQ dès l'admissibilité"):a==="medium"&&r.push("Dépendance modérée à l'assurance emploi - Planifiez la transition vers la retraite"),this.calculateTotalAnnualIncome([...e,...t])<3e4&&r.push("Revenus faibles - Explorez les programmes d'aide gouvernementaux disponibles"),r}static validateIncomeData(e=[],t=[]){const r=[];return[...e,...t].filter(n=>n.isActive&&n.type==="assurance-emploi").forEach((n,a)=>{n.startDate||r.push(`Entrée AE ${a+1}: Date de début manquante`),(!n.weeklyNet||n.weeklyNet<=0)&&r.push(`Entrée AE ${a+1}: Montant hebdomadaire net invalide`),n.weeksUsed&&n.weeksUsed>50&&r.push(`Entrée AE ${a+1}: Nombre de semaines utilisées trop élevé`)}),[...e,...t].forEach((n,a)=>{n.isActive&&(n.annualAmount&&n.annualAmount<0||n.monthlyAmount&&n.monthlyAmount<0||n.weeklyAmount&&n.weeklyAmount<0||n.weeklyNet&&n.weeklyNet<0)&&r.push(`Entrée ${a+1}: Montants négatifs détectés`)}),{isValid:r.length===0,errors:r}}}class qi{static validatePromoCode(e){const t=Er[e.toUpperCase()];if(!t)return{isValid:!1,discount:0,message:"Code promo invalide"};const r=new Date,s=new Date(t.validUntil);return r>s?{isValid:!1,discount:0,message:"Code promo expiré"}:t.currentUses&&t.currentUses>=t.maxUses?{isValid:!1,discount:0,message:"Code promo épuisé"}:{isValid:!0,discount:t.discount,message:t.description,code:t}}static applyPromoCode(e,t){const r=this.validatePromoCode(t);if(!r.isValid)return{finalPrice:e,discount:0,savings:"0,00 $",validation:r};const s=e*r.discount/100,n=e-s;return{finalPrice:Math.round(n*100)/100,discount:r.discount,savings:`${s.toFixed(2)} $`,validation:r}}static checkFeatureUnlock(e,t){const r=this.validatePromoCode(e);return!r.isValid||!r.code?!1:!!(r.code.unlimitedFeatures||r.code.testMode)}static getEffectivePlan(e,t){const r=this.validatePromoCode(t);return!r.isValid||!r.code?e:r.code.unlimitedFeatures||r.code.testMode?"expert":e}static isTestCode(e){const t=this.validatePromoCode(e);return t.isValid&&t.code?.testMode===!0}static getValidPromoCodes(){const e=new Date;return Object.values(Er).filter(t=>{const r=new Date(t.validUntil);return e<=r&&(!t.currentUses||t.currentUsesa.id===e);n&&(s.currentContentIndex=Math.max(s.currentContentIndex,t),s.timeSpent+=r,s.lastAccessed=new Date,s.progress=Math.round(s.currentContentIndex/n.content.length*100),localStorage.setItem(`progress-${e}`,JSON.stringify(s)))}submitQuiz(e,t){const r=this.getAllModules().find(m=>m.id===e);if(!r)throw new Error("Module not found");const s=r.quiz;let n=0,a=0;const i=[];s.questions.forEach(m=>{n+=m.points;const d=t[m.id],p=d===m.correctAnswer;p&&(a+=m.points),i.push({questionId:m.id,question:m.question,userAnswer:d,correctAnswer:m.correctAnswer,isCorrect:p,explanation:m.explanation,points:p?m.points:0})});const l=Math.round(a/n*100),o=l>=s.passingScore;this.saveQuizResult(e,l,o);let u;return o&&(u=this.generateCertificate(e,l)),{score:l,passed:o,results:i,certificate:u}}saveQuizResult(e,t,r){const s=this.getQuizResults();s[e]={score:t,passed:r,completedAt:new Date().toISOString(),attempts:(s[e]?.attempts||0)+1},localStorage.setItem("quiz-results",JSON.stringify(s))}getQuizResults(){const e=localStorage.getItem("quiz-results");return e?JSON.parse(e):{}}generateCertificate(e,t){const r=this.getAllModules().find(a=>a.id===e);if(!r)throw new Error("Module not found");const s={id:`cert-${e}-${Date.now()}`,moduleId:e,userId:"current-user",title:`Certificat de réussite - ${r.title}`,issuedAt:new Date,score:t,credentialId:this.generateCredentialId()},n=this.getUserCertificates();return n.push(s),localStorage.setItem("user-certificates",JSON.stringify(n)),s}generateCredentialId(){return"MPR-"+Date.now().toString(36).toUpperCase()+"-"+Math.random().toString(36).substr(2,5).toUpperCase()}getUserCertificates(){const e=localStorage.getItem("user-certificates");return e?JSON.parse(e).map(t=>({...t,issuedAt:new Date(t.issuedAt),validUntil:t.validUntil?new Date(t.validUntil):void 0})):[]}addBookmark(e,t){const r=this.getUserProgress(e);r&&(r.bookmarks.includes(t)||(r.bookmarks.push(t),localStorage.setItem(`progress-${e}`,JSON.stringify(r))))}addNote(e,t,r){const s=this.getUserProgress(e);if(!s)return;const n={id:Date.now().toString(),contentId:t,text:r,createdAt:new Date,updatedAt:new Date};s.notes.push(n),localStorage.setItem(`progress-${e}`,JSON.stringify(s))}getLearningStats(){const e=this.getAllModules(),t=this.getQuizResults(),r=this.getUserCertificates(),s=Object.keys(t).filter(l=>t[l].passed),n=e.reduce((l,o)=>{const u=this.getUserProgress(o.id);return l+(u?.timeSpent||0)},0),a=Object.values(t).map(l=>l.score).filter(Boolean),i=a.length>0?a.reduce((l,o)=>l+o,0)/a.length:0;return{modulesCompleted:s.length,totalModules:e.length,certificatesEarned:r.length,totalTimeSpent:n,averageScore:Math.round(i)}}resetLearningData(){this.getAllModules().forEach(t=>{localStorage.removeItem(`progress-${t.id}`)}),localStorage.removeItem("quiz-results"),localStorage.removeItem("user-certificates")}};L(ye,"instance");let ds=ye;const Ce=class Ce{static getInstance(){return Ce.instance||(Ce.instance=new Ce),Ce.instance}getUserStats(){const e=localStorage.getItem("user-stats");if(e){const r=JSON.parse(e);return{...r,joinDate:new Date(r.joinDate),lastActivity:new Date(r.lastActivity)}}const t={totalPoints:0,level:1,experiencePoints:0,experienceToNextLevel:100,achievementsUnlocked:0,totalAchievements:this.getAllAchievements().length,currentStreak:0,longestStreak:0,completedChallenges:0,rank:"Débutant",joinDate:new Date,lastActivity:new Date};return this.saveUserStats(t),t}saveUserStats(e){localStorage.setItem("user-stats",JSON.stringify(e))}addPoints(e,t){const r=this.getUserStats();r.totalPoints+=e,r.experiencePoints+=e,r.lastActivity=new Date;const s=this.getLevelInfo(r.level);let n=!1,a=r.level,i=s.title;if(r.totalPoints>=s.maxPoints){const l=this.getLevelInfo(r.level+1);l&&(n=!0,a=l.level,i=l.title,r.level=a,r.rank=i,r.experiencePoints=r.totalPoints-l.minPoints,r.experienceToNextLevel=l.maxPoints-r.totalPoints)}else r.experienceToNextLevel=s.maxPoints-r.totalPoints;return this.saveUserStats(r),this.logActivity("points_earned",{points:e,reason:t}),{levelUp:n,newLevel:n?a:void 0,newTitle:n?i:void 0}}getLevelInfo(e){const t=[{level:1,title:"Débutant",minPoints:0,maxPoints:99,benefits:["Accès aux outils de base","Guide d'introduction"],icon:"🌱",color:"#10B981"},{level:2,title:"Apprenti Financier",minPoints:100,maxPoints:299,benefits:["Calculateurs avancés","Conseils personnalisés"],icon:"📚",color:"#3B82F6"},{level:3,title:"Gestionnaire Avisé",minPoints:300,maxPoints:599,benefits:["Analyses détaillées","Projections long terme"],icon:"💼",color:"#8B5CF6"},{level:4,title:"Planificateur Expert",minPoints:600,maxPoints:999,benefits:["Optimisation fiscale","Stratégies avancées"],icon:"🎯",color:"#F59E0B"},{level:5,title:"Maître de la Retraite",minPoints:1e3,maxPoints:1999,benefits:["Tous les outils premium","Support prioritaire"],icon:"👑",color:"#EF4444"},{level:6,title:"Sage Financier",minPoints:2e3,maxPoints:9999,benefits:["Statut VIP","Accès exclusif aux nouveautés"],icon:"🧙‍♂️",color:"#6366F1"}];return t.find(r=>r.level===e)||t[0]}getAllAchievements(){return[{id:"first-budget",title:"Premier Budget",description:"Créez votre premier budget équilibré",icon:"💰",category:"budget",difficulty:"bronze",points:50,progress:0,maxProgress:1,requirements:["Créer un budget avec revenus ≥ dépenses"],reward:"Déblocage du calculateur d'épargne automatique"},{id:"budget-master",title:"Maître du Budget",description:"Maintenez un budget équilibré pendant 3 mois",icon:"📊",category:"budget",difficulty:"gold",points:200,progress:0,maxProgress:3,requirements:["Budget équilibré pendant 3 mois consécutifs"],reward:'Titre spécial "Gestionnaire Exemplaire"'},{id:"first-savings",title:"Première Épargne",description:"Épargnez votre premier 100$",icon:"🏦",category:"savings",difficulty:"bronze",points:25,progress:0,maxProgress:100,requirements:["Atteindre 100$ d'épargne totale"],reward:`Guide "Stratégies d'épargne avancées"`},{id:"savings-milestone-1k",title:"Cap des 1000$",description:"Atteignez 1000$ d'épargne",icon:"💎",category:"savings",difficulty:"silver",points:100,progress:0,maxProgress:1e3,requirements:["Atteindre 1000$ d'épargne totale"],reward:"Calculateur d'intérêts composés premium"},{id:"emergency-fund-complete",title:"Fonds d'Urgence Complet",description:"Constituez un fonds d'urgence de 3 mois",icon:"🛡️",category:"savings",difficulty:"gold",points:300,progress:0,maxProgress:1,requirements:["Fonds d'urgence ≥ 3 mois de dépenses"],reward:'Badge "Sécurité Financière Assurée"'},{id:"onboarding-complete",title:"Formation Terminée",description:"Complétez votre parcours d'accompagnement",icon:"🎓",category:"learning",difficulty:"bronze",points:75,progress:0,maxProgress:1,requirements:["Terminer le parcours d'onboarding"],reward:"Accès aux modules avancés"},{id:"knowledge-seeker",title:"Chercheur de Savoir",description:"Consultez 10 guides éducatifs",icon:"📖",category:"learning",difficulty:"silver",points:150,progress:0,maxProgress:10,requirements:["Lire 10 guides éducatifs complets"],reward:"Bibliothèque de ressources premium"},{id:"retirement-planning-start",title:"Planification Retraite Amorcée",description:"Créez votre premier plan de retraite",icon:"🏖️",category:"retirement",difficulty:"silver",points:100,progress:0,maxProgress:1,requirements:["Utiliser le calculateur de retraite"],reward:'Guide "Optimisation REER/CELI"'},{id:"retirement-on-track",title:"Sur la Bonne Voie",description:"Votre épargne retraite suit le plan établi",icon:"🎯",category:"retirement",difficulty:"gold",points:250,progress:0,maxProgress:1,requirements:["Épargne retraite ≥ objectif pour votre âge"],reward:"Guide de préparation à une rencontre avec un professionnel"},{id:"debt-reduction-start",title:"Réduction de Dettes Amorcée",description:"Réduisez vos dettes de 10%",icon:"📉",category:"debt",difficulty:"bronze",points:75,progress:0,maxProgress:10,requirements:["Réduire le total des dettes de 10%"],reward:"Calculateur de remboursement optimisé"},{id:"debt-free",title:"Liberté Financière",description:"Éliminez toutes vos dettes",icon:"🎉",category:"debt",difficulty:"platinum",points:500,progress:0,maxProgress:1,requirements:["Total des dettes = 0$"],reward:'Badge "Libre de Dettes" + Titre spécial',isSecret:!0},{id:"consistent-user",title:"Utilisateur Assidu",description:"Utilisez l'application 7 jours consécutifs",icon:"🔥",category:"milestone",difficulty:"bronze",points:50,progress:0,maxProgress:7,requirements:["Connexion quotidienne pendant 7 jours"],reward:"Multiplicateur de points x1.1"},{id:"power-user",title:"Utilisateur Expert",description:"Utilisez tous les outils disponibles",icon:"⚡",category:"milestone",difficulty:"gold",points:300,progress:0,maxProgress:1,requirements:["Utiliser chaque outil au moins une fois"],reward:"Accès anticipé aux nouvelles fonctionnalités"}]}getUserAchievements(){const e=localStorage.getItem("user-achievements"),t=this.getAllAchievements();if(!e)return t;const r=JSON.parse(e);return t.map(s=>({...s,progress:r[s.id]?.progress||0,unlockedAt:r[s.id]?.unlockedAt?new Date(r[s.id].unlockedAt):void 0}))}updateAchievementProgress(e,t){const s=this.getUserAchievements().find(i=>i.id===e);if(!s||s.unlockedAt)return{unlocked:!1};const n=Math.min(t,s.maxProgress);s.progress=n;let a=!1;if(n>=s.maxProgress){s.unlockedAt=new Date,a=!0,this.addPoints(s.points,`Succès débloqué: ${s.title}`);const i=this.getUserStats();i.achievementsUnlocked++,this.saveUserStats(i)}return this.saveAchievementProgress(e,s),{unlocked:a,achievement:a?s:void 0}}saveAchievementProgress(e,t){const r=localStorage.getItem("user-achievements")||"{}",s=JSON.parse(r);s[e]={progress:t.progress,unlockedAt:t.unlockedAt?.toISOString()},localStorage.setItem("user-achievements",JSON.stringify(s))}getActiveChallenges(){const e=localStorage.getItem("active-challenges");if(!e)return this.generateWeeklyChallenges();const t=JSON.parse(e).map(s=>({...s,startDate:new Date(s.startDate),endDate:new Date(s.endDate)})),r=new Date;return t.filter(s=>s.endDate>r)}generateWeeklyChallenges(){const e=new Date,t=new Date(e);t.setDate(e.getDate()-e.getDay());const r=new Date(t);r.setDate(t.getDate()+6);const s=[{id:"weekly-budget-check",title:"Vérification Budgétaire",description:"Consultez votre budget 3 fois cette semaine",category:"budget",duration:7,startDate:t,endDate:r,isActive:!0,isCompleted:!1,progress:0,target:3,reward:{points:50,badge:"Gestionnaire Vigilant"},participants:Math.floor(Math.random()*500)+100,difficulty:"easy"},{id:"weekly-savings-goal",title:"Objectif d'Épargne",description:"Épargnez au moins 50$ cette semaine",category:"savings",duration:7,startDate:t,endDate:r,isActive:!0,isCompleted:!1,progress:0,target:50,reward:{points:75,title:"Épargnant de la Semaine"},participants:Math.floor(Math.random()*300)+50,difficulty:"medium"}];return localStorage.setItem("active-challenges",JSON.stringify(s)),s}updateChallengeProgress(e,t){const r=this.getActiveChallenges(),s=r.find(a=>a.id===e);if(!s||s.isCompleted)return{completed:!1};s.progress=Math.min(t,s.target);let n=!1;if(s.progress>=s.target){s.isCompleted=!0,n=!0,this.addPoints(s.reward.points,`Défi complété: ${s.title}`);const a=this.getUserStats();a.completedChallenges++,this.saveUserStats(a)}return localStorage.setItem("active-challenges",JSON.stringify(r)),{completed:n,challenge:n?s:void 0}}updateStreak(){const e=this.getUserStats(),t=new Date().toDateString(),r=e.lastActivity.toDateString(),s=new Date;s.setDate(s.getDate()-1);const n=s.toDateString();let a=!1;return r===t?{streakIncreased:!1,currentStreak:e.currentStreak}:(r===n?(e.currentStreak++,a=!0):(e.currentStreak=1,a=!0),e.currentStreak>e.longestStreak&&(e.longestStreak=e.currentStreak),e.lastActivity=new Date,this.saveUserStats(e),e.currentStreak===7?this.addPoints(100,"Série de 7 jours !"):e.currentStreak===30&&this.addPoints(500,"Série de 30 jours !"),{streakIncreased:a,currentStreak:e.currentStreak})}logActivity(e,t){const r=this.getRecentActivities();r.unshift({id:Date.now().toString(),action:e,data:t,timestamp:new Date});const s=r.slice(0,50);localStorage.setItem("user-activities",JSON.stringify(s)),this.checkActivityBasedAchievements(e,t)}getRecentActivities(){const e=localStorage.getItem("user-activities");return e?JSON.parse(e).map(t=>({...t,timestamp:new Date(t.timestamp)})):[]}checkActivityBasedAchievements(e,t){switch(e){case"budget_created":this.updateAchievementProgress("first-budget",1);break;case"savings_updated":t?.amount>=100&&this.updateAchievementProgress("first-savings",t.amount),t?.amount>=1e3&&this.updateAchievementProgress("savings-milestone-1k",t.amount);break;case"onboarding_completed":this.updateAchievementProgress("onboarding-complete",1);break;case"guide_read":const r=this.getUserAchievements().find(s=>s.id==="knowledge-seeker")?.progress||0;this.updateAchievementProgress("knowledge-seeker",r+1);break}}getUserRanking(){const e=this.getUserStats(),t=1e4;let r=Math.max(1,Math.floor(t*(1-e.totalPoints/3e3)));r=Math.min(r,t);const s=Math.round((t-r)/t*100);return{rank:r,totalUsers:t,percentile:s}}resetGamificationData(){localStorage.removeItem("user-stats"),localStorage.removeItem("user-achievements"),localStorage.removeItem("active-challenges"),localStorage.removeItem("user-activities")}getAvailableRewards(){const e=this.getUserAchievements().filter(r=>!r.unlockedAt&&!r.isSecret),t=this.getActiveChallenges().filter(r=>!r.isCompleted);return{achievements:e,challenges:t}}};L(Ce,"instance");let Vt=Ce;const Gi=Object.freeze(Object.defineProperty({__proto__:null,GamificationService:Vt},Symbol.toStringTag,{value:"Module"})),ka={logement:"need",services:"need",transport:"need",alimentation:"need",sante:"need",loisirs:"want",epargne:"savings_debt",divers:"want"};class Hi{static getFrequencyMultiplier(e){switch(e){case"weekly":return 52;case"biweekly":return 26;case"monthly":return 12;case"quarterly":return 4;case"annually":return 1;case"seasonal":return 1;default:return 12}}static toMonthlyAmount(e){if(!e.isActive)return 0;if(e.frequency==="seasonal")return(e.amount||0)/12;const t=this.getFrequencyMultiplier(e.frequency);return(e.amount||0)*t/12}static computeAllocations(e,t){let r=0,s=0,n=0;for(const l of e.expenses||[]){const o=this.toMonthlyAmount(l);if(o<=0)continue;const u=ka[l.category];if(u==="savings_debt"){n+=o;continue}if(typeof l.needSharePct=="number"&&!Number.isNaN(l.needSharePct)){const d=Math.max(0,Math.min(100,Number(l.needSharePct))),p=o*d/100,x=o-p;r+=p,s+=x}else u==="need"?r+=o:s+=o}if(e.mortgage?.isActive){const l=e.mortgage.frequency,o=l==="weekly"?52:l==="biweekly"?26:12;r+=e.mortgage.amount*o/12}const a=r+s+n,i=Math.max(1,t||0);return{totalNeeds:r,totalWants:s,totalSavingsDebt:n,totalExpenses:a,pctNeeds:r/i*100,pctWants:s/i*100,pctSavingsDebt:n/i*100}}static defaultTargets(){return{needsPct:50,wantsPct:30,savingsDebtPct:20}}}const Yt="mpr:lastSaves";function ps(c){try{const e=sessionStorage.getItem(Yt),t=e?JSON.parse(e):[];t.unshift(c),sessionStorage.setItem(Yt,JSON.stringify(t.slice(0,5)))}catch{}}const Ui={async saveUserData(c,e){const t=["logementBreakdown","servicesPublicsBreakdown","assurancesBreakdown","telecomBreakdown","alimentationBreakdown","transportBreakdown","santeBreakdown","loisirsBreakdown"],r=JSON.parse(JSON.stringify(c||{}));r.cashflow=r.cashflow||{};for(const u of t)r.cashflow[u]==null&&(r.cashflow[u]={});const s=e||`retirement-data-${new Date().toISOString().split("T")[0]}.json`,n=JSON.stringify(r,null,2),a=window;if(a.showSaveFilePicker)try{const u=await a.showSaveFilePicker({suggestedName:s,types:[{description:"Données MonPlanRetraite.ca",accept:{"application/json":[".json"]}}]}),m=await u.createWritable();return await m.write(new Blob([n],{type:"application/json"})),await m.close(),ps({name:u.name||s,when:new Date().toISOString(),method:"fs"}),{ok:!0}}catch{}const i=new Blob([n],{type:"application/json"}),l=URL.createObjectURL(i),o=document.createElement("a");return o.href=l,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(l),ps({name:s,when:new Date().toISOString(),method:"download"}),{ok:!0}},getRecentSaves(){try{const c=sessionStorage.getItem(Yt);return c?JSON.parse(c):[]}catch{return[]}}},Oa=[{upTo:55867,rate:.15},{upTo:111733,rate:.205},{upTo:173205,rate:.26},{upTo:246752,rate:.29},{upTo:1/0,rate:.33}],za=[{upTo:51780,rate:.14},{upTo:103545,rate:.19},{upTo:126e3,rate:.24},{upTo:1/0,rate:.2575}],$a={basicPersonalFederal:15700,basicPersonalQuebec:17800,ageAmountFederal:8200,ageAmountQuebec:3200,pensionAmountFederal:2e3,pensionAmountQuebec:2e3,federalCreditRate:.15,quebecCreditRate:.15},La={eligible:{grossUp:.38,fedCredit:.1502,qcCredit:.11},nonEligible:{grossUp:.15,fedCredit:.091,qcCredit:.04}},qa={recoveryStart:93e3,recoveryRate:.15},Ga={baseAnnual:12e3,reductionRate:.5},Ha={federalBrackets:Oa,quebecBrackets:za,credits:$a,dividends:La,oas:qa,gis:Ga,capitalGainsInclusion:.5};function ue(c,e){return new Intl.NumberFormat(e==="fr"?"fr-CA":"en-CA",{style:"currency",currency:"CAD",maximumFractionDigits:0}).format(c)}class Wi{static async generateSummary(e){const t=e.language,r=t==="fr",s=new ce({unit:"mm",format:"letter"});s.setFillColor(245,247,255),s.rect(0,0,215.9,279.4,"F"),s.setFontSize(22),s.setTextColor(31,41,55),s.text(r?"Optimisation fiscale — Résumé":"Tax Optimization — Summary",108,50,{align:"center"}),s.setFontSize(12),s.setTextColor(75,85,99);const n=r?`Client: ${e.clientName||"—"} | Horizon: ${e.horizonYears} ans | Besoin net annuel: ${ue(e.targetNetAnnual,t)}`:`Client: ${e.clientName||"—"} | Horizon: ${e.horizonYears} years | Net annual need: ${ue(e.targetNetAnnual,t)}`;s.text(n,108,64,{align:"center"});let a=88;if(s.setFontSize(16),s.setTextColor(31,41,55),s.text(r?"Impôts totaux (horizon)":"Total taxes (horizon)",20,a),a+=10,s.setFontSize(12),s.setTextColor(55,65,81),e.greedy&&(s.text(`• Greedy: ${ue(e.greedy.totalTax,t)}`,24,a),a+=6),e.dp){const u=e.dp.score!=null?` — ${r?"Score plan":"Plan score"}: ${Math.round(e.dp.score)}`:"";s.text(`• DP/Beam: ${ue(e.dp.totalTax,t)}${u}`,24,a),a+=6}e.baseline&&(s.text(`• ${r?"RRSP seulement":"RRSP only"}: ${ue(e.baseline.totalTax,t)}`,24,a),a+=8),s.setFontSize(16),s.setTextColor(31,41,55),s.text(r?"Robustesse (scénarios chocs)":"Robustness (shock scenarios)",20,a),a+=10,s.setFontSize(12),s.setTextColor(55,65,81);const i=(u,m)=>{if(!m)return;const d=`• ${u}: Score ${m.robustScore} — seq:${m.sequence.shortfallYears} inf:${m.inflation.shortfallYears} lon:${m.longevity.shortfallYears}`,p=s.splitTextToSize(d,175);s.text(p,24,a),a+=p.length*5+2};i("Greedy",e.greedy?.robust),i("DP/Beam",e.dp?.robust),i(r?"RRSP seulement":"RRSP only",e.baseline?.robust),a+=6;const l=[{name:"DP/Beam",r:e.dp?.robust},{name:"Greedy",r:e.greedy?.robust},{name:r?"RRSP seulement":"RRSP only",r:e.baseline?.robust}].filter(u=>u.r);if(l.length>0){l.sort((m,d)=>m.r.robustScore-d.r.robustScore);const u=l[0];s.setFontSize(16),s.setTextColor(31,41,55),s.text(r?`Explications (plan le plus robuste: ${u.name})`:`Explanations (most robust plan: ${u.name})`,20,a),a+=10,s.setFontSize(11),s.setTextColor(75,85,99),u.r.explanations.forEach(m=>{a>270&&(s.addPage(),a=20);const d=s.splitTextToSize("• "+m,175);s.text(d,24,a),a+=d.length*5+2})}if(e.mc){a>250&&(s.addPage(),a=20),s.setFontSize(16),s.setTextColor(31,41,55),s.text(r?"Monte Carlo (aperçu)":"Monte Carlo (overview)",20,a),a+=10,s.setFontSize(12),s.setTextColor(55,65,81);const u=r?"Prob. succès":"Success prob",m="P5",d="P50",p="P95",x=r?"Drawdown max":"Max drawdown",E=e.mc.iterations?` — ${e.mc.iterations} itérations`:"",v=e.mc.horizonYears?` — Horizon: ${e.mc.horizonYears} ${r?"ans":"years"}`:"",f=`• ${u}: ${Math.round(e.mc.successProb*100)}% | ${m}: ${ue(e.mc.p5,t)} | ${d}: ${ue(e.mc.p50,t)} | ${p}: ${ue(e.mc.p95,t)} | ${x}: ${ue(e.mc.maxDrawdown,t)}${E}${v}`,g=s.splitTextToSize(f,175);s.text(g,24,a),a+=g.length*5+4}if(e.stress){a>250&&(s.addPage(),a=20),s.setFontSize(16),s.setTextColor(31,41,55),s.text("Stress tests (scores)",20,a),a+=10,s.setFontSize(12),s.setTextColor(55,65,81);const u=r?"Séquence":"Sequence",m="Inflation",d=r?"Longévité":"Longevity",p=`• ${u}: ${e.stress.sequence}/100 | ${m}: ${e.stress.inflation}/100 | ${d}: ${e.stress.longevity}/100`,x=s.splitTextToSize(p,175);s.text(x,24,a),a+=x.length*5+4}s.setFontSize(8),s.setTextColor(107,114,128);const o=new Date().toLocaleDateString(t==="fr"?"fr-CA":"en-CA");return s.text(`${r?"Généré le":"Generated on"} ${o} — MonPlanRetraite.ca`,108,272,{align:"center"}),s.output("blob")}}const pe=Ha;function xs(c,e){let t=0,r=0;for(const s of e){const n=s.upTo,a=Math.max(0,Math.min(c,n)-r);if(t+=a*s.rate,r=n,c<=n)break}return t}function ms(c,e,t){const r=e*t,s=Math.min(r,Math.max(0,c));return{creditApplied:s,taxAfter:Math.max(0,c-s)}}function Ua(c,e,t){return Math.max(e,Math.min(t,c))}function Wa(c){const e=pe,t=Math.max(0,Number(c.ordinaryIncome)||0)+Math.max(0,Number(c.rrspWithdrawals)||0)+Math.max(0,Number(c.rrifWithdrawals)||0)+Math.max(0,Number(c.eligiblePensionIncome)||0),r=Math.max(0,Number(c.cpp)||0),s=Math.max(0,Number(c.oas)||0),n=Math.max(0,Number(c.eligibleDividends)||0),a=Math.max(0,Number(c.nonEligibleDividends)||0),i=n*(1+e.dividends.eligible.grossUp),l=a*(1+e.dividends.nonEligible.grossUp),o=Math.max(0,Number(c.capitalGains)||0),u=o*e.capitalGainsInclusion;return{grossIncome:t+n+a+o+r+s,ordinary:t,eligibleDivGrossed:i,nonEligibleDivGrossed:l,capGainsTaxable:u,cpp:r,oas:s}}function fs(c,e,t,r="federal"){const s=pe.credits,n=(r==="federal"?s.basicPersonalFederal:s.basicPersonalQuebec)+(e&&e>=65?r==="federal"?s.ageAmountFederal:s.ageAmountQuebec:0)+(t&&t>0?r==="federal"?s.pensionAmountFederal:s.pensionAmountQuebec:0);if(e&&e>=65&&r==="federal"&&c>42e3){const l=Ua(1-(c-42e3)/58e3,0,1),o=s.ageAmountFederal*(1-l);return Math.max(0,n-o)}return Math.max(0,n)}function ja(c,e){const t=pe.dividends,r=c*t.eligible.fedCredit+e*t.nonEligible.fedCredit,s=c*t.eligible.qcCredit+e*t.nonEligible.qcCredit;return{federal:r,qc:s}}function Va(c){const e=pe.oas,t=c.ordinary+c.eligibleDivGrossed+c.nonEligibleDivGrossed+c.capGainsTaxable+c.cpp+c.oas;if(t<=e.recoveryStart)return 0;const s=(t-e.recoveryStart)*e.recoveryRate;return Math.min(s,c.oas)}function Ya(c){const e=pe.gis,t=c.ordinary+c.eligibleDivGrossed+c.nonEligibleDivGrossed+c.capGainsTaxable+c.cpp;return Math.max(0,e.baseAnnual-e.reductionRate*t)}function be(c){const e=c.age??70;if(c.status,(c.province??"QC")!=="QC")throw new Error("Only QC policy is configured in v1.");const r=Wa(c),s=r.ordinary+r.eligibleDivGrossed+r.nonEligibleDivGrossed+r.capGainsTaxable+r.cpp+r.oas,n=r.ordinary+r.eligibleDivGrossed+r.nonEligibleDivGrossed+r.capGainsTaxable+r.cpp+r.oas,a=xs(s,pe.federalBrackets),i=xs(n,pe.quebecBrackets),l=fs(s,e,c.eligiblePensionIncome,"federal"),o=fs(n,e,c.eligiblePensionIncome,"qc"),u=ms(a,l,pe.credits.federalCreditRate),m=ms(i,o,pe.credits.quebecCreditRate),d=ja(r.eligibleDivGrossed,r.nonEligibleDivGrossed),p=Math.max(0,u.taxAfter-d.federal),x=Math.max(0,m.taxAfter-d.qc),E=Va(r),v=Ya(r),f=p+x+E-v,g=r.ordinary+c.eligiblePensionIncome+r.cpp+(r.oas-E)+(c.eligibleDividends||0)+(c.nonEligibleDividends||0)+(c.capitalGains||0)-(p+x)+v;return{taxableFederal:s,taxableQuebec:n,federalTaxBeforeCredits:a,quebecTaxBeforeCredits:i,nonRefundableCreditsAppliedFed:u.creditApplied,nonRefundableCreditsAppliedQc:m.creditApplied,federalTaxAfterCredits:p,quebecTaxAfterCredits:x,oasClawback:E,gisBenefit:v,totalTax:f,netIncome:g,breakdown:{grossIncome:r.grossIncome,ordinary:r.ordinary,eligibleDividends:c.eligibleDividends||0,nonEligibleDividends:c.nonEligibleDividends||0,capitalGainsRealized:c.capitalGains||0,capitalGainsTaxablePortion:r.capGainsTaxable,cpp:r.cpp,oasGross:r.oas}}}function Ka(c,e=100){const t=be(c),r=be({...c,ordinaryIncome:Math.max(0,(c.ordinaryIncome||0)+e)}),s=r.totalTax-t.totalTax;return{base:t,withDelta:r,marginalRate:s/e}}function Qa(c,e){const t=e.grossReturnTFSA??.04,r=e.grossReturnNonReg??.04,s=e.grossReturnRRSP??.04,n=e.grossReturnRRIF??.04;return{tfsa:c.tfsa*(1+t),nonRegistered:c.nonRegistered*(1+r),rrsp:c.rrsp*(1+s),rrif:c.rrif*(1+n),cppAnnual:c.cppAnnual,oasAnnual:c.oasAnnual}}function We(c,e){const t=Math.max(0,e||0),r=Math.min(c,t);return[r,c-r]}function Bs(c,e,t,r,s){let n=Qa(t,s);const[a,i]=We(n.tfsa,r.withdrawTFSA||0),[l,o]=We(n.nonRegistered,r.withdrawNonReg||0),[u,m]=We(n.rrsp,r.withdrawRRSP||0),[d,p]=We(n.rrif,r.withdrawRRIF||0);let x=n.cppAnnual||0,E=n.oasAnnual||0;r.startCPP&&(s.includeCPP??!0)&&(x=x>0?x:9600),r.startOAS&&(s.includeOAS??!0)&&(E=E>0?E:8400);const v=s.province??"QC",f=u+d+0+0,g=0,h=0,A=0,y=(r.withdrawNonReg||0)*(s.nonRegCapitalGainsRatio??.25),C={ordinaryIncome:f,eligiblePensionIncome:g,cpp:x,oas:E,eligibleDividends:h,nonEligibleDividends:A,capitalGains:y,age:e,province:v},S=be(C),F={tfsa:i,nonRegistered:o,rrsp:m,rrif:p,cppAnnual:x,oasAnnual:E},w=Ka(C,100).marginalRate;return{yearIndex:c,age:e,openingBalances:t,decisions:{withdrawTFSA:a,withdrawNonReg:l,withdrawRRSP:u,withdrawRRIF:d,startCPP:!!r.startCPP,startOAS:!!r.startOAS},tax:{totalTax:S.totalTax,netIncome:S.netIncome,oasClawback:S.oasClawback,gisBenefit:S.gisBenefit,taxableFederal:S.taxableFederal,taxableQuebec:S.taxableQuebec},incomeBreakdown:{ordinaryIncome:C.ordinaryIncome,eligiblePensionIncome:0,cpp:x,oas:E,dividendsEligible:h,dividendsNonEligible:A,capitalGains:y},closingBalances:F,mtrApprox:w}}function ji(c,e,t,r){const s=[];let n={...c};for(let a=0;a0&&(p+=1),(y.mtrApprox||0)>=.45&&(x+=1)}return{score:m+5e3*d+1e3*p+500*x,totalTax:Math.round(m),shortfallYears:d,clawbackYears:p,highMTRYears:x,results:u}}function Ja(c,e,t,r){const s=r==="fr",n=[];c.shortfallYears>0&&n.push(s?`Séquence négative: ${c.shortfallYears} an(s) sous l'objectif net (prioriser coussin et limiter retraits imposables).`:`Negative sequence: ${c.shortfallYears} year(s) below target net (prioritize cash cushion and limit taxable withdrawals).`),c.highMTRYears>0&&n.push(s?`Pics de taux marginaux sous choc: ${c.highMTRYears} an(s) ≥ 45%.`:`Marginal rate spikes under shock: ${c.highMTRYears} year(s) ≥ 45%.`),e.shortfallYears>0&&n.push(s?`Inflation élevée: ${e.shortfallYears} an(s) sous l'objectif (prévoir indexation du besoin net).`:`High inflation: ${e.shortfallYears} year(s) below target (index the net need).`),t.shortfallYears>0&&n.push(s?`Longévité +5 ans: ${t.shortfallYears} an(s) sous l'objectif (renforcer durabilité des retraits).`:`Longevity +5y: ${t.shortfallYears} year(s) below target (reinforce withdrawal sustainability).`);const a=c.clawbackYears+e.clawbackYears+t.clawbackYears;return a>0&&n.push(s?`Récupération SV présente dans ${a} cas (lisser les retraits pour rester sous le seuil).`:`OAS clawback present in ${a} cases (smooth withdrawals to stay under threshold).`),n.length===0&&n.push(s?"Plan robuste dans les trois scénarios testés.":"Plan robust across the three tested scenarios."),n}function Vi(c,e="fr"){const{opening:t,assumptions:r,decisions:s,horizonYears:n,targetNetAnnual:a}=c,i=qt(t,r,s,n,a,"sequence"),l=qt(t,r,s,n,a,"inflation"),o=qt(t,r,s,n,a,"longevity"),u=Math.round((i.score+l.score+o.score)/3),m=Ja(i,l,o,e);return{sequence:i,inflation:l,longevity:o,robustScore:u,explanations:m}}class Yi{static optimize(e){const{opening:t,assumptions:r,horizonYears:s,targetNetAnnual:n,startCPPAt:a=70,startOASAt:i=70}=e,l=[];let o={...t};const u=r.province??"QC",m=r.includeCPP??!0,d=r.includeOAS??!0;for(let p=0;p=a&&!o.cppAnnual,v=d&&x>=i&&!o.oasAnnual,g=be(It(0,0,x,u,o)).netIncome;let h=Math.max(0,n-g),A=Math.min(o.nonRegistered,h);h-=A;let y=0;if(h>0&&o.rrsp>0){y=Xa(h,x,u,o),y=Math.min(y,o.rrsp);const w=be(It(y,0,x,u,o)).netIncome-g;h=Math.max(0,h-w)}let C=0;h>0&&o.tfsa>0&&(C=Math.min(o.tfsa,h),h-=C),l.push({yearIndex:p,withdrawTFSA:C,withdrawNonReg:A,withdrawRRSP:y,withdrawRRIF:0,startCPP:E,startOAS:v}),o={tfsa:Math.max(0,o.tfsa-C),nonRegistered:Math.max(0,o.nonRegistered-A),rrsp:Math.max(0,o.rrsp-y),rrif:o.rrif,cppAnnual:E?o.cppAnnual||9600:o.cppAnnual,oasAnnual:v?o.oasAnnual||8400:o.oasAnnual}}return l}}function It(c,e,t,r,s){return{ordinaryIncome:c+e,eligiblePensionIncome:0,cpp:s.cppAnnual||0,oas:s.oasAnnual||0,eligibleDividends:0,nonEligibleDividends:0,capitalGains:0,age:t,province:r}}function Xa(c,e,t,r){const s=be(It(0,0,e,t,r)).netIncome;let n=0,a=Math.max(1e3,r.rrsp);const i=1;let l=0;for(let o=0;o<24;o++){const u=(n+a)/2,d=be(It(u,0,e,t,r)).netIncome-s;if(Math.abs(d-c)<=i){l=u;break}d{l.has(u)||(l.add(u),o.push(u))}),o.length>0?o:["NON_ENREGISTRE","REER","CELI"]}static buildMonthlySchedule(e,t,r){const s=[],n=Math.max(0,Number(t)||0);if(n===0||r.length===0)return{scenarioId:e,period:"monthly",entries:s};const a=ge.computeSimpleAllocation(r),i=new Date;for(let l=0;l<12;l++){const u=new Date(i.getFullYear(),i.getMonth()+l,1).toISOString().split("T")[0];a.forEach(({source:m,weight:d})=>{const p=+(n*d).toFixed(2);p>0&&s.push({dateISO:u,source:m,gross:p,net:p,notes:ge.noteForSource(m)})})}return{scenarioId:e,period:"monthly",entries:s}}static computeSimpleAllocation(e){const t=Array.from(new Set(e));return t.length===1?[{source:t[0],weight:1}]:t.length===2?t.map(r=>({source:r,weight:.5})):t.slice(0,3).map(r=>({source:r,weight:1/3}))}static noteForSource(e){switch(e){case"NON_ENREGISTRE":return"Prioriser le non-enregistré peut réduire l'impôt futur sur les placements.";case"REER":return"Utiliser le REER avant 71 ans peut réduire les retraits minimums futurs du FERR.";case"CELI":return"Le CELI est souvent préservé en dernier pour sa croissance à l'abri de l'impôt.";case"RRIF":return"Respectez les retraits minimums du FERR; ajustez au besoin.";case"CRI":case"LIF":return"Tenez compte des contraintes CRI/LIF; vérifiez les limites applicables.";case"PENSION":return"Les rentes privées suivent des modalités fixes; ajustez votre budget en conséquence.";default:return"Estimation pédagogique (non contraignante)."}}static hasAny(e,t){try{const r=JSON.stringify(e||{}).toLowerCase();return t.some(s=>r.includes(s.toLowerCase()))}catch{return!1}}}class hs{static generateSuggestedFilename(){const e=new Date,t=e.toISOString().split("T")[0],r=e.toTimeString().split(" ")[0].replace(/:/g,"h").substring(0,5);return`${this.DEFAULT_PREFIX}-${t}-${r}.json`}static getAllStorageData(){const e=Y.keys(),t={};e.forEach(n=>{try{const a=Y.getItem(n);a!==null&&(t[n]=a)}catch{}});const r=["user_profile","retirement_data","savings_data","income_data","expenses_data","assumptions_data","onboarding_completed","language_preference"],s={};return r.forEach(n=>{try{const a=localStorage.getItem(n);a&&(s[n]=JSON.parse(a))}catch{}}),{secureData:t,regularData:s,exportTimestamp:new Date().toISOString(),version:"1.0",appName:"Mon Plan Retraite"}}static calculateDataSize(e){try{const t=JSON.stringify(e),r=new Blob([t]).size;return r<1024?`${r} octets`:r<1024*1024?`${Math.round(r/1024)} KB`:`${Math.round(r/(1024*1024))} MB`}catch{return"0 octets"}}static saveLastSaveInfo(e,t){const r={filename:e,location:t,timestamp:new Date().toISOString()};try{localStorage.setItem(this.LAST_SAVE_KEY,JSON.stringify(r))}catch{}}static getLastSaveInfo(){try{const e=localStorage.getItem(this.LAST_SAVE_KEY);return e?JSON.parse(e):null}catch{return null}}static clearAllStorageData(e=!0){const t=e?this.getLastSaveInfo():null;Y.clear();const r=["theme","locale","debug_mode",...e?[this.LAST_SAVE_KEY]:[]];Object.keys(localStorage).forEach(n=>{r.includes(n)||localStorage.removeItem(n)}),e&&t&&this.saveLastSaveInfo(t.filename,t.location)}static async transferToLocalFile(e={}){try{const t=this.getAllStorageData(),r=this.calculateDataSize(t);if(Object.keys(t.secureData).length===0&&Object.keys(t.regularData).length===0)return{success:!1,error:"Aucune donnée à sauvegarder dans le localStorage"};const s=e.suggestedFilename||this.generateSuggestedFilename(),n={...t,description:e.description||"Sauvegarde complète des données de plan de retraite",exportInfo:{totalDataSize:r,exportDate:new Date().toLocaleString("fr-CA"),secureDataKeys:Object.keys(t.secureData),regularDataKeys:Object.keys(t.regularData)}};if("showSaveFilePicker"in window)try{const a=await window.showSaveFilePicker({suggestedName:s,types:[{description:"Fichier de sauvegarde Mon Plan Retraite",accept:{"application/json":[".json"]}}]}),i=await a.createWritable(),l=JSON.stringify(n,null,2);return await i.write(l),await i.close(),this.saveLastSaveInfo(a.name,"Emplacement choisi par l'utilisateur"),this.clearAllStorageData(e.preserveLastSaveInfo!==!1),{success:!0,filename:a.name,dataSize:r}}catch(a){if(a.name==="AbortError")return{success:!1,cancelled:!0,error:"Sauvegarde annulée par l'utilisateur"};throw a}else{const a=JSON.stringify(n,null,2),i=new Blob([a],{type:"application/json"}),l=URL.createObjectURL(i),o=document.createElement("a");return o.href=l,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(l),this.saveLastSaveInfo(s,"Dossier Téléchargements"),this.clearAllStorageData(e.preserveLastSaveInfo!==!1),{success:!0,filename:s,dataSize:r}}}catch(t){return{success:!1,error:`Erreur lors du transfert : ${t instanceof Error?t.message:"Erreur inconnue"}`}}}static previewTransferData(){const e=this.getAllStorageData(),t=Object.keys(e.secureData),r=Object.keys(e.regularData);return{totalKeys:t.length+r.length,secureKeys:t,regularKeys:r,estimatedSize:this.calculateDataSize(e),hasData:t.length>0||r.length>0}}static async loadFromLocalFile(e){try{const t=await e.text(),r=JSON.parse(t);if(!r.version||!r.appName||r.appName!=="Mon Plan Retraite")throw new Error("Format de fichier non reconnu ou invalide");const s=[];return r.secureData&&typeof r.secureData=="object"&&Object.entries(r.secureData).forEach(([n,a])=>{try{Y.setItem(n,a),s.push(`secure:${n}`)}catch{}}),r.regularData&&typeof r.regularData=="object"&&Object.entries(r.regularData).forEach(([n,a])=>{try{localStorage.setItem(n,JSON.stringify(a)),s.push(`regular:${n}`)}catch{}}),{success:!0,loadedKeys:s}}catch(t){return{success:!1,error:`Erreur lors du chargement : ${t instanceof Error?t.message:"Fichier invalide"}`}}}static clearAllData(e=!1){this.clearAllStorageData(!e)}}L(hs,"LAST_SAVE_KEY","last_save_info"),L(hs,"DEFAULT_PREFIX","plan-retraite");class Ki{static getAssumptions(){return{inflation:Ie.INFLATION,stockReturns:Ie.ACTIONS_CANADIENNES,bondReturns:Ie.REVENU_FIXE,salaryGrowth:Ie.CROISSANCE_SALAIRE,source:Ie.SOURCE,lastUpdated:"Janvier 2025"}}static getTooltips(){return{inflation:{title:"Inflation",description:"Hausse générale des prix chaque année",example:"100 $ aujourd'hui = 102,10 $ l'an prochain",icon:"📈"},stockReturns:{title:"Actions canadiennes",description:"Rendement moyen attendu des actions",example:"10 000 $ pourrait valoir 66 200 $ après 30 ans",icon:"📊"},bondReturns:{title:"Obligations",description:"Rendement des prêts gouvernementaux",example:"Plus stable que les actions, croissance plus lente",icon:"🏛️"},salaryGrowth:{title:"Croissance des salaires",description:"Augmentation moyenne des salaires",example:"50 000 $ aujourd'hui = 126 000 $ dans 30 ans",icon:"💰"}}}static formatPercentage(e){return`${(e*100).toFixed(1).replace(".",",")} %`}static getTransparencyNotification(e){return{context:e,message:{retirement:"Cette projection utilise un taux d'inflation de 2,1 % selon les normes IPF 2025",investment:"Rendement des actions canadiennes : 6,6 % (norme IPF 2025)",budget:"Croissance des salaires : 3,1 % par année (norme IPF 2025)",general:"Calculs basés sur les standards professionnels IPF 2025"}[e],detailsLink:"/hypotheses"}}static calculateInflationImpact(e,t){const r=this.getAssumptions();return e*Math.pow(1+r.inflation,t)}static calculateStockGrowth(e,t){const r=this.getAssumptions();return e*Math.pow(1+r.stockReturns,t)}static calculateBondGrowth(e,t){const r=this.getAssumptions();return e*Math.pow(1+r.bondReturns,t)}static calculateSalaryGrowth(e,t){const r=this.getAssumptions();return e*Math.pow(1+r.salaryGrowth,t)}static getEducationalExamples(){return{inflation:{title:"Impact de l'inflation",examples:[{description:"Panier d'épicerie de 100 $ aujourd'hui",result:`${this.formatPercentage(.021)} = 102,10 $ l'an prochain`},{description:"Coût de la vie dans 10 ans",result:`100 $ aujourd'hui = ${Math.round(this.calculateInflationImpact(100,10))} $ dans 10 ans`}]},stocks:{title:"Croissance des actions",examples:[{description:"Placement de 10 000 $ en actions",result:`Pourrait valoir ${Math.round(this.calculateStockGrowth(1e4,30)).toLocaleString("fr-CA")} $ après 30 ans`},{description:"REER de 1 000 $ par année",result:"Pourrait accumuler plus de 100 000 $ en 20 ans"}]},bonds:{title:"Sécurité des obligations",examples:[{description:"Placement de 10 000 $ en obligations",result:`Pourrait valoir ${Math.round(this.calculateBondGrowth(1e4,30)).toLocaleString("fr-CA")} $ après 30 ans`},{description:"Moins de risque que les actions",result:"Croissance plus lente mais plus prévisible"}]},salary:{title:"Évolution des salaires",examples:[{description:"Salaire de 50 000 $ aujourd'hui",result:`Pourrait être ${Math.round(this.calculateSalaryGrowth(5e4,30)).toLocaleString("fr-CA")} $ dans 30 ans`},{description:"Augmentation annuelle moyenne",result:`${this.formatPercentage(Ie.CROISSANCE_SALAIRE)} par année`}]}}}static validateAssumptions(){const e=this.getAssumptions(),t=[];return e.stockReturns<=e.bondReturns&&t.push("Les actions devraient avoir un rendement supérieur aux obligations"),e.salaryGrowth<=e.inflation&&t.push("La croissance des salaires devrait dépasser l'inflation"),(e.inflation<.01||e.inflation>.05)&&t.push("Le taux d'inflation semble inhabituel"),{isValid:t.length===0,warnings:t}}static getAssumptionsSummary(){const e=this.getAssumptions();return`Hypothèses utilisées (${e.source}) : • Inflation : ${this.formatPercentage(e.inflation)} • Actions canadiennes : ${this.formatPercentage(e.stockReturns)} • Obligations : ${this.formatPercentage(e.bondReturns)} • Croissance des salaires : ${this.formatPercentage(e.salaryGrowth)} Ces hypothèses sont conformes aux standards professionnels de l'Institut de planification financière.`}}class Qi{static analyzeProperty(e){const t=e.revenusLocatifsAnnuels-this.calculateTotalExpenses(e.depensesAnnuelles),r=e.revenusLocatifsAnnuels/e.valeurMarchande*100,s=t/e.valeurMarchande*100,n=t*.35,a=t-n,i=e.valeurMarchande-e.coutBaseAjuste,l=Math.min(e.amortissementCumule,i),o=Math.max(0,i-e.amortissementCumule),u=this.calculatePropertyProjections(e,10);return{rendements:{brut:r,net:s,apresImpot:a/e.valeurMarchande*100},fiscalite:{plusValueBrute:i,recupAmortissement:l,gainEnCapitalNet:o,gainEnCapitalImposable:o*.5,impotEstime:o*.5*.35},projections:{valeur10ans:u.valeurFuture,revenus10ans:u.revenusFuturs,rendement10ans:u.rendementFutur},fluxTresorerie:{annuel:t,apresImpot:a,mensuel:a/12}}}static generateSaleScenarios(e,t,r){const s=this.analyzeProperty(e),n=[],a={nom:"Vente Comptant",type:"COMPTANT",gainEnCapital:s.fiscalite.gainEnCapitalNet,recupAmortissement:s.fiscalite.recupAmortissement,impotTotalDu:s.fiscalite.impotEstime,liquiditeNette:e.valeurMarchande-s.fiscalite.impotEstime,strategies:this.generateReinvestmentStrategies(e.valeurMarchande-s.fiscalite.impotEstime,t,r)};if(n.push(a),s.fiscalite.gainEnCapitalNet>1e5){const i={nom:"Réserve d'Épargne Étalée",type:"RESERVE_ETALEE",gainEnCapital:s.fiscalite.gainEnCapitalNet,recupAmortissement:s.fiscalite.recupAmortissement,impotTotalDu:s.fiscalite.impotEstime*.8,liquiditeNette:e.valeurMarchande-s.fiscalite.impotEstime*.8,nombreAnneesEtalement:5,economieImpotEtalement:s.fiscalite.impotEstime*.2,strategies:this.generateReinvestmentStrategies(e.valeurMarchande-s.fiscalite.impotEstime*.8,t,r)};n.push(i)}if(this.isEchange44Eligible(e,r)){const i={nom:"Échange 44",type:"ECHANGE_44",gainEnCapital:0,recupAmortissement:0,impotTotalDu:0,liquiditeNette:e.valeurMarchande,strategies:this.generateReinvestmentStrategies(e.valeurMarchande,t,r)};n.push(i)}return n}static generateReinvestmentStrategies(e,t,r){const s=[];if(t.anneesManquantes>0&&e>=t.coutRachatParAnnee){const a=Math.min(t.anneesManquantes,Math.floor(e/t.coutRachatParAnnee)),i={nom:`Rachat RREGOP (${a} années)`,type:"RREGOP_RACHAT",montantAlloue:a*t.coutRachatParAnnee,rendementEscompte:8.5,avantagesFiscaux:["Déduction d'impôt immédiate","Pension viagère garantie","Indexation automatique","Protection contre l'inflation"],risques:["Aucun - Garantie gouvernementale"],impactRetraite:{pensionAnnuelle:a*t.impactPensionViagere*12,ageRetraite:t.ageRetraitePrevu,securiteFinanciere:10}};s.push(i)}const n=e-(s[0]?.montantAlloue||0);if(n>0){const a={nom:"REER/CELI Mixte",type:"REER_CELI",montantAlloue:n*.6,rendementEscompte:6.5,avantagesFiscaux:["Déduction d'impôt REER","Croissance à l'abri de l'impôt CELI","Flexibilité de retrait"],risques:["Volatilité des marchés","Taux de rendement variable"],impactRetraite:{pensionAnnuelle:n*.6*.04,ageRetraite:t.ageRetraitePrevu,securiteFinanciere:7}};s.push(a)}if(n>0){const a={nom:"Portefeuille Diversifié",type:"PORTEFEUILLE",montantAlloue:n*.4,rendementEscompte:7,avantagesFiscaux:["Diversification géographique","Croissance à long terme","Liquidité"],risques:["Volatilité","Risque de marché","Inflation"],impactRetraite:{pensionAnnuelle:n*.4*.05,ageRetraite:t.ageRetraitePrevu+2,securiteFinanciere:6}};s.push(a)}return s}static compareScenarios(e){if(e.length===0)return{scenarios:[],meilleurScenario:{},analyseRisque:{liquidite:0,fiscalite:0,rendement:0,securite:0},recommandation:"Aucun scénario disponible"};const t=e.map(s=>{const n=Math.min(10,s.liquiditeNette/1e5*10),a=Math.max(1,10-s.impotTotalDu/5e4*10),i=this.calculateRendementScore(s),l=this.calculateSecuriteScore(s),o=(n+a+i+l)/4;return{...s,scoreTotal:o}});t.sort((s,n)=>(n.scoreTotal||0)-(s.scoreTotal||0));const r=t[0];return{scenarios:t,meilleurScenario:r,analyseRisque:{liquidite:Math.min(10,r.liquiditeNette/1e5*10),fiscalite:Math.max(1,10-r.impotTotalDu/5e4*10),rendement:this.calculateRendementScore(r),securite:this.calculateSecuriteScore(r)},recommandation:this.generateRecommendation(r)}}static generateExecutionPlan(e,t){return{etapes:[{ordre:1,titre:"Évaluation de la propriété",description:"Obtenir une évaluation professionnelle à jour",duree:"2-3 semaines",responsable:"Évaluateur immobilier",statut:"A_FAIRE",notes:"Important pour optimiser le prix de vente"},{ordre:2,titre:"Consultation fiscale",description:"Analyser les implications fiscales avec un expert-comptable",duree:"1-2 semaines",responsable:"Comptable/Conseiller fiscal",statut:"A_FAIRE",notes:"Optimiser la stratégie de vente"},{ordre:3,titre:"Préparation de la vente",description:"Mise en marché et préparation des documents",duree:"4-8 semaines",responsable:"Courtier immobilier",statut:"A_FAIRE",notes:"Inclure les améliorations mineures si rentables"},{ordre:4,titre:"Négociation et vente",description:"Processus de vente et finalisation",duree:"2-4 semaines",responsable:"Courtier immobilier",statut:"A_FAIRE",notes:"Négocier les conditions optimales"},{ordre:5,titre:"Réinvestissement RREGOP",description:"Procéder au rachat d'années RREGOP",duree:"2-4 semaines",responsable:"Conseiller RREGOP",statut:"A_FAIRE",notes:"Priorité absolue - délais stricts"},{ordre:6,titre:"Placement des fonds restants",description:"Exécuter la stratégie de réinvestissement",duree:"2-3 semaines",responsable:"Conseiller financier",statut:"A_FAIRE",notes:"Diversifier selon le profil de risque"}],timeline:{debut:"Maintenant",fin:"8-12 semaines",duree:"2-3 mois"},contacts:[{nom:"Conseiller RREGOP",role:"Spécialiste RREGOP",telephone:"514-555-0123",email:"rregop@gouv.qc.ca",specialite:"Rachat d'années RREGOP"},{nom:"Conseiller fiscal",role:"Comptable/Conseiller fiscal",telephone:"514-555-0124",email:"fiscal@expertise.ca",specialite:"Optimisation fiscale immobilière"},{nom:"Courtier immobilier",role:"Vente immobilière",telephone:"514-555-0125",email:"vente@immobilier.ca",specialite:"Vente de propriétés à revenus"}],documents:[{nom:"Évaluation immobilière",type:"EVALUATION",statut:"REQUIS",dateLimite:"2 semaines"},{nom:"Analyse fiscale détaillée",type:"FISCAL",statut:"REQUIS",dateLimite:"2 semaines"},{nom:"Contrat de vente",type:"CONTRAT",statut:"REQUIS",dateLimite:"6 semaines"},{nom:"Formulaire de rachat RREGOP",type:"LEGAL",statut:"REQUIS",dateLimite:"8 semaines"}],checklist:["Évaluation immobilière obtenue","Consultation fiscale effectuée","Propriété mise en marché","Vente finalisée","Rachat RREGOP effectué","Fonds restants placés"]}}static calculateTotalExpenses(e){return Object.values(e).reduce((t,r)=>t+r,0)}static calculatePropertyProjections(e,t){const r=e.valeurMarchande*Math.pow(1+e.appreciationAnnuelle/100,t),s=e.revenusLocatifsAnnuels*Math.pow(1+e.augmentationLoyersAnnuelle/100,t),n=s/r*100;return{valeurFuture:r,revenusFuturs:s,rendementFutur:n}}static isEchange44Eligible(e,t){return e.typeProprieteDuplex==="DUPLEX"&&t?.hasReplacementProperty}static calculateRendementScore(e){const t=Math.min(10,e.liquiditeNette/1e5*10),r=e.strategies.reduce((s,n)=>s+n.rendementEscompte,0)/e.strategies.length;return Math.min(10,(t+r)/2)}static calculateSecuriteScore(e){return e.strategies.find(s=>s.type==="RREGOP_RACHAT")?10:e.strategies.find(s=>s.type==="REER_CELI")?7:5}static generateRecommendation(e){return e.type==="ECHANGE_44"?"Échange 44 recommandé pour éviter l'impôt immédiat et maintenir l'exposition immobilière.":e.type==="RESERVE_ETALEE"?"Réserve d'épargne étalée recommandée pour optimiser la fiscalité et étaler l'impôt sur 5 ans.":"Vente comptant recommandée pour maximiser la liquidité et permettre le réinvestissement RREGOP immédiat."}}function Pe(c){const e=Number(c);return Number.isFinite(e)?e:0}function Is(c){return c.reduce((e,t)=>e+(Number.isFinite(t)?t:0),0)}function Za(c,e){const t=c.personal||{},r=Pe(t.netMensuel);if(r>0)return r;const s=e?.incomeKeys??["salaire1","salaire2"];return Is(s.map(a=>Pe(t[a])))/12}function ei(c){const e=c.cashflow||{};return Is(["logement","servicesPublics","assurances","telecom","alimentation","transport","sante","loisirs","depensesSaisonnieres"].map(r=>Pe(e[r])))}function ti(c){const e=c;if(e.budgetSettings?.emergencyFund!=null)return Pe(e.budgetSettings.emergencyFund);const t=e.savings||{},r=["emergencyFund","fondsUrgence","liquidSavings","epargneLiquide","bankSavings","epargne1"];for(const s of r)if(t[s]!=null)return Pe(t[s]);return 0}function ri(c,e){return c>=0&&e>=3?"low":c>=0&&e>=1||c<0&&e>=2?"medium":"high"}class Ji{static analyze(e,t={}){const r=t.emergencyTargetMonths??3,s=t.minMonthlyBuffer??100,n=Za(e,t),a=ei(e),i=n-a,l=ti(e),o=r,u=Math.max(0,a)*o,m=Math.max(0,u-l),d=a>0?l/a:1/0,p=[];if(i<0){const f=Math.abs(i);p.push({id:"negative-monthly-cashflow",severity:f>=250?"error":"warning",message:`Votre flux de trésorerie mensuel est négatif de ${f.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})}.`,suggestion:"Réduisez vos dépenses essentielles/discrétionnaires et reportez les achats non urgents. Augmentez vos revenus ou ajustez le plan."})}else i0?p.push({id:"emergency-fund-shortfall",severity:i<0?"error":"warning",message:`Fonds d’urgence insuffisant de ${m.toLocaleString("fr-CA",{style:"currency",currency:"CAD"})} (cible ${r} mois).`,suggestion:"Alimentez votre fonds d’urgence en priorité (visez 3–6 mois de dépenses essentielles)."}):p.push({id:"emergency-fund-ok",severity:"info",message:`Fonds d’urgence adéquat (~${d.toFixed(1)} mois de dépenses couvertes).`});const x=e.cashflow||{},E=Pe(x.depensesSaisonnieres);E>0&&i-E/12<0&&p.push({id:"seasonal-expense-risk",severity:"warning",message:"Vos dépenses saisonnières peuvent réduire votre marge mensuelle et causer un découvert lors des périodes de pointe.",suggestion:"Utilisez des “sinking funds” mensuels pour lisser les dépenses saisonnières et éviter un choc de trésorerie."});const v=ri(i,d);return{netMonthlyIncome:n,totalMonthlyExpenses:a,monthlyCashflow:i,emergencySaved:l,emergencyTargetMonths:r,riskLevel:v,alerts:p}}}function si(c,e,t){const r=e/12;if(!isFinite(r)||Math.abs(r)<1e-9)return c/Math.max(1,t);const s=Math.pow(1+r,t);return c*(r*s)/(s-1)}function ni(c,e){const{financing:t,ownership:r}=e,s=re(t.price),n=re(t.salesTaxRate,.15),a=re(t.downPayment),i=Math.max(1,Math.floor(re(t.termMonths,60))),l=re(t.annualRate,.07),o=re(t.warrantyCost),u=re(t.registrationFees),m=s*(1+n),d=Math.max(0,m-a),p=si(d,l,i),x=Math.min(i,Math.max(1,Math.floor(c*12))),E=p*x,v=re(r.maintenancePerYear)*c,f=re(r.insurancePerYear)*c,g=re(r.fuelOrEnergyPerYear)*c,h=re(r.otherRecurringPerYear)*c,A=a+o+u,y=re(r.expectedResaleValue),C=A+E+v+f+g+h-y;return{label:e.label,monthlyPayment:je(p),upfrontCost:je(A),totalCost:je(C),monthlyTCO:je(C/Math.max(1,c*12))}}class Xi{static compare(e){const t=Math.max(1,Math.floor(e.horizonYears)),r=e.options.map(i=>ni(t,i)),s=r.slice().sort((i,l)=>i.totalCost-l.totalCost)[0],n=r.slice().sort((i,l)=>i.monthlyTCO-l.monthlyTCO)[0];let a="";return s.label===n.label?a=`Option recommandée: ${s.label} (coût total et coût mensuel les plus bas).`:a=`Option ${s.label} minimise le coût total, mais ${n.label} minimise le coût mensuel (meilleure liquidité).`,{horizonYears:t,results:r,bestByTotalCost:s,bestByMonthlyTCO:n,recommendation:a}}}function re(c,e=0){const t=Number(c);return Number.isFinite(t)?t:e}function je(c){return Math.round((c+Number.EPSILON)*100)/100}function gs(c){return Math.max(0,Math.min(1,c))}function ie(c){return Math.round((c+Number.EPSILON)*100)/100}function Jt(c){return c<60?{min:.7,max:.75}:c<=65?{min:.7,max:.75}:c<=75?{min:.65,max:.7}:c<=85?{min:.6,max:.65}:{min:.55,max:.6}}function ai(){return{canada:.275,unitedStates:.375,international:.35}}function Ts(c,e,t){const r=Jt(c),s=(r.min+r.max)/2,n={min:12,max:24};let a=.05;if(e&&t&&t>0){const u=e*n.min;a=gs(u/t),a=Math.min(a,.15)}let i=gs(1-s-a);const l={equities:ie(s),bonds:ie(i),cash:ie(1-ie(s)-ie(i))},o=["Allocation alignée sur la planification moderne (60–75 % actions).","Maintenez un coussin de 12–24 mois de dépenses essentielles en liquidités pour traverser les baisses.","Rééquilibrez annuellement et dès qu’un écart dépasse ±5 % de la cible (vendre ce qui a trop monté, acheter ce qui a baissé).","Diversification actions: CA 27,5 %, US 37,5 %, International 35 %."];return{targetAllocation:l,equityBand:r,equityGeoBreakdown:ai(),cashCushionMonths:n,notes:o}}function Zi(c,e){const t=[{asset:"equities",delta:ie(e.equities-c.equities)},{asset:"bonds",delta:ie(e.bonds-c.bonds)},{asset:"cash",delta:ie(e.cash-c.cash)}],r=e.equities+e.bonds+e.cash;if(Math.abs(r-1)>1e-6){const s=n=>n/r;e={equities:ie(s(e.equities)),bonds:ie(s(e.bonds)),cash:ie(s(e.cash))}}return{current:c,target:e,deltas:t,rule:"Rééquilibrage si écart > 5 % (points de pourcentage)."}}function Ps(c){const e=Number(c);return Number.isFinite(e)?e:0}function ii(c){const e=c?.personal?.naissance1;if(!e)return;const t=new Date(e);if(!Number.isNaN(t.getTime()))return new Date().getFullYear()-t.getFullYear()}function oi(c,e){return e.reduce((t,r)=>t+Ps(c?.[r]),0)}function ci(c){const e=c.cashflow||{};return oi(e,["logement","servicesPublics","assurances","alimentation","transport","sante"])}function li(c){const e=c.savings||{};return["reer1","reer2","celi1","celi2","placements1","placements2","epargne1","epargne2","cri1","cri2"].reduce((r,s)=>r+Ps(e[s]),0)}function ui(c){return c.includes("fail")?"fail":c.includes("warn")?"warn":"pass"}class eo{static run(e,t={}){const r=t.age??ii(e)??70,s=t.monthlyEssentialSpending??ci(e),n=t.portfolioValue??li(e),a=t.currentEquityAllocation,i=Ts(r,s,n),l=Jt(r),o=[],u=n>0?Math.min(24,Math.max(0,Math.floor(i.targetAllocation.cash*n/Math.max(1,s)))):0;let m="pass";u<6?m="fail":u<12&&(m="warn");const d=[];u<12&&d.push("Constituez un coussin de 12–24 mois de dépenses essentielles en liquidités (comptes à intérêt élevé, CPG courts)."),a!=null?al.max&&(d.push("Ramenez la poche actions dans la bande recommandée pour limiter la variabilité des deux premières années."),m!=="fail"&&(m="warn")):d.push(`Ciblez ${Math.round((l.min+l.max)/2*100)} % d’actions avec rééquilibrage annuel et bande ±5 %.`),d.push("Rééquilibrez annuellement; vendez ce qui a trop monté et achetez ce qui a baissé (discipline)."),o.push({id:"sequence",title:"Risque de séquence (-30% puis -15%)",level:m,summary:u>=12?"Coussin suffisant pour traverser 2 années défavorables sans vendre des actions.":"Coussin insuffisant pour absorber deux années défavorables sans ventes forcées.",metrics:{cashCushionMonths:u,recommendedEquityMid:((l.min+l.max)/2).toFixed(2)},suggestions:d});const p=s*Math.pow(1.08,2),x=p-s,E=Math.max(0,i.targetAllocation.cash*n/Math.max(1,12)),v=E>0?x/E:1/0;let f="pass";!Number.isFinite(v)||v>1.5?f="fail":v>.6&&(f="warn");const g=["Indexez vos retraits d’environ 3 % par an en régime normal et évitez de sur‑indexer lors des pics temporaires.","Privilégiez des actions de qualité et des secteurs résilients (santé, biens de consommation, financiers)."];f!=="pass"&&g.push("Augmentez le coussin de liquidités (vers 18–24 mois) pour amortir les pics d’inflation temporaires."),o.push({id:"inflationSpike",title:"Choc d’inflation (+8 % sur 2 ans)",level:f,summary:f==="pass"?"Coussin et allocation compatibles avec un pic d’inflation de 2 ans.":"Pic d’inflation stressant la marge mensuelle: ajustez le coussin et tenez la ligne de rééquilibrage.",metrics:{inflatedMonthly:Math.round(p),extraPerMonth:Math.round(x),approxMonthlyFromCash:Math.round(E)},suggestions:g});let h="pass";const A=["Pensez sur 30 ans, pas 3 mois; l’inflation ne pardonne pas."];a!=null&&(al.max)&&(h="warn",A.push("Alignez la poche actions avec la bande recommandée (60–75 % typiquement) pour préserver le pouvoir d’achat sur +5 ans.")),u<12&&(h=h==="warn"?"fail":"warn",A.push("Un coussin de 12–24 mois renforce la robustesse de fin de vie (+5 ans).")),o.push({id:"longevity",title:"Longévité +5 ans",level:h,summary:h==="pass"?"Allocation et coussin compatibles avec +5 ans de longévité.":"Ajustez la poche actions et/ou le coussin pour un horizon plus long.",metrics:{equityBandMin:l.min,equityBandMax:l.max,cashCushionMonths:u},suggestions:A});const y=ui(o.map(S=>S.level));return{scenarios:o,overall:y,notes:["Stratégie moderne: 60–75 % actions diversifiées, 25–40 % obligations, 12–24 mois de liquidités.","Rééquilibrage annuel et bande ±5 %: vendez ce qui a trop monté, achetez ce qui a baissé.","Diversification géographique: CA ~27,5 %, US ~37,5 %, International ~35 % (dans la poche actions)."]}}}function oe(c){const e=Number(c);return Number.isFinite(e)?e:0}function Xt(c){return c.reduce((e,t)=>e+(Number.isFinite(t)?t:0),0)}function di(c){const e=c?.personal?.naissance1;if(!e)return;const t=new Date(e);if(!Number.isNaN(t.getTime()))return new Date().getFullYear()-t.getFullYear()}function pi(c){const e=c.personal||{},t=oe(e.netMensuel);return t>0?t:(oe(e.salaire1)+oe(e.salaire2))/12}function ws(c){const e=c.cashflow||{};return Xt(["logement","servicesPublics","assurances","telecom","alimentation","transport","sante","loisirs","depensesSaisonnieres"].map(r=>oe(e[r])))}function xi(c){const e=c.savings||{};return Xt(["reer1","reer2","celi1","celi2","placements1","placements2","epargne1","epargne2","cri1","cri2"].map(r=>oe(e[r])))}function mi(c,e,t,r){const s=Ts(r??70,t,e);if(t<=0)return 0;const n=Math.max(0,s.targetAllocation.cash*e);return Math.floor(n/t)}function fi(c){const e=c.cashflow||{},t=ws(c);if(t<=0)return 0;const s=(oe(e.loisirs)+oe(e.depensesSaisonnieres)+oe(e.telecom))/t;return Math.max(0,Math.min(1,s))}function hi(c){return 1/(1+Math.exp(-c))}function gi(c){const e=c.savingsRate,t=Math.min(24,Math.max(0,c.cashCushionMonths)),r=Math.min(1,Math.max(0,c.equityMisalignment)),s=Math.min(1,Math.max(0,c.expenseVolatilityProxy)),n=-.5+2.2*e+.06*t-1.4*r-.8*s;return hi(n)}function vi(c){return c>=.8?"low":c>=.55?"medium":"high"}function Ai(c,e){const t=c.cashflow||{},r=oe(t.depensesSaisonnieres);let s=e;const n=.2,a=[];for(let i=1;i<=12;i++){let l=0;[12,1,2].includes(i)&&(l=-Math.min(r/6,Math.abs(e)/4));const o=-.01*s;s=(1-n)*s+n*(e+l+o);const u=Math.max(50,Math.abs(s)*.15);a.push({monthIndex:i,expected:Math.round(s),lower:Math.round(s-1.28*u),upper:Math.round(s+1.28*u)})}return a}class to{static analyze(e,t){const r=di(e)??70,s=pi(e),n=ws(e),a=s-n,i=xi(e),l=(()=>{const y=e.cashflow||{};return Xt(["logement","servicesPublics","assurances","alimentation","transport","sante"].map(S=>oe(y[S])))})(),o=mi(e,i,l,r),u=s>0?Math.max(0,a/s):0,m=Jt(r),d=(m.min+m.max)/2,p=Math.max(0,Math.min(1,oe(t?.currentEquityAllocation))),x=t?.currentEquityAllocation==null?0:Math.abs(p-d),E=fi(e),v={savingsRate:u,monthlyCashflow:Math.round(a),cashCushionMonths:o,equityMisalignment:x,expenseVolatilityProxy:E},f=gi(v),g=vi(f),h=[];u<.2&&h.push("Augmentez votre taux d’épargne vers 20 % (réduire dépenses discrétionnaires, optimiser factures)."),o<12&&h.push("Constituez un coussin de 12–24 mois de dépenses essentielles en liquidités."),t?.currentEquityAllocation!=null&&x>.05&&h.push("Alignez progressivement la poche actions dans la bande recommandée (rééquilibrage ±5 %)."),E>.35&&h.push("Lissez les dépenses saisonnières via “sinking funds” mensuels pour réduire la variabilité.");const A=Ai(e,a);return{summary:v,successProbability:Math.round(f*1e3)/1e3,riskLevel:g,recommendations:h,forecast12m:A}}}function vs(c,e,t=4){return e?c:c?"•••• "+c.slice(-t):""}function V(c,e,t,r,s){const n=c.splitTextToSize(`• ${e}`,s);return c.text(n,t,r),r+n.length*5+2}async function Ei(c,e,t={}){const s=(t.language||"fr")==="fr",n=!!t.showFullSensitive,a=new ce({unit:"mm",format:"letter"}),i=215.9,l=279.4,o=20,u=i-2*o;a.setFillColor(245,247,255),a.rect(0,0,i,l,"F"),a.setFontSize(22),a.setTextColor(31,41,55);const m={trusted:s?"Dossier urgence — Personne de confiance":"Emergency dossier — Trusted person",notary:s?"Dossier urgence — Notaire":"Emergency dossier — Notary",planner:s?"Dossier urgence — Planificateur":"Emergency dossier — Planner",liquidator:s?"Dossier urgence — Liquidateur":"Emergency dossier — Liquidator"};a.text(m[e],i/2,80,{align:"center"}),a.setFontSize(14),a.setTextColor(107,114,128);const d=s?"Informations essentielles en cas d’urgence — document confidentiel":"Essential information in case of emergency — confidential document";a.text(d,i/2,95,{align:"center"}),a.setFontSize(11),a.setTextColor(55,65,81);const p=`${s?"Nom":"Name"}: ${c.prenom||""} ${c.nom||""}`;a.text(p,i/2,112,{align:"center"}),a.setFontSize(10),a.setTextColor(107,114,128);const x=new Date().toLocaleDateString(s?"fr-CA":"en-CA"),E=t.authorName?` • ${s?"Par":"By"} ${t.authorName}`:"";a.text(`${s?"Généré le":"Generated on"} ${x}${E}`,i/2,124,{align:"center"}),a.setFontSize(9),a.setTextColor(120,120,120);const v=s?"Document à conserver en lieu sûr. Ne pas transmettre par courriel non chiffré.":"Store securely. Do not send by unencrypted email.";a.text(v,i/2,135,{align:"center"}),a.addPage();let f=o;a.setFontSize(18),a.setTextColor(31,41,55),a.text(s?"1) Coordonnées & Contacts":"1) Contacts & Details",o,f),f+=10,a.setFontSize(11),a.setTextColor(75,85,99),f=V(a,(s?"Adresse":"Address")+`: ${c.adresse||"—"}`,o,f,u),f=V(a,(s?"Téléphone":"Phone")+`: ${c.telephone||"—"}`,o,f,u),f=V(a,(s?"Courriel":"Email")+`: ${c.courriel||"—"}`,o,f,u);const g=(s?"NAS":"SIN")+`: ${vs(c.nas||"",n)}`;f=V(a,g,o,f,u);const h=(s?"Carte santé":"Health card")+`: ${vs(c.assuranceMaladie||"",n)}`;f=V(a,h,o,f,u),f+=4,a.setFontSize(13),a.setTextColor(31,41,55),a.text(s?"Contact d’urgence principal":"Primary emergency contact",o,f),f+=7,a.setFontSize(11),a.setTextColor(75,85,99),f=V(a,(s?"Nom":"Name")+`: ${c.contactUrgenceNom||"—"}`,o,f,u),f=V(a,(s?"Téléphone":"Phone")+`: ${c.contactUrgenceTelephone||"—"}`,o,f,u),a.addPage(),f=o,a.setFontSize(18),a.setTextColor(31,41,55),a.text(s?"2) Documents juridiques & emplacements":"2) Legal documents & locations",o,f),f+=10,a.setFontSize(11),a.setTextColor(75,85,99),f=V(a,(s?"Testament":"Will")+`: ${c.possedeTestament?s?"Oui":"Yes":s?"Non":"No"}`,o,f,u),f=V(a,(s?"Lieu du testament":"Will location")+`: ${c.lieuTestament||c.testamentEmplacement||"—"}`,o,f,u),(e!=="trusted"||n)&&(f=V(a,(s?"Exécuteur testamentaire":"Executor")+`: ${c.executeurTestamentaire||"—"}`,o,f,u),f=V(a,(s?"Téléphone exécuteur":"Executor phone")+`: ${c.executeurTelephone||"—"}`,o,f,u),f=V(a,(s?"Notaire":"Notary")+`: ${c.notaire||"—"}`,o,f,u),f=V(a,(s?"Coordonnées notaire":"Notary contact")+`: ${c.notaireTelephone||"—"} • ${c.notaireAdresse||""}`,o,f,u)),f=V(a,(s?"Mandat de protection":"Protection mandate")+`: ${c.mandatProtectionPossede?s?"Oui":"Yes":s?"Non":"No"}`,o,f,u),f=V(a,(s?"Emplacement mandat":"Mandate location")+`: ${c.mandatProtectionEmplacement||"—"}`,o,f,u),a.addPage(),f=o,a.setFontSize(18),a.setTextColor(31,41,55),a.text(s?"3) Aperçu financier":"3) Financial overview",o,f),f+=10,a.setFontSize(11),a.setTextColor(75,85,99);const A=c.comptesBancaires?.length||0,y=c.cartesCredit?.length||0,C=(c.reers?.length||0)+(c.celis?.length||0)+(c.cris?.length||0)+(c.ferrs?.length||0)+(c.brokerAccounts?.length||0);f=V(a,(s?"Comptes bancaires":"Bank accounts")+`: ${A}`,o,f,u),f=V(a,(s?"Cartes de crédit":"Credit cards")+`: ${y}`,o,f,u),f=V(a,(s?"Comptes d’investissement":"Investment accounts")+`: ${C}`,o,f,u);const S=Array.from(new Set([...(c.comptesBancaires||[]).map(D=>D.institution).filter(Boolean),...(c.reers||[]).map(D=>D.institution).filter(Boolean),...(c.celis||[]).map(D=>D.institution).filter(Boolean),...(c.cris||[]).map(D=>D.institution).filter(Boolean),...(c.ferrs||[]).map(D=>D.institution).filter(Boolean),...(c.brokerAccounts||[]).map(D=>D.courtier).filter(Boolean)]));S.length&&(f=V(a,`Institutions: ${S.join(", ")}`,o,f,u)),a.addPage(),f=o,a.setFontSize(18),a.setTextColor(31,41,55),a.text(s?"4) Biens & résidences":"4) Assets & residences",o,f),f+=10,a.setFontSize(11),a.setTextColor(75,85,99),c.residencePrincipale?.adresse&&(f=V(a,(s?"Résidence principale":"Primary residence")+`: ${c.residencePrincipale.adresse}`,o,f,u)),c.residenceSecondaire?.adresse&&(f=V(a,(s?"Résidence secondaire":"Secondary residence")+`: ${c.residenceSecondaire.adresse}`,o,f,u)),c.autresProprietes?.length&&(f=V(a,(s?"Autres propriétés":"Other properties")+`: ${c.autresProprietes.length}`,o,f,u)),c.vehiculePrincipal?.marqueModeleAnnee&&(f=V(a,(s?"Véhicule principal":"Primary vehicle")+`: ${c.vehiculePrincipal.marqueModeleAnnee}`,o,f,u)),a.addPage(),f=o,a.setFontSize(18),a.setTextColor(31,41,55),a.text(s?"5) Instructions & volontés":"5) Instructions & wishes",o,f),f+=10,a.setFontSize(11),a.setTextColor(75,85,99);const F=[];c.instructionsSpeciales&&F.push((s?"Instructions spéciales":"Special instructions")+`: ${c.instructionsSpeciales}`),c.volontesFuneraires&&F.push((s?"Volontés funéraires":"Funeral wishes")+`: ${c.volontesFuneraires}`),c.donOrganes&&F.push((s?"Don d’organes":"Organ donation")+`: ${c.donOrganes}`),F.length||F.push("—");for(const D of F)f=V(a,D,o,f,u),f>l-20&&(a.addPage(),f=o);a.addPage(),f=o,a.setFontSize(18),a.setTextColor(31,41,55),a.text("Notes",o,f),f+=10,a.setFontSize(10),a.setTextColor(107,114,128);let w="";switch(e){case"trusted":w=s?"Ce document est destiné à un conjoint, enfant ou ami de confiance. Les identifiants sensibles sont masqués par défaut.":"This document is intended for a trusted spouse, child or friend. Sensitive identifiers are redacted by default.";break;case"notary":w=s?"Ce document offre un aperçu des éléments juridiques pertinents. Les emplacements de documents et contacts clés sont fournis.":"This document provides an overview of relevant legal elements. Locations of documents and key contacts are provided.";break;case"planner":w=s?"Ce document synthétise les informations utiles à la planification financière, sans exposer les identifiants complets.":"This document synthesizes information useful for financial planning, without exposing full identifiers.";break;case"liquidator":w=s?"Ce document assiste le liquidateur dans l’inventaire initial et la localisation des documents et coordonnées.":"This document assists the liquidator with the initial inventory and locating documents and contacts.";break}const b=a.splitTextToSize(w,u);a.text(b,o,f);const R=a.getNumberOfPages?.()??1;for(let D=1;D<=R;D++){a.setPage(D),a.setDrawColor(229,231,235),a.line(o,l-15,i-o,l-15),a.setFontSize(8),a.setTextColor(107,114,128);const I=`Page ${D} ${s?"de":"of"} ${R}`;a.text(I,i/2,l-8,{align:"center"})}return a.output("blob")}const ro=Object.freeze(Object.defineProperty({__proto__:null,generateEmergencyPDF:Ei},Symbol.toStringTag,{value:"Module"}));export{zi as $,$i as A,Hi as B,ki as C,Cr as D,Rr as E,hn as F,Yi as G,Ti as H,_i as I,Ni as J,Mi as K,ds as L,Y as M,Wt as N,Ar as O,Te as P,tn as Q,Qi as R,eo as S,Wi as T,sn as U,rn as V,ae as W,Fi as X,dn as Y,Pi as Z,Ue as _,jt as a,Gi as a0,ro as a1,Q as b,Ma as c,Na as d,Vi as e,be as f,ji as g,ge as h,hs as i,Xi as j,Jt as k,Zi as l,to as m,Di as n,vn as o,qi as p,Ii as q,Ts as r,wi as s,Bi as t,Li as u,Vt as v,Oi as w,Ki as x,Ji as y,Ui as z};