@vpdev2/metakyc-sdk 1.0.20 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"OverviewStep.d.ts","sourceRoot":"","sources":["../../../src/components/steps/OverviewStep.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAI1B,MAAM,WAAW,iBAAiB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;CACrB;AAED;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAiGpD,CAAC"}
1
+ {"version":3,"file":"OverviewStep.d.ts","sourceRoot":"","sources":["../../../src/components/steps/OverviewStep.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAI1B,MAAM,WAAW,iBAAiB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;CACrB;AAED;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAyFpD,CAAC"}
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Jt=Object.defineProperty;var Xt=(t,e,s)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var U=(t,e,s)=>Xt(t,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const er=require("axios"),c=require("react"),r=require("react/jsx-runtime"),$=require("react-hook-form"),oe=require("zod");function tr(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,n.get?n:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const Ie=tr(c);var T=(t=>(t[t.IdentitySdk=0]="IdentitySdk",t[t.RiskScoring=1]="RiskScoring",t[t.Questionaries=2]="Questionaries",t[t.AdditionalData=3]="AdditionalData",t[t.AppropriatenessTest=4]="AppropriatenessTest",t[t.UploadDocument=5]="UploadDocument",t[t.ManualReview=6]="ManualReview",t[t.Overview=7]="Overview",t[t.InvestorCategorization=8]="InvestorCategorization",t))(T||{}),xe=(t=>(t[t.NotStarted=0]="NotStarted",t[t.InProgress=1]="InProgress",t[t.Success=2]="Success",t[t.PartialSuccess=3]="PartialSuccess",t[t.Failed=4]="Failed",t[t.Skipped=5]="Skipped",t[t.AdminReview=6]="AdminReview",t[t.SkippedAndAdminReview=7]="SkippedAndAdminReview",t))(xe||{}),re=(t=>(t[t.None=0]="None",t[t.InProgress=1]="InProgress",t[t.Finished=2]="Finished",t[t.OnHold=3]="OnHold",t[t.IdentityPending=4]="IdentityPending",t))(re||{}),Le=(t=>(t[t.None=0]="None",t[t.RepresentativeKYC=1]="RepresentativeKYC",t[t.ManualRiskCriteria=2]="ManualRiskCriteria",t[t.UploadDocumentReview=3]="UploadDocumentReview",t[t.AdminReview=4]="AdminReview",t))(Le||{}),Te=(t=>(t[t.LowRisk=0]="LowRisk",t[t.MediumRisk=1]="MediumRisk",t[t.HighRisk=2]="HighRisk",t[t.Alert=3]="Alert",t))(Te||{}),ce=(t=>(t[t.None=0]="None",t[t.Pending=1]="Pending",t[t.Approved=2]="Approved",t[t.Rejected=3]="Rejected",t[t.ResendRequested=4]="ResendRequested",t[t.Unknown=5]="Unknown",t[t.InProgress=6]="InProgress",t))(ce||{}),de=(t=>(t[t.Approved=0]="Approved",t[t.Reject=1]="Reject",t[t.UnderReview=2]="UnderReview",t[t.Closed=3]="Closed",t[t.AdminReview=4]="AdminReview",t[t.New=5]="New",t[t.InProgress=6]="InProgress",t))(de||{}),Me=(t=>(t[t.ProviderResultPending=0]="ProviderResultPending",t[t.ProviderResultReceived=1]="ProviderResultReceived",t[t.Canceled=2]="Canceled",t[t.ExtendedToNewApplicant=3]="ExtendedToNewApplicant",t))(Me||{}),Oe=(t=>(t[t.None=0]="None",t[t.ProviderResultPending=1]="ProviderResultPending",t[t.ProviderResultReceived=2]="ProviderResultReceived",t[t.Canceled=3]="Canceled",t))(Oe||{}),te=(t=>(t[t.Onfido=0]="Onfido",t[t.Sumsub=2]="Sumsub",t[t.SardinAI=3]="SardinAI",t))(te||{}),ze=(t=>(t[t.Individual=0]="Individual",t[t.Company=1]="Company",t))(ze||{}),fe=(t=>(t[t.Male=0]="Male",t[t.Female=1]="Female",t[t.Other=2]="Other",t))(fe||{}),Be=(t=>(t[t.Image=0]="Image",t[t.Video=1]="Video",t[t.PDF=2]="PDF",t[t.OfficePDF=3]="OfficePDF",t[t.Custom=4]="Custom",t))(Be||{}),_e=(t=>(t[t.Pending=0]="Pending",t[t.Approved=1]="Approved",t[t.Rejected=2]="Rejected",t[t.RequiresRevision=3]="RequiresRevision",t))(_e||{}),$e=(t=>(t[t.SingleChoice=0]="SingleChoice",t[t.MultipleChoice=1]="MultipleChoice",t[t.Text=2]="Text",t))($e||{}),we=(t=>(t[t.String=0]="String",t[t.Integer=1]="Integer",t[t.Decimal=2]="Decimal",t[t.Boolean=3]="Boolean",t[t.Date=4]="Date",t[t.Country=5]="Country",t[t.DigitOnly=6]="DigitOnly",t))(we||{}),Ke=(t=>(t[t.Text=0]="Text",t[t.Radio=1]="Radio",t[t.Checkbox=2]="Checkbox",t[t.Dropdown=3]="Dropdown",t[t.Country=4]="Country",t))(Ke||{}),Ue=(t=>(t[t.None=0]="None",t[t.Country=1]="Country",t))(Ue||{}),J=(t=>(t[t.Individual=0]="Individual",t[t.Sophisticated=1]="Sophisticated",t[t.HighNetWorth=2]="HighNetWorth",t[t.Business=3]="Business",t))(J||{}),qe=(t=>(t[t.Retail=0]="Retail",t[t.Professional=1]="Professional",t[t.EligibleCounterparty=2]="EligibleCounterparty",t))(qe||{});const He=["firstName","lastName","email","phonenumber","dateOfBirth","street","streetNumber","zip","city","country","nationality","taxCountry","taxNumber"],rr=["firstName","lastName","title","email","dateOfBirth","phonenumber","mobileCountryCode","street","streetNumber","zip","city","country","nationality","otherNationality","defaultLanguage","taxCountry","placeOfBirth","countryOfBirth","salutation","educationLevel","occupation","taxNumber","externalRefId"],Ve={firstName:{label:"First Name",type:"text"},lastName:{label:"Last Name",type:"text"},title:{label:"Title",type:"text"},email:{label:"Email",type:"email"},dateOfBirth:{label:"Date of Birth",type:"date"},phonenumber:{label:"Phone Number",type:"tel"},mobileCountryCode:{label:"Mobile Country Code",type:"text"},street:{label:"Street",type:"text"},streetNumber:{label:"Street Number",type:"text"},zip:{label:"ZIP/Postal Code",type:"text"},city:{label:"City",type:"text"},country:{label:"Country",type:"select"},nationality:{label:"Nationality",type:"select"},otherNationality:{label:"Other Nationalities",type:"multiselect"},defaultLanguage:{label:"Default Language",type:"text"},taxCountry:{label:"Tax Country",type:"select"},placeOfBirth:{label:"Place of Birth",type:"text"},countryOfBirth:{label:"Country of Birth",type:"select"},salutation:{label:"Salutation",type:"select"},educationLevel:{label:"Education Level",type:"text"},occupation:{label:"Occupation",type:"text"},taxNumber:{label:"Tax Number",type:"text"},externalRefId:{label:"External Reference ID",type:"text"}};var V=(t=>(t.Default="default",t.Corporate="corporate",t.Fintech="fintech",t.Healthcare="healthcare",t.Modern="modern",t.Minimal="minimal",t))(V||{});const Ye={timeout:3e4,retries:3,locale:"en",endpoints:{pattern:"host-controller"}};class We{constructor(e){this.config=e}build(e,s){const n=`${e}.${s}`;if(this.config.customPaths&&this.config.customPaths[n])return this.config.customPaths[n];switch(this.config.pattern){case"host-controller":return`/api/${e}/${s}`;case"application-service":return`/services/app/${this.getServiceName(e)}/${s}`;case"custom":throw new Error(`Custom endpoint path not found for ${n}. Please provide it in customPaths.`);default:throw new Error(`Unknown endpoint pattern: ${this.config.pattern}`)}}getServiceName(e){return{Applicant:"MetaKYCVerification",Questionnaire:"MetaKYCVerification",UploadDocument:"MetaKYCVerification",AppropriatenessTest:"MetaKYCVerification",BaseInformation:"MetaKYCVerification"}[e]||e}}class ae extends Error{constructor(s,n,a,i,o){super(s);U(this,"response");this.code=n,this.details=a,this.validationErrors=i,this.name="MetaKYCError",this.response=o,Object.setPrototypeOf(this,ae.prototype)}}class he{static handleApiError(e){return new ae(e.message||"An unknown error occurred",e.code,e.details||void 0,e.validationErrors||void 0)}static handleAxiosError(e){if(e.response){const s=e.response.data;return s&&s.error?new ae(s.error.message||"An unknown error occurred",s.error.code,s.error.details||void 0,s.error.validationErrors||void 0,e.response):s&&s.result&&s.result.message?new ae(s.result.message,e.response.status,`HTTP ${e.response.status}: ${e.response.statusText}`,void 0,e.response):new ae((s==null?void 0:s.message)||e.message||"Request failed",e.response.status,`HTTP ${e.response.status}: ${e.response.statusText}`,void 0,e.response)}else return e.request?new ae("No response from server",0,"The request was made but no response was received. Please check your network connection."):new ae(e.message||"An unexpected error occurred",0,e.toString())}static isMetaKYCError(e){return e instanceof ae}}class Qe{constructor(e){U(this,"axiosInstance");U(this,"endpointBuilder");U(this,"config");this.config={...Ye,...e},this.endpointBuilder=new We(this.config.endpoints),this.axiosInstance=er.create({baseURL:this.config.baseUrl,timeout:this.config.timeout,headers:{"Content-Type":"application/json"}}),this.axiosInstance.interceptors.request.use(s=>(s.headers["Abp-TenantId"]=this.config.tenantId.toString(),s.headers.ApiKey=this.config.apiKey,s.headers["X-API-KEY"]=this.config.apiKey,this.config.locale&&(s.headers["Accept-Language"]=this.config.locale),s),s=>Promise.reject(s)),this.axiosInstance.interceptors.response.use(s=>s,async s=>{var a;const n=s.config;return((a=s.response)==null?void 0:a.status)>=500&&!n._retry&&(n._retry=!0,n._retryCount=(n._retryCount||0)+1,n._retryCount<(this.config.retries||3))?(await new Promise(i=>setTimeout(i,1e3*n._retryCount)),this.axiosInstance(n)):Promise.reject(s)})}buildEndpoint(e,s){return this.endpointBuilder.build(e,s)}async get(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.get(a,{params:n});return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}async post(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.post(a,n);return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}async put(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.put(a,n);return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}async delete(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.delete(a,{params:n});return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}handleResponse(e){const s=e.data;if(!s.success&&s.error)throw he.handleApiError(s.error);return s}getAxiosInstance(){return this.axiosInstance}}class Ge{constructor(e){this.httpClient=e}async createApplicant(e){return(await this.httpClient.post("Applicant","ApplicantRegistrationRequest",e)).result}async createCompanyApplicant(e){return(await this.httpClient.post("Applicant","ApplicantCompanyRegistrationRequest",e)).result}async duplicateApplicant(e){return(await this.httpClient.post("Applicant","DuplicateApplicantRegistrationRequest",e)).result}async getProgress(e){return(await this.httpClient.get("Applicant","GetApplicantProgress",{applicantId:e})).result}async getProgressStatus(e){return(await this.httpClient.get("Applicant","GetApplicantProgressStaus",{applicantId:e})).result}async getApplicantData(e){return(await this.httpClient.get("Applicant","GetApplicantData",{applicantId:e})).result}async getApplicantStatus(e){return(await this.httpClient.get("Applicant","GetApplicantStatus",{applicantId:e})).result}async stopProgress(e){await this.httpClient.get("Applicant","StopProgress",{applicantId:e})}async progressStepBack(e){await this.httpClient.get("Applicant","ProgressStepBack",{applicantId:e})}async setLanguage(e,s){await this.httpClient.post("Applicant","SetApplicantLng",{applicantId:e,language:s})}async activateApplicant(e){await this.httpClient.get("Applicant","ActivateApplicant",{applicantId:e})}async deleteApplicant(e){await this.httpClient.delete("Applicant","DeleteApplicant",{applicantId:e})}async checkApplicantExists(e){return(await this.httpClient.get("Applicant","CheckApplicantIfExists",{externalRefId:e})).result}}class Ze{constructor(e){this.httpClient=e}async getQuestionnaire(e){return(await this.httpClient.get("Questionnaire","GetQuestionnaire",{applicantid:e})).result}async fillQuestionnaire(e){return(await this.httpClient.post("Applicant","FillQuestionnarie",e)).result}}class Je{constructor(e){this.httpClient=e}async getUploadDocument(e){return(await this.httpClient.get("UploadDocument","GetUploadDocument",{applicantid:e})).result}async fillUploadDocument(e){await this.httpClient.post("Applicant","FillUploadDocument",e)}async reviewUploadDocument(e){await this.httpClient.post("UploadDocument","ReviewUploadDocument",e)}}class Xe{constructor(e){this.httpClient=e}async getAppropriatenessTest(e){return(await this.httpClient.get("AppropriatenessTest","GetAppropriatenessTest",{applicantid:e})).result}async fillAppropriatenessTest(e){return(await this.httpClient.post("Applicant","FillAppropriatenessTest",e)).result}}class et{constructor(e){this.httpClient=e}async getOverviewData(e){return(await this.httpClient.get("Applicant","GetOverviewData",{ApplicantId:e})).result}async passOverview(e){await this.httpClient.get("Applicant","PassOverview",{applicantId:e})}}class tt{constructor(e){this.httpClient=e}async getRiskScoringPlan(){return(await this.httpClient.get("Applicant","GetRiskScoringPlanInfo")).result}async getRiskCriterias(e){return(await this.httpClient.get("Risk","GetCriterias",{applicantId:e})).result}async submitRiskScoring(e){return(await this.httpClient.post("Applicant","RiskScoringRequest",e)).result}}class rt{constructor(e){this.httpClient=e}async identityRequest(e){console.log("[IdentityService] Calling IdentityRequest with input:",e);const s=await this.httpClient.post("Applicant","IdentityRequest",e);return console.log("[IdentityService] IdentityRequest response:",s),s.result}async identityCompanyRequest(e){return(await this.httpClient.post("Applicant","IdentityCompanyRequest",e)).result}async restartIdentityRequest(e){const s={applicantId:e,restart:!0,redirectUrl:"",ttl:604800};return console.log("[IdentityService] Restarting identity with restart=true:",s),this.identityRequest(s)}async restartIdentityCompanyRequest(e){const s={applicantId:e,restart:!0,redirectUrl:"",ttl:604800};return this.identityCompanyRequest(s)}}class st{constructor(e){this.httpClient=e}async getCountries(e,s,n){return(await this.httpClient.get("BaseInformation","GetAllCountries",{filter:e||"",lng:s||"en",type:n})).result}async getBranches(){return(await this.httpClient.get("BaseInformation","GetBranches")).result}async getLegalEntities(){return(await this.httpClient.get("BaseInformation","GetLegalEntities")).result}}class nt{constructor(e){this.httpClient=e}async setInvestorCategorization(e){return(await this.httpClient.post("Applicant","SetInvestorCategorization",e)).result}async getInvestorCategorization(e){return(await this.httpClient.get("Applicant","GetInvestorCategorisation",{applicantId:e})).result}}const Y={name:"Default",title:"KYC Verification",logo:{url:"",height:"40px",visible:!0},colors:{primary:"#2563eb",primaryHover:"#1d4ed8",primaryLight:"#dbeafe",primaryDark:"#1e40af",secondary:"#64748b",secondaryHover:"#475569",success:"#10b981",warning:"#f59e0b",danger:"#ef4444",info:"#3b82f6",background:"#ffffff",surface:"#f9fafb",border:"#e5e7eb",textPrimary:"#111827",textSecondary:"#6b7280",textMuted:"#9ca3af"},typography:{fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},spacing:{borderRadius:"0.5rem",cardPadding:"1.5rem",inputHeight:"2.5rem"},darkMode:{colors:{background:"#111827",surface:"#1f2937",border:"#374151",textPrimary:"#f9fafb",textSecondary:"#d1d5db",textMuted:"#9ca3af"}}},at={name:"Corporate",logo:{url:"",height:"40px",visible:!0},colors:{primary:"#0052CC",primaryHover:"#0747A6",primaryLight:"#DEEBFF",primaryDark:"#0747A6",secondary:"#6B778C",secondaryHover:"#5E6C84",success:"#00875A",warning:"#FF991F",danger:"#DE350B",info:"#0065FF",background:"#ffffff",surface:"#F4F5F7",border:"#DFE1E6",textPrimary:"#172B4D",textSecondary:"#5E6C84",textMuted:"#97A0AF"},typography:{fontFamily:"system-ui, -apple-system, sans-serif"},spacing:{borderRadius:"0.25rem",cardPadding:"1.5rem",inputHeight:"2.5rem"}},it={name:"Fintech",logo:{url:"",height:"36px",visible:!0},colors:{primary:"#00B386",primaryHover:"#009973",primaryLight:"#D1FAE5",primaryDark:"#047857",secondary:"#7C3AED",secondaryHover:"#6D28D9",success:"#10B981",warning:"#F59E0B",danger:"#EF4444",info:"#3B82F6",background:"#ffffff",surface:"#F9FAFB",border:"#E5E7EB",textPrimary:"#111827",textSecondary:"#6B7280",textMuted:"#9CA3AF"},typography:{fontFamily:"Montserrat, system-ui, sans-serif"},spacing:{borderRadius:"0.75rem",cardPadding:"2rem",inputHeight:"3rem"}},ot={name:"Healthcare",logo:{url:"",height:"44px",visible:!0},colors:{primary:"#06B6D4",primaryHover:"#0891B2",primaryLight:"#CFFAFE",primaryDark:"#0E7490",secondary:"#8B5CF6",secondaryHover:"#7C3AED",success:"#059669",warning:"#D97706",danger:"#DC2626",info:"#0284C7",background:"#ffffff",surface:"#F0F9FF",border:"#E0F2FE",textPrimary:"#0F172A",textSecondary:"#475569",textMuted:"#94A3B8"},typography:{fontFamily:"Lato, system-ui, sans-serif"},spacing:{borderRadius:"0.5rem",cardPadding:"1.75rem",inputHeight:"2.75rem"},darkMode:{colors:{background:"#0F172A",surface:"#1E293B",border:"#334155",textPrimary:"#F1F5F9",textSecondary:"#CBD5E1"}}},lt={name:"Modern",logo:{url:"",height:"38px",visible:!0},colors:{primary:"#8B5CF6",primaryHover:"#7C3AED",primaryLight:"#EDE9FE",primaryDark:"#6D28D9",secondary:"#EC4899",secondaryHover:"#DB2777",success:"#10B981",warning:"#F59E0B",danger:"#EF4444",info:"#3B82F6",background:"#ffffff",surface:"#FAFAFA",border:"#E5E5E5",textPrimary:"#171717",textSecondary:"#737373",textMuted:"#A3A3A3"},typography:{fontFamily:"Poppins, system-ui, sans-serif"},spacing:{borderRadius:"1rem",cardPadding:"2rem",inputHeight:"3rem"}},ct={name:"Minimal",logo:{url:"",height:"32px",visible:!0},colors:{primary:"#000000",primaryHover:"#18181B",primaryLight:"#F4F4F5",primaryDark:"#000000",secondary:"#71717A",secondaryHover:"#52525B",success:"#22C55E",warning:"#EAB308",danger:"#EF4444",info:"#3B82F6",background:"#ffffff",surface:"#FAFAFA",border:"#E4E4E7",textPrimary:"#09090B",textSecondary:"#71717A",textMuted:"#A1A1AA"},typography:{fontFamily:"system-ui, -apple-system, sans-serif"},spacing:{borderRadius:"0.25rem",cardPadding:"1.25rem",inputHeight:"2.25rem"}},dt={[V.Default]:Y,[V.Corporate]:at,[V.Fintech]:it,[V.Healthcare]:ot,[V.Modern]:lt,[V.Minimal]:ct};function pe(t){return dt[t]||Y}class ut{constructor(e){this.httpClient=e}async getThemeConfiguration(){var e;try{const s=await this.httpClient.get("Tenant","GetThemeConfiguration");if(!s.result.isEnabled)return pe(V.Default);let n=s.result.preset?pe(s.result.preset):pe(V.Default);return s.result.title&&(n.title=s.result.title),s.result.logo&&(n.logo={...n.logo,...s.result.logo}),s.result.colors&&(n.colors={...n.colors,...s.result.colors}),s.result.typography&&(n.typography={...n.typography,...s.result.typography}),s.result.spacing&&(n.spacing={...n.spacing,...s.result.spacing}),s.result.customCSS&&(n.customCSS=s.result.customCSS),s.result.darkMode&&(n.darkMode={colors:{...(e=n.darkMode)==null?void 0:e.colors,...s.result.darkMode.colors}}),n}catch(s){return console.warn("[ThemeService] Failed to fetch theme configuration:",s),pe(V.Default)}}async saveThemeConfiguration(e){await this.httpClient.post("Tenant","SaveThemeConfiguration",e)}getAvailablePresets(){return[{id:V.Default,name:"Default"},{id:V.Corporate,name:"Corporate"},{id:V.Fintech,name:"Fintech"},{id:V.Healthcare,name:"Healthcare"},{id:V.Modern,name:"Modern"},{id:V.Minimal,name:"Minimal"}]}getPreviewTheme(e,s){const n=pe(e);return s?{...n,...s,logo:{...n.logo,...s.logo},colors:{...n.colors,...s.colors},typography:s.typography?{...n.typography,...s.typography}:n.typography,spacing:s.spacing?{...n.spacing,...s.spacing}:n.spacing}:n}}class mt{constructor(){U(this,"listeners",new Map)}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>{this.off(e,s)}}off(e,s){const n=this.listeners.get(e);n&&n.delete(s)}emit(e,s){const n=this.listeners.get(e);n&&n.forEach(a=>{try{a(s)}catch(i){console.error(`Error in event listener for "${e}":`,i)}})}clear(){this.listeners.clear()}clearEvent(e){this.listeners.delete(e)}}class ht{constructor(){U(this,"events",new mt);U(this,"_applicantId",null);U(this,"_progress",null);U(this,"_error",null)}get applicantId(){return this._applicantId}get progress(){return this._progress}get currentStep(){var e;return((e=this._progress)==null?void 0:e.currentStep)||null}get steps(){var e;return((e=this._progress)==null?void 0:e.stepInfoList)||[]}get status(){var e;return((e=this._progress)==null?void 0:e.status)||re.None}get workflowResult(){var e;return((e=this._progress)==null?void 0:e.workflowResult)||null}get error(){return this._error}get isComplete(){return this.status===re.Finished}get isOnHold(){return this.status===re.OnHold}get isInProgress(){return this.status===re.InProgress}setApplicantId(e){this._applicantId=e}updateProgress(e){var n,a;const s=(n=this._progress)==null?void 0:n.currentStep;this._progress=e,this._applicantId=e.applicantId,this._error=null,this.events.emit("progressUpdated",e),(s==null?void 0:s.order)!==((a=e.currentStep)==null?void 0:a.order)&&this.events.emit("stepChanged",e.currentStep),this.events.emit("statusChanged",e.status),e.status===re.Finished&&e.workflowResult&&this.events.emit("completed",e.workflowResult)}setError(e){this._error=e,this.events.emit("error",e)}clearError(){this._error=null}reset(){this._applicantId=null,this._progress=null,this._error=null}onProgressUpdated(e){return this.events.on("progressUpdated",e)}onStepChanged(e){return this.events.on("stepChanged",e)}onStatusChanged(e){return this.events.on("statusChanged",e)}onError(e){return this.events.on("error",e)}onCompleted(e){return this.events.on("completed",e)}clearListeners(){this.events.clear()}}class pt{constructor(){U(this,"handlers",new Map)}registerHandler(e,s){this.handlers.set(e,s)}getHandler(e){return this.handlers.get(e)}hasHandler(e){return this.handlers.has(e)}async loadStepData(e,s){const n=this.getHandler(e);if(!n)throw new Error(`No handler registered for step action: ${T[e]}`);return n.loadData(s)}async submitStepData(e,s){const n=this.getHandler(e);if(!n)throw new Error(`No handler registered for step action: ${T[e]}`);return n.submitData(s)}}class gt{constructor(e,s,n,a,i,o,l,d){U(this,"state");U(this,"stepRouter");this.applicantService=e,this.questionnaireService=s,this.uploadDocumentService=n,this.appropriatenessTestService=a,this.overviewService=i,this.riskScoringService=o,this.investorCategorizationService=d,this.state=new ht,this.stepRouter=new pt,this.registerStepHandlers()}registerStepHandlers(){this.stepRouter.registerHandler(T.Questionaries,{loadData:e=>this.questionnaireService.getQuestionnaire(e),submitData:async e=>{await this.questionnaireService.fillQuestionnaire(e)}}),this.stepRouter.registerHandler(T.UploadDocument,{loadData:e=>this.uploadDocumentService.getUploadDocument(e),submitData:e=>this.uploadDocumentService.fillUploadDocument(e)}),this.stepRouter.registerHandler(T.AppropriatenessTest,{loadData:e=>this.appropriatenessTestService.getAppropriatenessTest(e),submitData:async e=>{await this.appropriatenessTestService.fillAppropriatenessTest(e)}}),this.stepRouter.registerHandler(T.Overview,{loadData:e=>this.overviewService.getOverviewData(e),submitData:e=>this.overviewService.passOverview(e.applicantId)}),this.stepRouter.registerHandler(T.RiskScoring,{loadData:e=>this.riskScoringService.getRiskCriterias(e),submitData:async e=>{await this.riskScoringService.submitRiskScoring(e)}}),this.stepRouter.registerHandler(T.IdentitySdk,{loadData:async e=>({applicantId:e,message:"Identity verification required"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.InvestorCategorization,{loadData:e=>this.investorCategorizationService.getInvestorCategorization(e),submitData:async e=>{await this.investorCategorizationService.setInvestorCategorization(e)}}),this.stepRouter.registerHandler(T.ManualReview,{loadData:async e=>({applicantId:e,message:"Your application is under manual review"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.AdditionalData,{loadData:async e=>({applicantId:e,message:"Additional data required"}),submitData:async()=>{}})}async initialize(e){try{this.state.setApplicantId(e);const s=await this.applicantService.getProgress(e);return this.state.updateProgress(s),s}catch(s){throw this.state.setError(s),s}}async refreshProgress(){if(!this.state.applicantId)throw new Error("Workflow not initialized. Call initialize() first.");try{const e=await this.applicantService.getProgress(this.state.applicantId);return this.state.updateProgress(e),e}catch(e){throw this.state.setError(e),e}}async getCurrentStepData(){if(!this.state.currentStep)throw new Error("No current step available");if(!this.state.applicantId)throw new Error("Workflow not initialized");try{return await this.stepRouter.loadStepData(this.state.currentStep.action,this.state.applicantId)}catch(e){throw this.state.setError(e),e}}async submitCurrentStep(e){if(!this.state.currentStep)throw new Error("No current step available");try{await this.stepRouter.submitStepData(this.state.currentStep.action,e),await this.refreshProgress()}catch(s){throw this.state.setError(s),s}}async moveToNextStep(){return this.refreshProgress()}async moveToPreviousStep(){if(!this.state.applicantId)throw new Error("Workflow not initialized");try{return await this.applicantService.progressStepBack(this.state.applicantId),await this.refreshProgress()}catch(e){throw this.state.setError(e),e}}getState(){return this.state}getStepRouter(){return this.stepRouter}}function Ce(t,e){return new Promise((s,n)=>{if(e&&document.getElementById(e)){s();return}const a=document.createElement("script");a.src=t,e&&(a.id=e),a.async=!0,a.onload=()=>s(),a.onerror=()=>n(new Error(`Failed to load script: ${t}`)),document.head.appendChild(a)})}function sr(t){return!!document.getElementById(t)}function nr(t){const e=document.getElementById(t);e&&e.remove()}class xt{constructor(e){U(this,"sdk",null);U(this,"config");this.config=e}async loadSDK(){await Ce("https://cdn.sumsub.com/websdk/v2/production/websdk.js","sumsub-sdk")}async initialize(e){if(window.snsWebSdk||await this.loadSDK(),!window.snsWebSdk)throw new Error("Sumsub SDK failed to load");this.sdk=window.snsWebSdk.init(this.config.accessToken,()=>this.config.accessToken).withConf({lang:this.config.lang||"en",email:this.config.applicantEmail,phone:this.config.applicantPhone,i18n:{}}).on("idCheck.onStepCompleted",s=>{console.log("Sumsub step completed:",s)}).on("idCheck.onError",s=>{console.error("Sumsub error:",s)}).build(),this.sdk.launch(`#${e}`)}destroy(){this.sdk&&(this.sdk.destroy(),this.sdk=null)}onComplete(e){this.sdk&&this.sdk.on("idCheck.applicantStatus",s=>{s.applicantStatus==="completed"&&e(s)})}onError(e){this.sdk&&this.sdk.on("idCheck.onError",e)}}class ft{constructor(e){U(this,"sdk",null);U(this,"config");this.config=e}async loadSDK(){await Ce("https://sdk.onfido.com/v12.0.0/onfido.min.js","onfido-sdk")}async initialize(e){if(window.Onfido||await this.loadSDK(),!window.Onfido)throw new Error("Onfido SDK failed to load");this.sdk=window.Onfido.init({token:this.config.token,containerId:e,steps:this.config.steps||[{type:"welcome",options:{title:"Identity Verification"}},{type:"document",options:{documentTypes:{passport:!0,driving_licence:!0,national_identity_card:!0}}},{type:"face",options:{requestedVariant:"standard"}},{type:"complete"}],onComplete:()=>{this.config.onComplete&&this.config.onComplete()},onError:s=>{this.config.onError&&this.config.onError(s)}})}destroy(){this.sdk&&(this.sdk.tearDown(),this.sdk=null)}}class yt{constructor(e){U(this,"sardineContext",null);U(this,"config");U(this,"sessionKey");this.config=e,this.sessionKey=e.sessionKey||this.generateSessionKey()}generateSessionKey(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const s=Math.random()*16|0;return(e==="x"?s:s&3|8).toString(16)})}getSardineHost(){const{environment:e,region:s}=this.config;if(e==="sandbox")return"api.sandbox.sardine.ai";switch(s){case"eu":return"api.eu.sardine.ai";case"ca":return"api.ca.sardine.ai";case"au":return"api.au.sardine.ai";default:return"api.sardine.ai"}}async loadSDK(){return new Promise((e,s)=>{if(window._Sardine){e();return}const n=this.getSardineHost(),a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=`https://${n}/assets/loader.min.js`,a.onload=()=>{console.log("[SardinAI] SDK loaded successfully"),e()},a.onerror=()=>{s(new Error("Failed to load SardinAI SDK"))};const i=document.getElementsByTagName("script")[0];i&&i.parentNode?i.parentNode.insertBefore(a,i):document.head.appendChild(a)})}async initialize(){try{if(await this.loadSDK(),!window._Sardine)throw new Error("SardinAI SDK not available after loading");const e=this.getSardineHost(),{clientId:s,environment:n,flow:a,enableBiometrics:i,enablePortScanning:o}=this.config;this.sardineContext=window._Sardine.createContext({clientId:s,sessionKey:this.sessionKey,userIdHash:void 0,flow:a||window.location.pathname,environment:n||"production",parentElement:document.body,enableBiometrics:i!==!1,enablePortScanning:o===!0,region:this.config.region,onDeviceResponse:l=>{console.log(`[SardinAI] Device ID: ${l.deviceId}`)},onConfigUpdate:(l,d,u)=>{switch(l){case"SESSION_UPDATE_FAILED":console.error("[SardinAI] Session update failed:",u);break;case"SESSION_UPDATED":console.log("[SardinAI] Session updated:",d);break;case"SESSION_NO_UPDATE":console.log("[SardinAI] No session update");break;default:console.warn("[SardinAI] Unknown event:",l)}}}),this.addNoScriptFallback(e),console.log("[SardinAI] SDK initialized with sessionKey:",this.sessionKey)}catch(e){throw console.error("[SardinAI] Initialization failed:",e),e}}addNoScriptFallback(e){const s=document.createElement("noscript"),n=document.createElement("img"),{clientId:a,flow:i}=this.config;n.src=`https://${e}/v1/a.png?clientId=${a}&sessionKey=${this.sessionKey}&flow=${i||"kyc"}&ns=1`,n.style.display="none",s.appendChild(n),document.body.appendChild(s)}updateConfig(e){if(!this.sardineContext){console.warn("[SardinAI] Cannot update config - SDK not initialized");return}e.sessionKey&&(this.sessionKey=e.sessionKey),this.sardineContext.updateConfig({...e,onConfigUpdate:(s,n,a)=>{switch(s){case"SESSION_UPDATE_FAILED":console.error("[SardinAI] Config update failed:",a);break;case"SESSION_UPDATED":console.log("[SardinAI] Config updated:",n);break;case"SESSION_NO_UPDATE":console.log("[SardinAI] No config update needed");break}}})}getSessionKey(){return this.sessionKey}destroy(){this.sardineContext&&(this.sardineContext=null)}}class me{static createProvider(e,s){switch(e){case te.Sumsub:return new xt(s);case te.Onfido:return new ft(s);case te.SardinAI:return new yt(s);default:throw new Error(`Unsupported identity provider: ${e}`)}}static parseProviderConfig(e,s,n){var a;switch(e){case te.Sumsub:return{accessToken:s.accessToken||s.token,applicantEmail:s.email,applicantPhone:s.phone,externalUserId:s.externalUserId,lang:s.lang||"en"};case te.Onfido:return{token:s.token||s.sdkToken};case te.SardinAI:const i=((a=n==null?void 0:n.identityProviders)==null?void 0:a.sardinai)||{};return{clientId:i.clientId||s.clientId,sessionKey:i.sessionKey||s.sessionKey,environment:i.environment||s.environment||"production",flow:i.flow||s.flow,region:i.region,enableBiometrics:i.enableBiometrics,enablePortScanning:i.enablePortScanning};default:throw new Error(`Unsupported identity provider: ${e}`)}}}class bt{constructor(e){U(this,"currentTheme",Y);U(this,"customStyleElement",null);U(this,"container");this.container=e||document.documentElement}applyTheme(e){this.currentTheme=this.mergeWithDefault(e),this.applyColors(this.currentTheme.colors),this.currentTheme.typography&&this.applyTypography(this.currentTheme.typography),this.currentTheme.spacing&&this.applySpacing(this.currentTheme.spacing),this.currentTheme.customCSS&&this.injectCustomCSS(this.currentTheme.customCSS),console.log("[ThemeManager] Theme applied:",this.currentTheme.name||"Custom")}applyColors(e){var n;const s={primary:e.primary,"primary-hover":e.primaryHover,"primary-light":e.primaryLight,"primary-dark":e.primaryDark,secondary:e.secondary,"secondary-hover":e.secondaryHover,success:e.success,warning:e.warning,danger:e.danger,info:e.info,background:e.background,surface:e.surface,border:e.border,"text-primary":e.textPrimary,"text-secondary":e.textSecondary,"text-muted":e.textMuted};Object.entries(s).forEach(([a,i])=>{this.container.style.setProperty(`--metakyc-${a}`,i)}),(n=this.currentTheme.darkMode)!=null&&n.colors&&this.applyDarkModeColors(this.currentTheme.darkMode.colors)}applyDarkModeColors(e){Object.entries(e).forEach(([s,n])=>{if(n){const a=`--metakyc-dark-${this.kebabCase(s)}`;this.container.style.setProperty(a,n)}})}applyTypography(e){e&&(e.fontFamily&&this.container.style.setProperty("--metakyc-font-family",e.fontFamily),e.headingFont&&this.container.style.setProperty("--metakyc-heading-font",e.headingFont),e.fontSize&&Object.entries(e.fontSize).forEach(([s,n])=>{this.container.style.setProperty(`--metakyc-font-size-${s}`,n)}),e.fontWeight&&Object.entries(e.fontWeight).forEach(([s,n])=>{this.container.style.setProperty(`--metakyc-font-weight-${s}`,n.toString())}))}applySpacing(e){e&&Object.entries(e).forEach(([s,n])=>{const a=`--metakyc-${this.kebabCase(s)}`;this.container.style.setProperty(a,n)})}injectCustomCSS(e){this.customStyleElement&&this.customStyleElement.remove(),this.customStyleElement=document.createElement("style"),this.customStyleElement.id="metakyc-custom-css",this.customStyleElement.textContent=e,document.head.appendChild(this.customStyleElement)}mergeWithDefault(e){var s;return{name:e.name||Y.name,title:e.title||Y.title,logo:{...Y.logo,...e.logo},colors:{...Y.colors,...e.colors},typography:e.typography?{...Y.typography,...e.typography}:Y.typography,spacing:e.spacing?{...Y.spacing,...e.spacing}:Y.spacing,customCSS:e.customCSS,darkMode:e.darkMode?{colors:{...(s=Y.darkMode)==null?void 0:s.colors,...e.darkMode.colors}}:Y.darkMode}}getCurrentTheme(){return this.currentTheme}resetTheme(){this.applyTheme(Y)}cleanup(){this.customStyleElement&&(this.customStyleElement.remove(),this.customStyleElement=null)}kebabCase(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}}const Ae=c.createContext(null),ar=({config:t,children:e})=>{const[s,n]=c.useState(null),a=c.useRef(!1),i=c.useRef(!1),o=c.useMemo(()=>{const d=new Qe(t),u=new Ge(d),x=new Ze(d),b=new Je(d),g=new Xe(d),y=new et(d),m=new tt(d),f=new rt(d),j=new st(d),h=new nt(d),N=new ut(d),k=new bt;return{httpClient:d,applicantService:u,questionnaireService:x,uploadDocumentService:b,appropriatenessTestService:g,overviewService:y,riskScoringService:m,identityService:f,baseInformationService:j,investorCategorizationService:h,themeService:N,themeManager:k}},[t]),l=c.useMemo(()=>({config:t,...o,currentTheme:s,createOrchestrator:()=>new gt(o.applicantService,o.questionnaireService,o.uploadDocumentService,o.appropriatenessTestService,o.overviewService,o.riskScoringService,o.identityService,o.investorCategorizationService)}),[t,o,s]);return c.useEffect(()=>((async()=>{if(a.current||i.current){console.log("[MetaKYC] Theme already loading or loaded, skipping...");return}a.current=!0;try{if(t.theme){console.log("[MetaKYC] Applying static theme from config"),o.themeManager.applyTheme(t.theme),n(o.themeManager.getCurrentTheme()),i.current=!0;return}console.log("[MetaKYC] Fetching theme from backend...");const u=await o.themeService.getThemeConfiguration();o.themeManager.applyTheme(u),n(o.themeManager.getCurrentTheme()),i.current=!0,console.log("[MetaKYC] Theme loaded and applied",u)}catch(u){console.warn("[MetaKYC] Failed to load theme, using default:",u),n(o.themeManager.getCurrentTheme()),i.current=!0}finally{a.current=!1}})(),()=>{o.themeManager.cleanup()}),[]),r.jsx(Ae.Provider,{value:l,children:e})};function ee(){const t=c.useContext(Ae);if(!t)throw new Error("useMetaKYC must be used within a MetaKYCProvider");return t}async function vt(t){return new Promise((e,s)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>{const i=n.result.split(",")[1];e(i)},n.onerror=a=>s(a)})}function ir(t,e){return t.size<=e}function or(t,e){return e.split(",").map(n=>n.trim()).some(n=>{if(n.endsWith("/*")){const a=n.slice(0,-2);return t.type.startsWith(a)}return t.type===n})}function ve(t){if(t===0)return"0 Bytes";const e=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(e));return Math.round(t/Math.pow(e,n)*100)/100+" "+s[n]}function lr(t){return t}function G(...t){return t.filter(Boolean).join(" ")}const ge={APPLICANT_ID:"metakyc_applicant_id",WORKFLOW_STATE:"metakyc_workflow_state"};function wt(t){try{localStorage.setItem(ge.APPLICANT_ID,t.toString())}catch(e){console.warn("Failed to save applicant ID to storage:",e)}}function jt(){try{const t=localStorage.getItem(ge.APPLICANT_ID);return t?parseInt(t,10):null}catch(t){return console.warn("Failed to retrieve applicant ID from storage:",t),null}}function kt(){try{localStorage.removeItem(ge.APPLICANT_ID)}catch(t){console.warn("Failed to clear applicant ID from storage:",t)}}function St(t){try{localStorage.setItem(ge.WORKFLOW_STATE,JSON.stringify(t))}catch(e){console.warn("Failed to save workflow state to storage:",e)}}function cr(){try{const t=localStorage.getItem(ge.WORKFLOW_STATE);return t?JSON.parse(t):null}catch(t){return console.warn("Failed to retrieve workflow state from storage:",t),null}}function Nt(){try{localStorage.removeItem(ge.WORKFLOW_STATE)}catch(t){console.warn("Failed to clear workflow state from storage:",t)}}function dr(){kt(),Nt()}function Ct(t){const{createOrchestrator:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(null),d=c.useRef(null),u=t||jt();c.useEffect(()=>{d.current||(d.current=e())},[e]),c.useEffect(()=>{var k;s&&u&&(wt(u),St({applicantId:u,currentStepOrder:(k=s.currentStep)==null?void 0:k.order,status:s.status,lastUpdated:new Date().toISOString(),workflowKey:s.workFlowKey,nextWorkflowKey:s.nextWorkflowKey}))},[s,u]);const x=c.useRef(!1),b=c.useRef(!1),g=c.useCallback(async()=>{if(!(!u||!d.current)){if(x.current){console.log("[Workflow] Load already in progress, skipping...");return}x.current=!0,i(!0),l(null);try{const k=await d.current.initialize(u);n(k),b.current=!0}catch(k){l(k)}finally{i(!1),x.current=!1}}},[u]);c.useEffect(()=>{u&&!b.current&&g()},[u,g]);const y=c.useCallback(async()=>{if(d.current){if(x.current){console.log("[Workflow] Refresh already in progress, skipping...");return}x.current=!0,i(!0),l(null);try{const k=await d.current.refreshProgress();n(k)}catch(k){l(k)}finally{i(!1),x.current=!1}}},[]),m=c.useCallback(async()=>{if(d.current){i(!0),l(null);try{const k=await d.current.moveToNextStep();n(k)}catch(k){l(k)}finally{i(!1)}}},[]),f=c.useCallback(async()=>{if(d.current){i(!0),l(null);try{const k=await d.current.moveToPreviousStep();n(k)}catch(k){l(k)}finally{i(!1)}}},[]),j=c.useCallback(async k=>{if(d.current){i(!0),l(null);try{await d.current.submitCurrentStep(k);const w=await d.current.refreshProgress();n(w)}catch(w){throw l(w),w}finally{i(!1)}}},[]),h=Ie.useMemo(()=>s!=null&&s.stepInfoList?[...s.stepInfoList].sort((k,w)=>k.order-w.order):[],[s==null?void 0:s.stepInfoList]),N=Ie.useMemo(()=>s?s.nextWorkflowKey&&s.nextWorkflowKey!==s.workFlowKey:!1,[s]);return{progress:s,applicantId:u,currentStep:(s==null?void 0:s.currentStep)||null,steps:h,status:(s==null?void 0:s.status)||re.None,workflowResult:(s==null?void 0:s.workflowResult)||null,workflowKey:s==null?void 0:s.workFlowKey,nextWorkflowKey:s==null?void 0:s.nextWorkflowKey,hasWorkflowChanged:N,isLoading:a,error:o,isComplete:(s==null?void 0:s.status)===re.Finished,isOnHold:(s==null?void 0:s.status)===re.OnHold,refreshProgress:y,moveToNext:m,moveBack:f,submitCurrentStep:j,orchestrator:d.current}}function At(t){const{questionnaireService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),x=c.useRef(!1),b=c.useRef(null),g=c.useCallback(async()=>{if(t){if(x.current){console.log("[Questionnaire] Load already in progress, skipping...");return}x.current=!0,i(!0),u(null);try{const m=await e.getQuestionnaire(t);n(m),b.current=t}catch(m){u(m)}finally{i(!1),x.current=!1}}},[t,e]);c.useEffect(()=>{t&&b.current!==t&&g()},[t]);const y=c.useCallback(async m=>{l(!0),u(null);try{return await e.fillQuestionnaire(m)}catch(f){throw u(f),f}finally{l(!1)}},[e]);return{questionnaire:s,isLoading:a,isSubmitting:o,error:d,load:g,submit:y}}function Et(t){const{uploadDocumentService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(0),[x,b]=c.useState(null),g=c.useRef(!1),y=c.useRef(null),m=c.useCallback(async()=>{if(t){if(g.current){console.log("[UploadDocument] Load already in progress, skipping...");return}g.current=!0,i(!0),b(null);try{const j=await e.getUploadDocument(t);n(j),y.current=t}catch(j){b(j)}finally{i(!1),g.current=!1}}},[t,e]);c.useEffect(()=>{t&&y.current!==t&&m()},[t]);const f=c.useCallback(async j=>{l(!0),u(0),b(null);try{await e.fillUploadDocument(j),u(100)}catch(h){throw b(h),h}finally{l(!1)}},[e]);return{uploadDocument:s,isLoading:a,isSubmitting:o,uploadProgress:d,error:x,load:m,submit:f}}function ur(t){const{appropriatenessTestService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),[x,b]=c.useState(null),g=c.useRef(!1),y=c.useRef(null),m=c.useCallback(async()=>{if(t){if(g.current){console.log("[AppropriatenessTest] Load already in progress, skipping...");return}g.current=!0,i(!0),u(null);try{const j=await e.getAppropriatenessTest(t);n(j),y.current=t}catch(j){u(j)}finally{i(!1),g.current=!1}}},[t,e]);c.useEffect(()=>{t&&y.current!==t&&m()},[t]);const f=c.useCallback(async j=>{l(!0),u(null);try{const h=await e.fillAppropriatenessTest(j);return b(h),h}catch(h){throw u(h),h}finally{l(!1)}},[e]);return{test:s,result:x,isLoading:a,isSubmitting:o,error:d,load:m,submit:f}}function It(t){const{overviewService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),x=c.useRef(!1),b=c.useRef(null),g=c.useCallback(async()=>{if(t){if(x.current){console.log("[Overview] Load already in progress, skipping...");return}x.current=!0,i(!0),u(null);try{const m=await e.getOverviewData(t);n(m),b.current=t}catch(m){u(m)}finally{i(!1),x.current=!1}}},[t,e]);c.useEffect(()=>{t&&b.current!==t&&g()},[t]);const y=c.useCallback(async()=>{if(t){l(!0),u(null);try{await e.passOverview(t)}catch(m){throw u(m),m}finally{l(!1)}}},[t,e]);return{overview:s,isLoading:a,isSubmitting:o,error:d,load:g,passOverview:y}}function Rt(t){const{identityService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(null),d=c.useRef(!1),u=c.useCallback(async(g,y)=>{if(t){if(d.current){console.log("[Identity] Request already in progress, skipping...");return}d.current=!0,i(!0),l(null);try{const m={applicantId:t,restart:!1,redirectUrl:g||"",ttl:y||604800};console.log("Identity request input:",m);const f=await e.identityRequest(m);return console.log("Identity request result:",f),n(f),f}catch(m){throw l(m),m}finally{i(!1),d.current=!1}}},[t,e]),x=c.useCallback(async(g,y)=>{if(t){i(!0),l(null);try{const m={applicantId:t,restart:!1,redirectUrl:g,ttl:y},f=await e.identityCompanyRequest(m);return n(f),f}catch(m){throw l(m),m}finally{i(!1)}}},[t,e]),b=c.useCallback(async()=>{if(t){if(d.current){console.log("[Identity] Restart already in progress, skipping...");return}d.current=!0,i(!0),l(null);try{const g={applicantId:t,restart:!0,redirectUrl:"",ttl:604800};console.log("Restarting identity with input:",g);const y=await e.identityRequest(g);return console.log("Restart identity result:",y),n(y),y}catch(g){throw l(g),g}finally{i(!1),d.current=!1}}},[t,e]);return{identityData:s,provider:(s==null?void 0:s.provider)||null,token:(s==null?void 0:s.publicProviderTokenObject)||null,isLoading:a,error:o,requestIdentity:u,requestCompanyIdentity:x,restartIdentity:b}}function Dt(t){const{riskScoringService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),[x,b]=c.useState(null),g=c.useRef(!1),y=c.useRef(null),m=c.useCallback(async()=>{if(t){if(g.current){console.log("[RiskScoring] Load already in progress, skipping...");return}g.current=!0,i(!0),u(null);try{const j=await e.getRiskCriterias(t);n(j),y.current=t}catch(j){u(j)}finally{i(!1),g.current=!1}}},[t,e]);c.useEffect(()=>{t&&y.current!==t&&m()},[t]);const f=c.useCallback(async j=>{l(!0),u(null);try{const h=await e.submitRiskScoring(j);return b(h),h}catch(h){throw u(h),h}finally{l(!1)}},[e]);return{criteria:s,result:x,isLoading:a,isSubmitting:o,error:d,load:m,submit:f}}function Pt(){const{applicantService:t,config:e}=ee(),[s,n]=c.useState(!1),[a,i]=c.useState(null),o=c.useRef(!1),l=c.useRef(!1),d=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(y){const m=Math.random()*16|0;return(y==="x"?m:m&3|8).toString(16)}),u=c.useCallback(async y=>{var m;if(o.current)throw console.log("[Applicant] Create already in progress, skipping..."),new Error("Creation already in progress");o.current=!0,n(!0),i(null);try{if(y.applicantAdditionalDatas||(y.applicantAdditionalDatas=[]),(m=e.identityProviders)!=null&&m.sardinai){const j=d();console.log("[SardinAI] Generated session key:",j),y.applicantAdditionalDatas.push({paramName:"sessionKey",value:j})}return await t.createApplicant(y)}catch(f){throw i(f),f}finally{n(!1),o.current=!1}},[t,e]),x=c.useCallback(async y=>{n(!0),i(null);try{return await t.createCompanyApplicant(y)}catch(m){throw i(m),m}finally{n(!1)}},[t]),b=c.useCallback(async y=>{if(l.current)throw console.log("[Applicant] Data load already in progress, skipping..."),new Error("Data load already in progress");l.current=!0,n(!0),i(null);try{return await t.getApplicantData(y)}catch(m){throw i(m),m}finally{n(!1),l.current=!1}},[t]),g=c.useCallback(async y=>{n(!0),i(null);try{await t.stopProgress(y)}catch(m){throw i(m),m}finally{n(!1)}},[t]);return{isLoading:s,error:a,createApplicant:u,createCompanyApplicant:x,getApplicantData:b,stopProgress:g}}const _=({children:t,variant:e="primary",size:s="md",isLoading:n=!1,disabled:a,className:i,...o})=>{const l="inline-flex items-center justify-center rounded-lg font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",d={primary:"bg-primary-500 text-white hover:bg-primary-600 focus:ring-primary-500",secondary:"bg-gray-200 text-gray-900 hover:bg-gray-300 focus:ring-gray-400",outline:"border-2 border-primary-500 text-primary-500 hover:bg-primary-50 focus:ring-primary-500",danger:"bg-danger-500 text-white hover:bg-danger-600 focus:ring-danger-500",ghost:"text-gray-700 hover:bg-gray-100 focus:ring-gray-400"},u={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-base",lg:"px-6 py-3 text-lg"};return r.jsxs("button",{className:G(l,d[e],u[s],i),disabled:a||n,...o,children:[n&&r.jsxs("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t]})},W=c.forwardRef(({label:t,error:e,helperText:s,leftIcon:n,rightIcon:a,className:i,...o},l)=>r.jsxs("div",{className:"w-full",children:[t&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t,o.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"relative",children:[n&&r.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none",children:n}),r.jsx("input",{ref:l,className:G("block w-full rounded-lg border px-3 py-2 text-sm transition-colors","focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent","disabled:bg-gray-100 disabled:cursor-not-allowed",e?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",n?"pl-10":"",a?"pr-10":"",i),...o}),a&&r.jsx("div",{className:"absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none",children:a})]}),e&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:e}),!e&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));W.displayName="Input";const R=({children:t,className:e,...s})=>r.jsx("div",{className:G("rounded-xl shadow-sm border",e),style:{backgroundColor:"var(--metakyc-surface, #ffffff)",borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:t}),Q=({children:t,className:e,...s})=>r.jsx("div",{className:G("px-6 py-4 border-b",e),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:t}),D=({children:t,className:e,...s})=>r.jsx("div",{className:G("px-6 py-4",e),...s,children:t}),X=({children:t,className:e,...s})=>r.jsx("div",{className:G("px-6 py-4 border-t",e),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:t}),ie=({children:t,variant:e="default",className:s,...n})=>{const a={default:"bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300",success:"bg-success-100 text-success-800 dark:bg-success-900 dark:text-success-300",danger:"bg-danger-100 text-danger-800 dark:bg-danger-900 dark:text-danger-300",warning:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300",info:"bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-300"};return r.jsx("span",{className:G("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",a[e],s),...n,children:t})},se=({size:t="md",className:e,...s})=>{const n={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"};return r.jsx("div",{className:G("flex items-center justify-center",e),...s,children:r.jsxs("svg",{className:G("animate-spin text-primary-500",n[t]),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})})},ue=c.forwardRef(({label:t,error:e,helperText:s,options:n,placeholder:a,className:i,...o},l)=>r.jsxs("div",{className:"w-full",children:[t&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t,o.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("select",{ref:l,className:G("block w-full rounded-lg border px-3 py-2 text-sm transition-colors","focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent","disabled:bg-gray-100 disabled:cursor-not-allowed",e?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",i),...o,children:[a&&r.jsx("option",{value:"",disabled:!0,children:a},"__placeholder__"),n.map((d,u)=>r.jsx("option",{value:d.value,disabled:d.disabled,children:d.label},d.value||`option-${u}`))]}),e&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:e}),!e&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));ue.displayName="Select";const Ft=({label:t,error:e,accept:s,multiple:n=!1,maxSize:a,onChange:i,value:o=[],className:l})=>{const[d,u]=c.useState(!1),x=c.useRef(null),b=h=>{if(!h)return;const N=Array.from(h);if(a&&N.filter(w=>w.size>a).length>0){const w=ve(a);alert(`Some files exceed the maximum size of ${w}`);return}i==null||i(n?[...o,...N]:[N[0]])},g=h=>{h.preventDefault(),u(!0)},y=()=>{u(!1)},m=h=>{h.preventDefault(),u(!1),b(h.dataTransfer.files)},f=()=>{var h;(h=x.current)==null||h.click()},j=h=>{const N=o.filter((k,w)=>w!==h);i==null||i(N)};return r.jsxs("div",{className:G("w-full",l),children:[t&&r.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t}),r.jsxs("div",{className:G("border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors",d?"border-primary-500 bg-primary-50 dark:bg-primary-900/20":"border-gray-300 dark:border-gray-600 hover:border-primary-500",e&&"border-danger-500"),onDragOver:g,onDragLeave:y,onDrop:m,onClick:f,children:[r.jsx("input",{ref:x,type:"file",className:"hidden",accept:s,multiple:n,onChange:h=>b(h.target.files)}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("svg",{className:"mx-auto h-12 w-12 text-gray-400",stroke:"currentColor",fill:"none",viewBox:"0 0 48 48",children:r.jsx("path",{d:"M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})}),r.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[r.jsx("span",{className:"font-medium text-primary-500",children:"Click to upload"})," or drag and drop"]}),a&&r.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum file size: ",ve(a)]})]})]}),o.length>0&&r.jsx("div",{className:"mt-3 space-y-2",children:o.map((h,N)=>r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[r.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[r.jsx("svg",{className:"h-5 w-5 text-gray-400 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{fillRule:"evenodd",d:"M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z",clipRule:"evenodd"})}),r.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate",children:h.name}),r.jsxs("span",{className:"text-xs text-gray-500",children:["(",ve(h.size),")"]})]}),r.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),j(N)},className:"ml-2 text-danger-500 hover:text-danger-700 focus:outline-none",children:r.jsx("svg",{className:"h-5 w-5",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]},N))}),e&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:e})]})},Lt=c.forwardRef(({countryCode:t="+1",onCountryCodeChange:e,className:s,...n},a)=>r.jsxs("div",{className:"w-full",children:[n.label&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[n.label,n.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:t,onChange:i=>e==null?void 0:e(i.target.value),className:G("w-20 rounded-lg border px-3 py-2 text-sm","focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent","border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white"),placeholder:"+1"}),r.jsx(W,{ref:a,type:"tel",className:G("flex-1",s),...n,label:""})]}),n.error&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:n.error})]}));Lt.displayName="PhoneInput";const Re=(t,e,s)=>{if(t&&"reportValidity"in t){const n=$.get(s,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},Se=(t,e)=>{for(const s in e.fields){const n=e.fields[s];n&&n.ref&&"reportValidity"in n.ref?Re(n.ref,s,t):n&&n.refs&&n.refs.forEach(a=>Re(a,s,t))}},De=(t,e)=>{e.shouldUseNativeValidation&&Se(t,e);const s={};for(const n in t){const a=$.get(e.fields,n),i=Object.assign(t[n]||{},{ref:a&&a.ref});if(mr(e.names||Object.keys(t),n)){const o=Object.assign({},$.get(s,n));$.set(o,"root",i),$.set(s,n,o)}else $.set(s,n,i)}return s},mr=(t,e)=>{const s=Pe(e);return t.some(n=>Pe(n).match(`^${s}\\.\\d+`))};function Pe(t){return t.replace(/\]|\[/g,"")}function Tt(t,e,s){function n(l,d){var u;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(u=l._zod).traits??(u.traits=new Set),l._zod.traits.add(t),e(l,d);for(const x in o.prototype)x in l||Object.defineProperty(l,x,{value:o.prototype[x].bind(l)});l._zod.constr=o,l._zod.def=d}const a=(s==null?void 0:s.Parent)??Object;class i extends a{}Object.defineProperty(i,"name",{value:t});function o(l){var d;const u=s!=null&&s.Parent?new i:this;n(u,l),(d=u._zod).deferred??(d.deferred=[]);for(const x of u._zod.deferred)x();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:l=>{var d,u;return s!=null&&s.Parent&&l instanceof s.Parent?!0:(u=(d=l==null?void 0:l._zod)==null?void 0:d.traits)==null?void 0:u.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class hr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const pr={};function Mt(t){return pr}function gr(t,e){return typeof e=="bigint"?e.toString():e}const Ot=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function be(t){return typeof t=="string"?t:t==null?void 0:t.message}function zt(t,e,s){var a,i,o,l,d,u;const n={...t,path:t.path??[]};if(!t.message){const x=be((o=(i=(a=t.inst)==null?void 0:a._zod.def)==null?void 0:i.error)==null?void 0:o.call(i,t))??be((l=e==null?void 0:e.error)==null?void 0:l.call(e,t))??be((d=s.customError)==null?void 0:d.call(s,t))??be((u=s.localeError)==null?void 0:u.call(s,t))??"Invalid input";n.message=x}return delete n.inst,delete n.continue,e!=null&&e.reportInput||delete n.input,n}const Bt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,gr,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},xr=Tt("$ZodError",Bt),_t=Tt("$ZodError",Bt,{Parent:Error}),fr=t=>(e,s,n,a)=>{const i=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:s,issues:[]},i);if(o instanceof Promise)throw new hr;if(o.issues.length){const l=new((a==null?void 0:a.Err)??t)(o.issues.map(d=>zt(d,i,Mt())));throw Ot(l,a==null?void 0:a.callee),l}return o.value},yr=fr(_t),br=t=>async(e,s,n,a)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:s,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const l=new((a==null?void 0:a.Err)??t)(o.issues.map(d=>zt(d,i,Mt())));throw Ot(l,a==null?void 0:a.callee),l}return o.value},vr=br(_t);function Fe(t,e){try{var s=t()}catch(n){return e(n)}return s&&s.then?s.then(void 0,e):s}function wr(t,e){for(var s={};t.length;){var n=t[0],a=n.code,i=n.message,o=n.path.join(".");if(!s[o])if("unionErrors"in n){var l=n.unionErrors[0].errors[0];s[o]={message:l.message,type:l.code}}else s[o]={message:i,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(x){return x.errors.forEach(function(b){return t.push(b)})}),e){var d=s[o].types,u=d&&d[n.code];s[o]=$.appendErrors(o,e,s,a,u?[].concat(u,n.message):n.message)}t.shift()}return s}function jr(t,e){for(var s={};t.length;){var n=t[0],a=n.code,i=n.message,o=n.path.join(".");if(!s[o])if(n.code==="invalid_union"&&n.errors.length>0){var l=n.errors[0][0];s[o]={message:l.message,type:l.code}}else s[o]={message:i,type:a};if(n.code==="invalid_union"&&n.errors.forEach(function(x){return x.forEach(function(b){return t.push(b)})}),e){var d=s[o].types,u=d&&d[n.code];s[o]=$.appendErrors(o,e,s,a,u?[].concat(u,n.message):n.message)}t.shift()}return s}function $t(t,e,s){if(s===void 0&&(s={}),function(n){return"_def"in n&&typeof n._def=="object"&&"typeName"in n._def}(t))return function(n,a,i){try{return Promise.resolve(Fe(function(){return Promise.resolve(t[s.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(o){return i.shouldUseNativeValidation&&Se({},i),{errors:{},values:s.raw?Object.assign({},n):o}})},function(o){if(function(l){return Array.isArray(l==null?void 0:l.issues)}(o))return{values:{},errors:De(wr(o.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw o}))}catch(o){return Promise.reject(o)}};if(function(n){return"_zod"in n&&typeof n._zod=="object"}(t))return function(n,a,i){try{return Promise.resolve(Fe(function(){return Promise.resolve((s.mode==="sync"?yr:vr)(t,n,e)).then(function(o){return i.shouldUseNativeValidation&&Se({},i),{errors:{},values:s.raw?Object.assign({},n):o}})},function(o){if(function(l){return l instanceof xr}(o))return{values:{},errors:De(jr(o.issues,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw o}))}catch(o){return Promise.reject(o)}};throw new Error("Invalid input: not a Zod schema")}function Kt(t){return oe.z.object({questionResults:oe.z.any()}).passthrough()}function kr(t){let e=oe.z.array(oe.z.instanceof(File));if(t.isRequired?e=e.min(1,`${t.displayName} is required`):e=e.optional(),t.multipleFile||(e=e.refine(s=>!s||s.length<=1,{message:"Only one file is allowed"})),t.maxEachFileSizeByte>0&&(e=e.refine(s=>!s||s.every(n=>n.size<=t.maxEachFileSizeByte),{message:`File size must not exceed ${Math.round(t.maxEachFileSizeByte/1024/1024)}MB`})),t.allowedTypes){const s=t.allowedTypes.split(",").map(n=>n.trim());e=e.refine(n=>n?n.every(a=>s.some(i=>i.endsWith("/*")?a.type.startsWith(i.slice(0,-2)):a.type===i)):!0,{message:"Invalid file type"})}return e}function Sr(t){const e={};return t.uploadDocumentFiles.forEach(s=>{const n=`file_${s.id}`;e[n]=kr(s)}),oe.z.object(e)}function Ut(t){return oe.z.any()}function Nr(t){return oe.z.string().min(1,"This question is required")}function Cr(t){const e={};return t.appropriatenessQuestions.forEach(s=>{const n=`question_${s.id}`;e[n]=Nr()}),oe.z.object(e)}const Ar=oe.z.any(),qt=({applicantId:t,onComplete:e,onBack:s})=>{const{questionnaire:n,isLoading:a,isSubmitting:i,error:o,submit:l}=At(t),d=c.useMemo(()=>n?{questionResults:n.questionGroups.map(f=>f.questions.map(j=>({questionId:j.id,values:[]})))}:{questionResults:[]},[n]),u=n?Kt():null,{control:x,handleSubmit:b,formState:{errors:g}}=$.useForm({resolver:u?$t(u):void 0,defaultValues:d}),y=async m=>{if(n)try{console.log("Form submitted with data:",m);const f=n.questionGroups.flatMap((h,N)=>h.questions.map((k,w)=>{var C,P,A;return{questionId:k.id,values:((A=(P=(C=m.questionResults)==null?void 0:C[N])==null?void 0:P[w])==null?void 0:A.values)||[]}}));console.log("Question results to submit:",f);const j={applicantId:t,questionnarieId:n.id,questionResults:f};console.log("Final input:",j),await l(j),e==null||e()}catch(f){console.error("Error submitting questionnaire:",f)}};return a?r.jsx(R,{children:r.jsx(D,{children:r.jsx(se,{className:"my-8"})})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading questionnaire: ",o.message]})})}):n?r.jsx("form",{onSubmit:b(y),children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.subtitle})]}),r.jsx(D,{className:"space-y-8",children:n.questionGroups.flatMap((m,f)=>m.questions.map((j,h)=>{const k=j.defaultAnswers&&j.defaultAnswers.length>0?j.showAsDropdown?j.canMultipleAnswer?"multi-select":"single-select":j.canMultipleAnswer?"checkbox":"radio":"text";return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300",children:[j.text,j.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),k==="text"&&r.jsx($.Controller,{control:x,name:`questionResults.${f}.${h}.values.0`,render:({field:w})=>{var C,P,A,S;return r.jsx(W,{value:w.value||"",onChange:w.onChange,onBlur:w.onBlur,name:w.name,placeholder:"Enter your answer...",error:(S=(A=(P=(C=g.questionResults)==null?void 0:C[f])==null?void 0:P[h])==null?void 0:A.values)==null?void 0:S.message})}}),(k==="single-select"||k==="radio")&&r.jsx($.Controller,{control:x,name:`questionResults.${f}.${h}.values.0`,render:({field:w})=>{var C,P,A,S;return r.jsx(ue,{value:w.value||"",onChange:w.onChange,onBlur:w.onBlur,name:w.name,options:j.defaultAnswers.map(F=>({value:F,label:F})),placeholder:"Select an option...",error:(S=(A=(P=(C=g.questionResults)==null?void 0:C[f])==null?void 0:P[h])==null?void 0:A.values)==null?void 0:S.message})}}),(k==="checkbox"||k==="multi-select")&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mb-2",children:"Choose one or more options"}),r.jsx($.Controller,{control:x,name:`questionResults.${f}.${h}.values`,render:({field:{value:w=[],onChange:C}})=>r.jsx("div",{className:"space-y-2",children:j.defaultAnswers.map((P,A)=>r.jsxs("label",{className:"flex items-center space-x-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Array.isArray(w)&&w.includes(P),onChange:S=>{const F=Array.isArray(w)?w:[],M=S.target.checked?[...F,P]:F.filter(q=>q!==P);C(M)},className:"h-4 w-4 text-primary-500 rounded border-gray-300 focus:ring-primary-500"}),r.jsx("span",{className:"text-sm",children:P})]},`answer-${f}-${h}-${A}`))})})]})]},j.id)}))}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{type:"submit",isLoading:i,onClick:()=>{console.log("Continue button clicked"),console.log("Form errors:",g)},children:"Continue"})]}),o&&r.jsx("div",{className:"mt-4 p-4 bg-red-50 border border-red-200 rounded",children:r.jsxs("p",{className:"text-red-600 text-sm",children:["Error: ",o.message]})})]})}):null},Ht=({applicantId:t,onComplete:e,onBack:s})=>{const{uploadDocument:n,isLoading:a,isSubmitting:i,error:o,submit:l}=Et(t),[d,u]=c.useState({}),x=async b=>{if(b.preventDefault(),!n)return;const g=await Promise.all(n.uploadDocumentFiles.map(async m=>{const f=d[m.id]||[],j=await Promise.all(f.map(async h=>({fileName:h.name,fileData:await vt(h)})));return{uploadDocumentFileId:m.id,valueList:j}})),y={applicantId:t,uploadDocumentId:n.id,uploadDocumentResults:g};await l(y),e==null||e()};return a?r.jsx(R,{children:r.jsx(D,{children:r.jsx(se,{className:"my-8"})})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading document requirements: ",o.message]})})}):n?r.jsx("form",{onSubmit:x,children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.subtitle})]}),r.jsx(D,{className:"space-y-6",children:n.uploadDocumentFiles.map(b=>r.jsx(Ft,{label:b.displayName,accept:b.allowedTypes,multiple:b.multipleFile,maxSize:b.maxEachFileSizeByte,value:d[b.id]||[],onChange:g=>{u(y=>({...y,[b.id]:g}))}},b.id))}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{type:"submit",isLoading:i,children:"Continue"})]})]})}):null},Vt=({applicantId:t,onComplete:e,onBack:s})=>{const{overview:n,isLoading:a,isSubmitting:i,error:o,passOverview:l}=It(t),d=async()=>{await l(),e==null||e()};return a?r.jsx(R,{children:r.jsx(D,{children:r.jsx(se,{className:"my-8"})})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading overview: ",o.message]})})}):n?r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:n.title||"Overview"}),n.description&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.description})]}),r.jsx(D,{className:"space-y-6",children:n.steps&&n.steps.length>0?r.jsx("div",{className:"metakyc-overview-steps space-y-3",children:n.steps.sort((u,x)=>u.order-x.order).map(u=>r.jsxs("div",{className:"metakyc-overview-step-item flex items-start p-4 rounded-lg bg-gray-50 dark:bg-gray-800",style:{border:"0"},children:[r.jsx("div",{className:"metakyc-step-icon flex-shrink-0",children:r.jsx("div",{className:"w-8 h-8 rounded-full bg-primary-500 text-white flex items-center justify-center font-medium text-sm",children:u.order+1})}),r.jsxs("div",{className:"metakyc-step-content",style:{flex:1,marginLeft:"1rem",border:"none",height:"auto",background:"transparent",margin:"0 0 0 1rem"},children:[r.jsx("h3",{className:"metakyc-step-title text-sm font-semibold text-gray-900 dark:text-white",children:u.title}),u.description&&r.jsx("p",{className:"metakyc-step-description text-sm text-gray-600 dark:text-gray-400 mt-1",children:u.description})]})]},u.order))}):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading overview data..."})})}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{onClick:d,isLoading:i,children:"Continue"})]})]}):null},Yt=({applicantId:t,onComplete:e,onBack:s})=>{const{criteria:n,isLoading:a,isSubmitting:i,error:o,submit:l}=Dt(t),[d,u]=c.useState(!1),x=c.useMemo(()=>!n||n.length===0?{criteriaValueInputs:[]}:{criteriaValueInputs:n.map(h=>({riskCriteriaId:h.id,values:[""]}))},[n]),b=n&&n.length>0?Ut():null,{control:g,handleSubmit:y,formState:{errors:m}}=$.useForm({resolver:b?$t(b):void 0,defaultValues:x});c.useEffect(()=>{!a&&n&&n.length===0&&!d&&!i&&(u(!0),l({applicantId:t,criteriaValueInputs:[]}).then(()=>e==null?void 0:e()).catch(console.error))},[a,n,d,i,l,t,e]);const f=async h=>{if(n)try{console.log("Risk scoring form submitted:",h),console.log("Criteria metadata:",n);const N=h.criteriaValueInputs.map((w,C)=>{const P=w.values||[],A=Array.isArray(P)?P.filter(S=>S&&S.trim()):P&&P.toString().trim()?[P.toString()]:[];return A.length===0?null:{riskCriteriaId:n[C].id,values:A}}).filter(w=>w!==null);console.log("Risk scoring criteriaValueInputs to submit:",N);const k={applicantId:t,criteriaValueInputs:N};console.log("Final risk scoring input:",k),await l(k),console.log("Risk scoring submitted successfully!"),e==null||e()}catch(N){throw console.error("Error submitting risk scoring:",N),N}},j=h=>h.builtInType===1?"country":!h.defaultValues||h.defaultValues.length===0?"text":h.multipleValue?"checkbox":"radio";return a?r.jsx(R,{children:r.jsxs(D,{children:[r.jsx(se,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading risk scoring criteria..."})]})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading criteria: ",o.message]})})}):!a&&n&&n.length===0?r.jsx(R,{children:r.jsxs(D,{children:[r.jsx(se,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400",children:"No risk scoring criteria required. Moving to next step..."})]})}):n?r.jsx("form",{onSubmit:y(f),children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:"Risk Assessment"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please answer the following questions for risk evaluation"})]}),r.jsx(D,{className:"space-y-8",children:n.map((h,N)=>{var w,C,P;const k=j(h);return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300",children:[h.displayName,h.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),h.description&&r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:h.description}),k==="text"&&r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values.0`,render:({field:A})=>{var S,F,M;return r.jsx(W,{...A,value:A.value||"",type:h.valueDataType===we.DigitOnly?"number":"text",placeholder:"Enter your answer...",error:(M=(F=(S=m.criteriaValueInputs)==null?void 0:S[N])==null?void 0:F.values)==null?void 0:M.message,onKeyDown:q=>{h.valueDataType===we.DigitOnly&&["e","E","+","-","."].includes(q.key)&&q.preventDefault()}})}}),k==="radio"&&h.defaultValues&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Choose one option"}),r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values.0`,render:({field:{value:A,onChange:S}})=>r.jsx("div",{className:"space-y-2",children:h.defaultValues.map((F,M)=>r.jsxs("label",{className:"flex items-center space-x-2 cursor-pointer",children:[r.jsx("input",{type:"radio",checked:A===F,onChange:()=>S(F),className:"h-4 w-4 text-primary-500 border-gray-300 focus:ring-primary-500"}),r.jsx("span",{className:"text-sm",children:F})]},`${N}-${M}`))})})]}),k==="checkbox"&&h.defaultValues&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Choose one or more options"}),r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values`,render:({field:{value:A=[],onChange:S}})=>r.jsx("div",{className:"space-y-2",children:h.defaultValues.map((F,M)=>r.jsxs("label",{className:"flex items-center space-x-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Array.isArray(A)&&A.includes(F),onChange:q=>{const K=Array.isArray(A)?A:[],p=q.target.checked?[...K,F]:K.filter(v=>v!==F);S(p)},className:"h-4 w-4 text-primary-500 rounded border-gray-300 focus:ring-primary-500"}),r.jsx("span",{className:"text-sm",children:F})]},`${N}-${M}`))})})]}),k==="country"&&r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values.0`,render:({field:A})=>{var S,F,M;return r.jsx(ue,{...A,options:[{value:"US",label:"United States"},{value:"GB",label:"United Kingdom"},{value:"DE",label:"Germany"}],placeholder:"Select a country...",error:(M=(F=(S=m.criteriaValueInputs)==null?void 0:S[N])==null?void 0:F.values)==null?void 0:M.message})}}),((P=(C=(w=m.criteriaValueInputs)==null?void 0:w[N])==null?void 0:C.values)==null?void 0:P.message)&&r.jsx("p",{className:"text-sm text-danger-500 mt-1",children:m.criteriaValueInputs[N].values.message})]},h.id)})}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{type:"submit",isLoading:i,onClick:()=>{console.log("Risk scoring submit button clicked"),console.log("Form errors:",m)},children:"Continue"})]}),o&&r.jsx("div",{className:"mt-4 p-4 bg-red-50 border border-red-200 rounded",children:r.jsxs("p",{className:"text-red-600 text-sm",children:["Error: ",o.message]})})]})}):null},Wt=({applicantId:t,onComplete:e,onBack:s})=>{const{investorCategorizationService:n}=ee(),[a,i]=c.useState(null),[o,l]=c.useState(!1),[d,u]=c.useState(null),x=async b=>{if(b.preventDefault(),a===null){u("Please select an investor type");return}l(!0),u(null);try{const g={applicantId:t,investorType:a};console.log("Submitting investor categorization:",g);const y=await n.setInvestorCategorization(g);console.log("Investor categorization result:",y),e==null||e()}catch(g){console.error("Error submitting investor categorization:",g),u(g.message||"Failed to submit investor categorization")}finally{l(!1)}};return r.jsx("form",{onSubmit:x,children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold text-gray-900 dark:text-white",children:"Which statement best describes you?"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"All Tokenise clients are treated as Retail Investors under EU regulation, which gives you the highest level of investor protection. For our internal purposes, we ask you to select the description that best matches your situation"})]}),r.jsxs(D,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-3",children:"Choose one"}),r.jsx("label",{className:`
1
+ "use strict";var Jt=Object.defineProperty;var Xt=(t,e,s)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var U=(t,e,s)=>Xt(t,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const er=require("axios"),c=require("react"),r=require("react/jsx-runtime"),$=require("react-hook-form"),oe=require("zod");function tr(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,n.get?n:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const Ie=tr(c);var T=(t=>(t[t.IdentitySdk=0]="IdentitySdk",t[t.RiskScoring=1]="RiskScoring",t[t.Questionaries=2]="Questionaries",t[t.AdditionalData=3]="AdditionalData",t[t.AppropriatenessTest=4]="AppropriatenessTest",t[t.UploadDocument=5]="UploadDocument",t[t.ManualReview=6]="ManualReview",t[t.Overview=7]="Overview",t[t.InvestorCategorization=8]="InvestorCategorization",t))(T||{}),xe=(t=>(t[t.NotStarted=0]="NotStarted",t[t.InProgress=1]="InProgress",t[t.Success=2]="Success",t[t.PartialSuccess=3]="PartialSuccess",t[t.Failed=4]="Failed",t[t.Skipped=5]="Skipped",t[t.AdminReview=6]="AdminReview",t[t.SkippedAndAdminReview=7]="SkippedAndAdminReview",t))(xe||{}),re=(t=>(t[t.None=0]="None",t[t.InProgress=1]="InProgress",t[t.Finished=2]="Finished",t[t.OnHold=3]="OnHold",t[t.IdentityPending=4]="IdentityPending",t))(re||{}),Le=(t=>(t[t.None=0]="None",t[t.RepresentativeKYC=1]="RepresentativeKYC",t[t.ManualRiskCriteria=2]="ManualRiskCriteria",t[t.UploadDocumentReview=3]="UploadDocumentReview",t[t.AdminReview=4]="AdminReview",t))(Le||{}),Te=(t=>(t[t.LowRisk=0]="LowRisk",t[t.MediumRisk=1]="MediumRisk",t[t.HighRisk=2]="HighRisk",t[t.Alert=3]="Alert",t))(Te||{}),ce=(t=>(t[t.None=0]="None",t[t.Pending=1]="Pending",t[t.Approved=2]="Approved",t[t.Rejected=3]="Rejected",t[t.ResendRequested=4]="ResendRequested",t[t.Unknown=5]="Unknown",t[t.InProgress=6]="InProgress",t))(ce||{}),de=(t=>(t[t.Approved=0]="Approved",t[t.Reject=1]="Reject",t[t.UnderReview=2]="UnderReview",t[t.Closed=3]="Closed",t[t.AdminReview=4]="AdminReview",t[t.New=5]="New",t[t.InProgress=6]="InProgress",t))(de||{}),Me=(t=>(t[t.ProviderResultPending=0]="ProviderResultPending",t[t.ProviderResultReceived=1]="ProviderResultReceived",t[t.Canceled=2]="Canceled",t[t.ExtendedToNewApplicant=3]="ExtendedToNewApplicant",t))(Me||{}),Oe=(t=>(t[t.None=0]="None",t[t.ProviderResultPending=1]="ProviderResultPending",t[t.ProviderResultReceived=2]="ProviderResultReceived",t[t.Canceled=3]="Canceled",t))(Oe||{}),te=(t=>(t[t.Onfido=0]="Onfido",t[t.Sumsub=2]="Sumsub",t[t.SardinAI=3]="SardinAI",t))(te||{}),ze=(t=>(t[t.Individual=0]="Individual",t[t.Company=1]="Company",t))(ze||{}),fe=(t=>(t[t.Male=0]="Male",t[t.Female=1]="Female",t[t.Other=2]="Other",t))(fe||{}),Be=(t=>(t[t.Image=0]="Image",t[t.Video=1]="Video",t[t.PDF=2]="PDF",t[t.OfficePDF=3]="OfficePDF",t[t.Custom=4]="Custom",t))(Be||{}),_e=(t=>(t[t.Pending=0]="Pending",t[t.Approved=1]="Approved",t[t.Rejected=2]="Rejected",t[t.RequiresRevision=3]="RequiresRevision",t))(_e||{}),$e=(t=>(t[t.SingleChoice=0]="SingleChoice",t[t.MultipleChoice=1]="MultipleChoice",t[t.Text=2]="Text",t))($e||{}),we=(t=>(t[t.String=0]="String",t[t.Integer=1]="Integer",t[t.Decimal=2]="Decimal",t[t.Boolean=3]="Boolean",t[t.Date=4]="Date",t[t.Country=5]="Country",t[t.DigitOnly=6]="DigitOnly",t))(we||{}),Ke=(t=>(t[t.Text=0]="Text",t[t.Radio=1]="Radio",t[t.Checkbox=2]="Checkbox",t[t.Dropdown=3]="Dropdown",t[t.Country=4]="Country",t))(Ke||{}),Ue=(t=>(t[t.None=0]="None",t[t.Country=1]="Country",t))(Ue||{}),J=(t=>(t[t.Individual=0]="Individual",t[t.Sophisticated=1]="Sophisticated",t[t.HighNetWorth=2]="HighNetWorth",t[t.Business=3]="Business",t))(J||{}),qe=(t=>(t[t.Retail=0]="Retail",t[t.Professional=1]="Professional",t[t.EligibleCounterparty=2]="EligibleCounterparty",t))(qe||{});const He=["firstName","lastName","email","phonenumber","dateOfBirth","street","streetNumber","zip","city","country","nationality","taxCountry","taxNumber"],rr=["firstName","lastName","title","email","dateOfBirth","phonenumber","mobileCountryCode","street","streetNumber","zip","city","country","nationality","otherNationality","defaultLanguage","taxCountry","placeOfBirth","countryOfBirth","salutation","educationLevel","occupation","taxNumber","externalRefId"],Ve={firstName:{label:"First Name",type:"text"},lastName:{label:"Last Name",type:"text"},title:{label:"Title",type:"text"},email:{label:"Email",type:"email"},dateOfBirth:{label:"Date of Birth",type:"date"},phonenumber:{label:"Phone Number",type:"tel"},mobileCountryCode:{label:"Mobile Country Code",type:"text"},street:{label:"Street",type:"text"},streetNumber:{label:"Street Number",type:"text"},zip:{label:"ZIP/Postal Code",type:"text"},city:{label:"City",type:"text"},country:{label:"Country",type:"select"},nationality:{label:"Nationality",type:"select"},otherNationality:{label:"Other Nationalities",type:"multiselect"},defaultLanguage:{label:"Default Language",type:"text"},taxCountry:{label:"Tax Country",type:"select"},placeOfBirth:{label:"Place of Birth",type:"text"},countryOfBirth:{label:"Country of Birth",type:"select"},salutation:{label:"Salutation",type:"select"},educationLevel:{label:"Education Level",type:"text"},occupation:{label:"Occupation",type:"text"},taxNumber:{label:"Tax Number",type:"text"},externalRefId:{label:"External Reference ID",type:"text"}};var V=(t=>(t.Default="default",t.Corporate="corporate",t.Fintech="fintech",t.Healthcare="healthcare",t.Modern="modern",t.Minimal="minimal",t))(V||{});const Ye={timeout:3e4,retries:3,locale:"en",endpoints:{pattern:"host-controller"}};class We{constructor(e){this.config=e}build(e,s){const n=`${e}.${s}`;if(this.config.customPaths&&this.config.customPaths[n])return this.config.customPaths[n];switch(this.config.pattern){case"host-controller":return`/api/${e}/${s}`;case"application-service":return`/services/app/${this.getServiceName(e)}/${s}`;case"custom":throw new Error(`Custom endpoint path not found for ${n}. Please provide it in customPaths.`);default:throw new Error(`Unknown endpoint pattern: ${this.config.pattern}`)}}getServiceName(e){return{Applicant:"MetaKYCVerification",Questionnaire:"MetaKYCVerification",UploadDocument:"MetaKYCVerification",AppropriatenessTest:"MetaKYCVerification",BaseInformation:"MetaKYCVerification"}[e]||e}}class ae extends Error{constructor(s,n,a,i,o){super(s);U(this,"response");this.code=n,this.details=a,this.validationErrors=i,this.name="MetaKYCError",this.response=o,Object.setPrototypeOf(this,ae.prototype)}}class he{static handleApiError(e){return new ae(e.message||"An unknown error occurred",e.code,e.details||void 0,e.validationErrors||void 0)}static handleAxiosError(e){if(e.response){const s=e.response.data;return s&&s.error?new ae(s.error.message||"An unknown error occurred",s.error.code,s.error.details||void 0,s.error.validationErrors||void 0,e.response):s&&s.result&&s.result.message?new ae(s.result.message,e.response.status,`HTTP ${e.response.status}: ${e.response.statusText}`,void 0,e.response):new ae((s==null?void 0:s.message)||e.message||"Request failed",e.response.status,`HTTP ${e.response.status}: ${e.response.statusText}`,void 0,e.response)}else return e.request?new ae("No response from server",0,"The request was made but no response was received. Please check your network connection."):new ae(e.message||"An unexpected error occurred",0,e.toString())}static isMetaKYCError(e){return e instanceof ae}}class Qe{constructor(e){U(this,"axiosInstance");U(this,"endpointBuilder");U(this,"config");this.config={...Ye,...e},this.endpointBuilder=new We(this.config.endpoints),this.axiosInstance=er.create({baseURL:this.config.baseUrl,timeout:this.config.timeout,headers:{"Content-Type":"application/json"}}),this.axiosInstance.interceptors.request.use(s=>(s.headers["Abp-TenantId"]=this.config.tenantId.toString(),s.headers.ApiKey=this.config.apiKey,s.headers["X-API-KEY"]=this.config.apiKey,this.config.locale&&(s.headers["Accept-Language"]=this.config.locale),s),s=>Promise.reject(s)),this.axiosInstance.interceptors.response.use(s=>s,async s=>{var a;const n=s.config;return((a=s.response)==null?void 0:a.status)>=500&&!n._retry&&(n._retry=!0,n._retryCount=(n._retryCount||0)+1,n._retryCount<(this.config.retries||3))?(await new Promise(i=>setTimeout(i,1e3*n._retryCount)),this.axiosInstance(n)):Promise.reject(s)})}buildEndpoint(e,s){return this.endpointBuilder.build(e,s)}async get(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.get(a,{params:n});return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}async post(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.post(a,n);return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}async put(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.put(a,n);return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}async delete(e,s,n){try{const a=this.buildEndpoint(e,s),i=await this.axiosInstance.delete(a,{params:n});return this.handleResponse(i)}catch(a){throw he.handleAxiosError(a)}}handleResponse(e){const s=e.data;if(!s.success&&s.error)throw he.handleApiError(s.error);return s}getAxiosInstance(){return this.axiosInstance}}class Ge{constructor(e){this.httpClient=e}async createApplicant(e){return(await this.httpClient.post("Applicant","ApplicantRegistrationRequest",e)).result}async createCompanyApplicant(e){return(await this.httpClient.post("Applicant","ApplicantCompanyRegistrationRequest",e)).result}async duplicateApplicant(e){return(await this.httpClient.post("Applicant","DuplicateApplicantRegistrationRequest",e)).result}async getProgress(e){return(await this.httpClient.get("Applicant","GetApplicantProgress",{applicantId:e})).result}async getProgressStatus(e){return(await this.httpClient.get("Applicant","GetApplicantProgressStaus",{applicantId:e})).result}async getApplicantData(e){return(await this.httpClient.get("Applicant","GetApplicantData",{applicantId:e})).result}async getApplicantStatus(e){return(await this.httpClient.get("Applicant","GetApplicantStatus",{applicantId:e})).result}async stopProgress(e){await this.httpClient.get("Applicant","StopProgress",{applicantId:e})}async progressStepBack(e){await this.httpClient.get("Applicant","ProgressStepBack",{applicantId:e})}async setLanguage(e,s){await this.httpClient.post("Applicant","SetApplicantLng",{applicantId:e,language:s})}async activateApplicant(e){await this.httpClient.get("Applicant","ActivateApplicant",{applicantId:e})}async deleteApplicant(e){await this.httpClient.delete("Applicant","DeleteApplicant",{applicantId:e})}async checkApplicantExists(e){return(await this.httpClient.get("Applicant","CheckApplicantIfExists",{externalRefId:e})).result}}class Ze{constructor(e){this.httpClient=e}async getQuestionnaire(e){return(await this.httpClient.get("Questionnaire","GetQuestionnaire",{applicantid:e})).result}async fillQuestionnaire(e){return(await this.httpClient.post("Applicant","FillQuestionnarie",e)).result}}class Je{constructor(e){this.httpClient=e}async getUploadDocument(e){return(await this.httpClient.get("UploadDocument","GetUploadDocument",{applicantid:e})).result}async fillUploadDocument(e){await this.httpClient.post("Applicant","FillUploadDocument",e)}async reviewUploadDocument(e){await this.httpClient.post("UploadDocument","ReviewUploadDocument",e)}}class Xe{constructor(e){this.httpClient=e}async getAppropriatenessTest(e){return(await this.httpClient.get("AppropriatenessTest","GetAppropriatenessTest",{applicantid:e})).result}async fillAppropriatenessTest(e){return(await this.httpClient.post("Applicant","FillAppropriatenessTest",e)).result}}class et{constructor(e){this.httpClient=e}async getOverviewData(e){return(await this.httpClient.get("Applicant","GetOverviewData",{ApplicantId:e})).result}async passOverview(e){await this.httpClient.get("Applicant","PassOverview",{applicantId:e})}}class tt{constructor(e){this.httpClient=e}async getRiskScoringPlan(){return(await this.httpClient.get("Applicant","GetRiskScoringPlanInfo")).result}async getRiskCriterias(e){return(await this.httpClient.get("Risk","GetCriterias",{applicantId:e})).result}async submitRiskScoring(e){return(await this.httpClient.post("Applicant","RiskScoringRequest",e)).result}}class rt{constructor(e){this.httpClient=e}async identityRequest(e){console.log("[IdentityService] Calling IdentityRequest with input:",e);const s=await this.httpClient.post("Applicant","IdentityRequest",e);return console.log("[IdentityService] IdentityRequest response:",s),s.result}async identityCompanyRequest(e){return(await this.httpClient.post("Applicant","IdentityCompanyRequest",e)).result}async restartIdentityRequest(e){const s={applicantId:e,restart:!0,redirectUrl:"",ttl:604800};return console.log("[IdentityService] Restarting identity with restart=true:",s),this.identityRequest(s)}async restartIdentityCompanyRequest(e){const s={applicantId:e,restart:!0,redirectUrl:"",ttl:604800};return this.identityCompanyRequest(s)}}class st{constructor(e){this.httpClient=e}async getCountries(e,s,n){return(await this.httpClient.get("BaseInformation","GetAllCountries",{filter:e||"",lng:s||"en",type:n})).result}async getBranches(){return(await this.httpClient.get("BaseInformation","GetBranches")).result}async getLegalEntities(){return(await this.httpClient.get("BaseInformation","GetLegalEntities")).result}}class nt{constructor(e){this.httpClient=e}async setInvestorCategorization(e){return(await this.httpClient.post("Applicant","SetInvestorCategorization",e)).result}async getInvestorCategorization(e){return(await this.httpClient.get("Applicant","GetInvestorCategorisation",{applicantId:e})).result}}const Y={name:"Default",title:"KYC Verification",logo:{url:"",height:"40px",visible:!0},colors:{primary:"#2563eb",primaryHover:"#1d4ed8",primaryLight:"#dbeafe",primaryDark:"#1e40af",secondary:"#64748b",secondaryHover:"#475569",success:"#10b981",warning:"#f59e0b",danger:"#ef4444",info:"#3b82f6",background:"#ffffff",surface:"#f9fafb",border:"#e5e7eb",textPrimary:"#111827",textSecondary:"#6b7280",textMuted:"#9ca3af"},typography:{fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},spacing:{borderRadius:"0.5rem",cardPadding:"1.5rem",inputHeight:"2.5rem"},darkMode:{colors:{background:"#111827",surface:"#1f2937",border:"#374151",textPrimary:"#f9fafb",textSecondary:"#d1d5db",textMuted:"#9ca3af"}}},at={name:"Corporate",logo:{url:"",height:"40px",visible:!0},colors:{primary:"#0052CC",primaryHover:"#0747A6",primaryLight:"#DEEBFF",primaryDark:"#0747A6",secondary:"#6B778C",secondaryHover:"#5E6C84",success:"#00875A",warning:"#FF991F",danger:"#DE350B",info:"#0065FF",background:"#ffffff",surface:"#F4F5F7",border:"#DFE1E6",textPrimary:"#172B4D",textSecondary:"#5E6C84",textMuted:"#97A0AF"},typography:{fontFamily:"system-ui, -apple-system, sans-serif"},spacing:{borderRadius:"0.25rem",cardPadding:"1.5rem",inputHeight:"2.5rem"}},it={name:"Fintech",logo:{url:"",height:"36px",visible:!0},colors:{primary:"#00B386",primaryHover:"#009973",primaryLight:"#D1FAE5",primaryDark:"#047857",secondary:"#7C3AED",secondaryHover:"#6D28D9",success:"#10B981",warning:"#F59E0B",danger:"#EF4444",info:"#3B82F6",background:"#ffffff",surface:"#F9FAFB",border:"#E5E7EB",textPrimary:"#111827",textSecondary:"#6B7280",textMuted:"#9CA3AF"},typography:{fontFamily:"Montserrat, system-ui, sans-serif"},spacing:{borderRadius:"0.75rem",cardPadding:"2rem",inputHeight:"3rem"}},ot={name:"Healthcare",logo:{url:"",height:"44px",visible:!0},colors:{primary:"#06B6D4",primaryHover:"#0891B2",primaryLight:"#CFFAFE",primaryDark:"#0E7490",secondary:"#8B5CF6",secondaryHover:"#7C3AED",success:"#059669",warning:"#D97706",danger:"#DC2626",info:"#0284C7",background:"#ffffff",surface:"#F0F9FF",border:"#E0F2FE",textPrimary:"#0F172A",textSecondary:"#475569",textMuted:"#94A3B8"},typography:{fontFamily:"Lato, system-ui, sans-serif"},spacing:{borderRadius:"0.5rem",cardPadding:"1.75rem",inputHeight:"2.75rem"},darkMode:{colors:{background:"#0F172A",surface:"#1E293B",border:"#334155",textPrimary:"#F1F5F9",textSecondary:"#CBD5E1"}}},lt={name:"Modern",logo:{url:"",height:"38px",visible:!0},colors:{primary:"#8B5CF6",primaryHover:"#7C3AED",primaryLight:"#EDE9FE",primaryDark:"#6D28D9",secondary:"#EC4899",secondaryHover:"#DB2777",success:"#10B981",warning:"#F59E0B",danger:"#EF4444",info:"#3B82F6",background:"#ffffff",surface:"#FAFAFA",border:"#E5E5E5",textPrimary:"#171717",textSecondary:"#737373",textMuted:"#A3A3A3"},typography:{fontFamily:"Poppins, system-ui, sans-serif"},spacing:{borderRadius:"1rem",cardPadding:"2rem",inputHeight:"3rem"}},ct={name:"Minimal",logo:{url:"",height:"32px",visible:!0},colors:{primary:"#000000",primaryHover:"#18181B",primaryLight:"#F4F4F5",primaryDark:"#000000",secondary:"#71717A",secondaryHover:"#52525B",success:"#22C55E",warning:"#EAB308",danger:"#EF4444",info:"#3B82F6",background:"#ffffff",surface:"#FAFAFA",border:"#E4E4E7",textPrimary:"#09090B",textSecondary:"#71717A",textMuted:"#A1A1AA"},typography:{fontFamily:"system-ui, -apple-system, sans-serif"},spacing:{borderRadius:"0.25rem",cardPadding:"1.25rem",inputHeight:"2.25rem"}},dt={[V.Default]:Y,[V.Corporate]:at,[V.Fintech]:it,[V.Healthcare]:ot,[V.Modern]:lt,[V.Minimal]:ct};function pe(t){return dt[t]||Y}class ut{constructor(e){this.httpClient=e}async getThemeConfiguration(){var e;try{const s=await this.httpClient.get("Tenant","GetThemeConfiguration");if(!s.result.isEnabled)return pe(V.Default);let n=s.result.preset?pe(s.result.preset):pe(V.Default);return s.result.title&&(n.title=s.result.title),s.result.logo&&(n.logo={...n.logo,...s.result.logo}),s.result.colors&&(n.colors={...n.colors,...s.result.colors}),s.result.typography&&(n.typography={...n.typography,...s.result.typography}),s.result.spacing&&(n.spacing={...n.spacing,...s.result.spacing}),s.result.customCSS&&(n.customCSS=s.result.customCSS),s.result.darkMode&&(n.darkMode={colors:{...(e=n.darkMode)==null?void 0:e.colors,...s.result.darkMode.colors}}),n}catch(s){return console.warn("[ThemeService] Failed to fetch theme configuration:",s),pe(V.Default)}}async saveThemeConfiguration(e){await this.httpClient.post("Tenant","SaveThemeConfiguration",e)}getAvailablePresets(){return[{id:V.Default,name:"Default"},{id:V.Corporate,name:"Corporate"},{id:V.Fintech,name:"Fintech"},{id:V.Healthcare,name:"Healthcare"},{id:V.Modern,name:"Modern"},{id:V.Minimal,name:"Minimal"}]}getPreviewTheme(e,s){const n=pe(e);return s?{...n,...s,logo:{...n.logo,...s.logo},colors:{...n.colors,...s.colors},typography:s.typography?{...n.typography,...s.typography}:n.typography,spacing:s.spacing?{...n.spacing,...s.spacing}:n.spacing}:n}}class mt{constructor(){U(this,"listeners",new Map)}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>{this.off(e,s)}}off(e,s){const n=this.listeners.get(e);n&&n.delete(s)}emit(e,s){const n=this.listeners.get(e);n&&n.forEach(a=>{try{a(s)}catch(i){console.error(`Error in event listener for "${e}":`,i)}})}clear(){this.listeners.clear()}clearEvent(e){this.listeners.delete(e)}}class ht{constructor(){U(this,"events",new mt);U(this,"_applicantId",null);U(this,"_progress",null);U(this,"_error",null)}get applicantId(){return this._applicantId}get progress(){return this._progress}get currentStep(){var e;return((e=this._progress)==null?void 0:e.currentStep)||null}get steps(){var e;return((e=this._progress)==null?void 0:e.stepInfoList)||[]}get status(){var e;return((e=this._progress)==null?void 0:e.status)||re.None}get workflowResult(){var e;return((e=this._progress)==null?void 0:e.workflowResult)||null}get error(){return this._error}get isComplete(){return this.status===re.Finished}get isOnHold(){return this.status===re.OnHold}get isInProgress(){return this.status===re.InProgress}setApplicantId(e){this._applicantId=e}updateProgress(e){var n,a;const s=(n=this._progress)==null?void 0:n.currentStep;this._progress=e,this._applicantId=e.applicantId,this._error=null,this.events.emit("progressUpdated",e),(s==null?void 0:s.order)!==((a=e.currentStep)==null?void 0:a.order)&&this.events.emit("stepChanged",e.currentStep),this.events.emit("statusChanged",e.status),e.status===re.Finished&&e.workflowResult&&this.events.emit("completed",e.workflowResult)}setError(e){this._error=e,this.events.emit("error",e)}clearError(){this._error=null}reset(){this._applicantId=null,this._progress=null,this._error=null}onProgressUpdated(e){return this.events.on("progressUpdated",e)}onStepChanged(e){return this.events.on("stepChanged",e)}onStatusChanged(e){return this.events.on("statusChanged",e)}onError(e){return this.events.on("error",e)}onCompleted(e){return this.events.on("completed",e)}clearListeners(){this.events.clear()}}class pt{constructor(){U(this,"handlers",new Map)}registerHandler(e,s){this.handlers.set(e,s)}getHandler(e){return this.handlers.get(e)}hasHandler(e){return this.handlers.has(e)}async loadStepData(e,s){const n=this.getHandler(e);if(!n)throw new Error(`No handler registered for step action: ${T[e]}`);return n.loadData(s)}async submitStepData(e,s){const n=this.getHandler(e);if(!n)throw new Error(`No handler registered for step action: ${T[e]}`);return n.submitData(s)}}class gt{constructor(e,s,n,a,i,o,l,d){U(this,"state");U(this,"stepRouter");this.applicantService=e,this.questionnaireService=s,this.uploadDocumentService=n,this.appropriatenessTestService=a,this.overviewService=i,this.riskScoringService=o,this.investorCategorizationService=d,this.state=new ht,this.stepRouter=new pt,this.registerStepHandlers()}registerStepHandlers(){this.stepRouter.registerHandler(T.Questionaries,{loadData:e=>this.questionnaireService.getQuestionnaire(e),submitData:async e=>{await this.questionnaireService.fillQuestionnaire(e)}}),this.stepRouter.registerHandler(T.UploadDocument,{loadData:e=>this.uploadDocumentService.getUploadDocument(e),submitData:e=>this.uploadDocumentService.fillUploadDocument(e)}),this.stepRouter.registerHandler(T.AppropriatenessTest,{loadData:e=>this.appropriatenessTestService.getAppropriatenessTest(e),submitData:async e=>{await this.appropriatenessTestService.fillAppropriatenessTest(e)}}),this.stepRouter.registerHandler(T.Overview,{loadData:e=>this.overviewService.getOverviewData(e),submitData:e=>this.overviewService.passOverview(e.applicantId)}),this.stepRouter.registerHandler(T.RiskScoring,{loadData:e=>this.riskScoringService.getRiskCriterias(e),submitData:async e=>{await this.riskScoringService.submitRiskScoring(e)}}),this.stepRouter.registerHandler(T.IdentitySdk,{loadData:async e=>({applicantId:e,message:"Identity verification required"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.InvestorCategorization,{loadData:e=>this.investorCategorizationService.getInvestorCategorization(e),submitData:async e=>{await this.investorCategorizationService.setInvestorCategorization(e)}}),this.stepRouter.registerHandler(T.ManualReview,{loadData:async e=>({applicantId:e,message:"Your application is under manual review"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.AdditionalData,{loadData:async e=>({applicantId:e,message:"Additional data required"}),submitData:async()=>{}})}async initialize(e){try{this.state.setApplicantId(e);const s=await this.applicantService.getProgress(e);return this.state.updateProgress(s),s}catch(s){throw this.state.setError(s),s}}async refreshProgress(){if(!this.state.applicantId)throw new Error("Workflow not initialized. Call initialize() first.");try{const e=await this.applicantService.getProgress(this.state.applicantId);return this.state.updateProgress(e),e}catch(e){throw this.state.setError(e),e}}async getCurrentStepData(){if(!this.state.currentStep)throw new Error("No current step available");if(!this.state.applicantId)throw new Error("Workflow not initialized");try{return await this.stepRouter.loadStepData(this.state.currentStep.action,this.state.applicantId)}catch(e){throw this.state.setError(e),e}}async submitCurrentStep(e){if(!this.state.currentStep)throw new Error("No current step available");try{await this.stepRouter.submitStepData(this.state.currentStep.action,e),await this.refreshProgress()}catch(s){throw this.state.setError(s),s}}async moveToNextStep(){return this.refreshProgress()}async moveToPreviousStep(){if(!this.state.applicantId)throw new Error("Workflow not initialized");try{return await this.applicantService.progressStepBack(this.state.applicantId),await this.refreshProgress()}catch(e){throw this.state.setError(e),e}}getState(){return this.state}getStepRouter(){return this.stepRouter}}function Ce(t,e){return new Promise((s,n)=>{if(e&&document.getElementById(e)){s();return}const a=document.createElement("script");a.src=t,e&&(a.id=e),a.async=!0,a.onload=()=>s(),a.onerror=()=>n(new Error(`Failed to load script: ${t}`)),document.head.appendChild(a)})}function sr(t){return!!document.getElementById(t)}function nr(t){const e=document.getElementById(t);e&&e.remove()}class xt{constructor(e){U(this,"sdk",null);U(this,"config");this.config=e}async loadSDK(){await Ce("https://cdn.sumsub.com/websdk/v2/production/websdk.js","sumsub-sdk")}async initialize(e){if(window.snsWebSdk||await this.loadSDK(),!window.snsWebSdk)throw new Error("Sumsub SDK failed to load");this.sdk=window.snsWebSdk.init(this.config.accessToken,()=>this.config.accessToken).withConf({lang:this.config.lang||"en",email:this.config.applicantEmail,phone:this.config.applicantPhone,i18n:{}}).on("idCheck.onStepCompleted",s=>{console.log("Sumsub step completed:",s)}).on("idCheck.onError",s=>{console.error("Sumsub error:",s)}).build(),this.sdk.launch(`#${e}`)}destroy(){this.sdk&&(this.sdk.destroy(),this.sdk=null)}onComplete(e){this.sdk&&this.sdk.on("idCheck.applicantStatus",s=>{s.applicantStatus==="completed"&&e(s)})}onError(e){this.sdk&&this.sdk.on("idCheck.onError",e)}}class ft{constructor(e){U(this,"sdk",null);U(this,"config");this.config=e}async loadSDK(){await Ce("https://sdk.onfido.com/v12.0.0/onfido.min.js","onfido-sdk")}async initialize(e){if(window.Onfido||await this.loadSDK(),!window.Onfido)throw new Error("Onfido SDK failed to load");this.sdk=window.Onfido.init({token:this.config.token,containerId:e,steps:this.config.steps||[{type:"welcome",options:{title:"Identity Verification"}},{type:"document",options:{documentTypes:{passport:!0,driving_licence:!0,national_identity_card:!0}}},{type:"face",options:{requestedVariant:"standard"}},{type:"complete"}],onComplete:()=>{this.config.onComplete&&this.config.onComplete()},onError:s=>{this.config.onError&&this.config.onError(s)}})}destroy(){this.sdk&&(this.sdk.tearDown(),this.sdk=null)}}class yt{constructor(e){U(this,"sardineContext",null);U(this,"config");U(this,"sessionKey");this.config=e,this.sessionKey=e.sessionKey||this.generateSessionKey()}generateSessionKey(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const s=Math.random()*16|0;return(e==="x"?s:s&3|8).toString(16)})}getSardineHost(){const{environment:e,region:s}=this.config;if(e==="sandbox")return"api.sandbox.sardine.ai";switch(s){case"eu":return"api.eu.sardine.ai";case"ca":return"api.ca.sardine.ai";case"au":return"api.au.sardine.ai";default:return"api.sardine.ai"}}async loadSDK(){return new Promise((e,s)=>{if(window._Sardine){e();return}const n=this.getSardineHost(),a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=`https://${n}/assets/loader.min.js`,a.onload=()=>{console.log("[SardinAI] SDK loaded successfully"),e()},a.onerror=()=>{s(new Error("Failed to load SardinAI SDK"))};const i=document.getElementsByTagName("script")[0];i&&i.parentNode?i.parentNode.insertBefore(a,i):document.head.appendChild(a)})}async initialize(){try{if(await this.loadSDK(),!window._Sardine)throw new Error("SardinAI SDK not available after loading");const e=this.getSardineHost(),{clientId:s,environment:n,flow:a,enableBiometrics:i,enablePortScanning:o}=this.config;this.sardineContext=window._Sardine.createContext({clientId:s,sessionKey:this.sessionKey,userIdHash:void 0,flow:a||window.location.pathname,environment:n||"production",parentElement:document.body,enableBiometrics:i!==!1,enablePortScanning:o===!0,region:this.config.region,onDeviceResponse:l=>{console.log(`[SardinAI] Device ID: ${l.deviceId}`)},onConfigUpdate:(l,d,u)=>{switch(l){case"SESSION_UPDATE_FAILED":console.error("[SardinAI] Session update failed:",u);break;case"SESSION_UPDATED":console.log("[SardinAI] Session updated:",d);break;case"SESSION_NO_UPDATE":console.log("[SardinAI] No session update");break;default:console.warn("[SardinAI] Unknown event:",l)}}}),this.addNoScriptFallback(e),console.log("[SardinAI] SDK initialized with sessionKey:",this.sessionKey)}catch(e){throw console.error("[SardinAI] Initialization failed:",e),e}}addNoScriptFallback(e){const s=document.createElement("noscript"),n=document.createElement("img"),{clientId:a,flow:i}=this.config;n.src=`https://${e}/v1/a.png?clientId=${a}&sessionKey=${this.sessionKey}&flow=${i||"kyc"}&ns=1`,n.style.display="none",s.appendChild(n),document.body.appendChild(s)}updateConfig(e){if(!this.sardineContext){console.warn("[SardinAI] Cannot update config - SDK not initialized");return}e.sessionKey&&(this.sessionKey=e.sessionKey),this.sardineContext.updateConfig({...e,onConfigUpdate:(s,n,a)=>{switch(s){case"SESSION_UPDATE_FAILED":console.error("[SardinAI] Config update failed:",a);break;case"SESSION_UPDATED":console.log("[SardinAI] Config updated:",n);break;case"SESSION_NO_UPDATE":console.log("[SardinAI] No config update needed");break}}})}getSessionKey(){return this.sessionKey}destroy(){this.sardineContext&&(this.sardineContext=null)}}class me{static createProvider(e,s){switch(e){case te.Sumsub:return new xt(s);case te.Onfido:return new ft(s);case te.SardinAI:return new yt(s);default:throw new Error(`Unsupported identity provider: ${e}`)}}static parseProviderConfig(e,s,n){var a;switch(e){case te.Sumsub:return{accessToken:s.accessToken||s.token,applicantEmail:s.email,applicantPhone:s.phone,externalUserId:s.externalUserId,lang:s.lang||"en"};case te.Onfido:return{token:s.token||s.sdkToken};case te.SardinAI:const i=((a=n==null?void 0:n.identityProviders)==null?void 0:a.sardinai)||{};return{clientId:i.clientId||s.clientId,sessionKey:i.sessionKey||s.sessionKey,environment:i.environment||s.environment||"production",flow:i.flow||s.flow,region:i.region,enableBiometrics:i.enableBiometrics,enablePortScanning:i.enablePortScanning};default:throw new Error(`Unsupported identity provider: ${e}`)}}}class bt{constructor(e){U(this,"currentTheme",Y);U(this,"customStyleElement",null);U(this,"container");this.container=e||document.documentElement}applyTheme(e){this.currentTheme=this.mergeWithDefault(e),this.applyColors(this.currentTheme.colors),this.currentTheme.typography&&this.applyTypography(this.currentTheme.typography),this.currentTheme.spacing&&this.applySpacing(this.currentTheme.spacing),this.currentTheme.customCSS&&this.injectCustomCSS(this.currentTheme.customCSS),console.log("[ThemeManager] Theme applied:",this.currentTheme.name||"Custom")}applyColors(e){var n;const s={primary:e.primary,"primary-hover":e.primaryHover,"primary-light":e.primaryLight,"primary-dark":e.primaryDark,secondary:e.secondary,"secondary-hover":e.secondaryHover,success:e.success,warning:e.warning,danger:e.danger,info:e.info,background:e.background,surface:e.surface,border:e.border,"text-primary":e.textPrimary,"text-secondary":e.textSecondary,"text-muted":e.textMuted};Object.entries(s).forEach(([a,i])=>{this.container.style.setProperty(`--metakyc-${a}`,i)}),(n=this.currentTheme.darkMode)!=null&&n.colors&&this.applyDarkModeColors(this.currentTheme.darkMode.colors)}applyDarkModeColors(e){Object.entries(e).forEach(([s,n])=>{if(n){const a=`--metakyc-dark-${this.kebabCase(s)}`;this.container.style.setProperty(a,n)}})}applyTypography(e){e&&(e.fontFamily&&this.container.style.setProperty("--metakyc-font-family",e.fontFamily),e.headingFont&&this.container.style.setProperty("--metakyc-heading-font",e.headingFont),e.fontSize&&Object.entries(e.fontSize).forEach(([s,n])=>{this.container.style.setProperty(`--metakyc-font-size-${s}`,n)}),e.fontWeight&&Object.entries(e.fontWeight).forEach(([s,n])=>{this.container.style.setProperty(`--metakyc-font-weight-${s}`,n.toString())}))}applySpacing(e){e&&Object.entries(e).forEach(([s,n])=>{const a=`--metakyc-${this.kebabCase(s)}`;this.container.style.setProperty(a,n)})}injectCustomCSS(e){this.customStyleElement&&this.customStyleElement.remove(),this.customStyleElement=document.createElement("style"),this.customStyleElement.id="metakyc-custom-css",this.customStyleElement.textContent=e,document.head.appendChild(this.customStyleElement)}mergeWithDefault(e){var s;return{name:e.name||Y.name,title:e.title||Y.title,logo:{...Y.logo,...e.logo},colors:{...Y.colors,...e.colors},typography:e.typography?{...Y.typography,...e.typography}:Y.typography,spacing:e.spacing?{...Y.spacing,...e.spacing}:Y.spacing,customCSS:e.customCSS,darkMode:e.darkMode?{colors:{...(s=Y.darkMode)==null?void 0:s.colors,...e.darkMode.colors}}:Y.darkMode}}getCurrentTheme(){return this.currentTheme}resetTheme(){this.applyTheme(Y)}cleanup(){this.customStyleElement&&(this.customStyleElement.remove(),this.customStyleElement=null)}kebabCase(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}}const Ae=c.createContext(null),ar=({config:t,children:e})=>{const[s,n]=c.useState(null),a=c.useRef(!1),i=c.useRef(!1),o=c.useMemo(()=>{const d=new Qe(t),u=new Ge(d),x=new Ze(d),b=new Je(d),g=new Xe(d),y=new et(d),m=new tt(d),f=new rt(d),j=new st(d),h=new nt(d),N=new ut(d),k=new bt;return{httpClient:d,applicantService:u,questionnaireService:x,uploadDocumentService:b,appropriatenessTestService:g,overviewService:y,riskScoringService:m,identityService:f,baseInformationService:j,investorCategorizationService:h,themeService:N,themeManager:k}},[t]),l=c.useMemo(()=>({config:t,...o,currentTheme:s,createOrchestrator:()=>new gt(o.applicantService,o.questionnaireService,o.uploadDocumentService,o.appropriatenessTestService,o.overviewService,o.riskScoringService,o.identityService,o.investorCategorizationService)}),[t,o,s]);return c.useEffect(()=>((async()=>{if(a.current||i.current){console.log("[MetaKYC] Theme already loading or loaded, skipping...");return}a.current=!0;try{if(t.theme){console.log("[MetaKYC] Applying static theme from config"),o.themeManager.applyTheme(t.theme),n(o.themeManager.getCurrentTheme()),i.current=!0;return}console.log("[MetaKYC] Fetching theme from backend...");const u=await o.themeService.getThemeConfiguration();o.themeManager.applyTheme(u),n(o.themeManager.getCurrentTheme()),i.current=!0,console.log("[MetaKYC] Theme loaded and applied",u)}catch(u){console.warn("[MetaKYC] Failed to load theme, using default:",u),n(o.themeManager.getCurrentTheme()),i.current=!0}finally{a.current=!1}})(),()=>{o.themeManager.cleanup()}),[]),r.jsx(Ae.Provider,{value:l,children:e})};function ee(){const t=c.useContext(Ae);if(!t)throw new Error("useMetaKYC must be used within a MetaKYCProvider");return t}async function vt(t){return new Promise((e,s)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>{const i=n.result.split(",")[1];e(i)},n.onerror=a=>s(a)})}function ir(t,e){return t.size<=e}function or(t,e){return e.split(",").map(n=>n.trim()).some(n=>{if(n.endsWith("/*")){const a=n.slice(0,-2);return t.type.startsWith(a)}return t.type===n})}function ve(t){if(t===0)return"0 Bytes";const e=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(e));return Math.round(t/Math.pow(e,n)*100)/100+" "+s[n]}function lr(t){return t}function G(...t){return t.filter(Boolean).join(" ")}const ge={APPLICANT_ID:"metakyc_applicant_id",WORKFLOW_STATE:"metakyc_workflow_state"};function wt(t){try{localStorage.setItem(ge.APPLICANT_ID,t.toString())}catch(e){console.warn("Failed to save applicant ID to storage:",e)}}function jt(){try{const t=localStorage.getItem(ge.APPLICANT_ID);return t?parseInt(t,10):null}catch(t){return console.warn("Failed to retrieve applicant ID from storage:",t),null}}function kt(){try{localStorage.removeItem(ge.APPLICANT_ID)}catch(t){console.warn("Failed to clear applicant ID from storage:",t)}}function St(t){try{localStorage.setItem(ge.WORKFLOW_STATE,JSON.stringify(t))}catch(e){console.warn("Failed to save workflow state to storage:",e)}}function cr(){try{const t=localStorage.getItem(ge.WORKFLOW_STATE);return t?JSON.parse(t):null}catch(t){return console.warn("Failed to retrieve workflow state from storage:",t),null}}function Nt(){try{localStorage.removeItem(ge.WORKFLOW_STATE)}catch(t){console.warn("Failed to clear workflow state from storage:",t)}}function dr(){kt(),Nt()}function Ct(t){const{createOrchestrator:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(null),d=c.useRef(null),u=t||jt();c.useEffect(()=>{d.current||(d.current=e())},[e]),c.useEffect(()=>{var k;s&&u&&(wt(u),St({applicantId:u,currentStepOrder:(k=s.currentStep)==null?void 0:k.order,status:s.status,lastUpdated:new Date().toISOString(),workflowKey:s.workFlowKey,nextWorkflowKey:s.nextWorkflowKey}))},[s,u]);const x=c.useRef(!1),b=c.useRef(!1),g=c.useCallback(async()=>{if(!(!u||!d.current)){if(x.current){console.log("[Workflow] Load already in progress, skipping...");return}x.current=!0,i(!0),l(null);try{const k=await d.current.initialize(u);n(k),b.current=!0}catch(k){l(k)}finally{i(!1),x.current=!1}}},[u]);c.useEffect(()=>{u&&!b.current&&g()},[u,g]);const y=c.useCallback(async()=>{if(d.current){if(x.current){console.log("[Workflow] Refresh already in progress, skipping...");return}x.current=!0,i(!0),l(null);try{const k=await d.current.refreshProgress();n(k)}catch(k){l(k)}finally{i(!1),x.current=!1}}},[]),m=c.useCallback(async()=>{if(d.current){i(!0),l(null);try{const k=await d.current.moveToNextStep();n(k)}catch(k){l(k)}finally{i(!1)}}},[]),f=c.useCallback(async()=>{if(d.current){i(!0),l(null);try{const k=await d.current.moveToPreviousStep();n(k)}catch(k){l(k)}finally{i(!1)}}},[]),j=c.useCallback(async k=>{if(d.current){i(!0),l(null);try{await d.current.submitCurrentStep(k);const w=await d.current.refreshProgress();n(w)}catch(w){throw l(w),w}finally{i(!1)}}},[]),h=Ie.useMemo(()=>s!=null&&s.stepInfoList?[...s.stepInfoList].sort((k,w)=>k.order-w.order):[],[s==null?void 0:s.stepInfoList]),N=Ie.useMemo(()=>s?s.nextWorkflowKey&&s.nextWorkflowKey!==s.workFlowKey:!1,[s]);return{progress:s,applicantId:u,currentStep:(s==null?void 0:s.currentStep)||null,steps:h,status:(s==null?void 0:s.status)||re.None,workflowResult:(s==null?void 0:s.workflowResult)||null,workflowKey:s==null?void 0:s.workFlowKey,nextWorkflowKey:s==null?void 0:s.nextWorkflowKey,hasWorkflowChanged:N,isLoading:a,error:o,isComplete:(s==null?void 0:s.status)===re.Finished,isOnHold:(s==null?void 0:s.status)===re.OnHold,refreshProgress:y,moveToNext:m,moveBack:f,submitCurrentStep:j,orchestrator:d.current}}function At(t){const{questionnaireService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),x=c.useRef(!1),b=c.useRef(null),g=c.useCallback(async()=>{if(t){if(x.current){console.log("[Questionnaire] Load already in progress, skipping...");return}x.current=!0,i(!0),u(null);try{const m=await e.getQuestionnaire(t);n(m),b.current=t}catch(m){u(m)}finally{i(!1),x.current=!1}}},[t,e]);c.useEffect(()=>{t&&b.current!==t&&g()},[t]);const y=c.useCallback(async m=>{l(!0),u(null);try{return await e.fillQuestionnaire(m)}catch(f){throw u(f),f}finally{l(!1)}},[e]);return{questionnaire:s,isLoading:a,isSubmitting:o,error:d,load:g,submit:y}}function Et(t){const{uploadDocumentService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(0),[x,b]=c.useState(null),g=c.useRef(!1),y=c.useRef(null),m=c.useCallback(async()=>{if(t){if(g.current){console.log("[UploadDocument] Load already in progress, skipping...");return}g.current=!0,i(!0),b(null);try{const j=await e.getUploadDocument(t);n(j),y.current=t}catch(j){b(j)}finally{i(!1),g.current=!1}}},[t,e]);c.useEffect(()=>{t&&y.current!==t&&m()},[t]);const f=c.useCallback(async j=>{l(!0),u(0),b(null);try{await e.fillUploadDocument(j),u(100)}catch(h){throw b(h),h}finally{l(!1)}},[e]);return{uploadDocument:s,isLoading:a,isSubmitting:o,uploadProgress:d,error:x,load:m,submit:f}}function ur(t){const{appropriatenessTestService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),[x,b]=c.useState(null),g=c.useRef(!1),y=c.useRef(null),m=c.useCallback(async()=>{if(t){if(g.current){console.log("[AppropriatenessTest] Load already in progress, skipping...");return}g.current=!0,i(!0),u(null);try{const j=await e.getAppropriatenessTest(t);n(j),y.current=t}catch(j){u(j)}finally{i(!1),g.current=!1}}},[t,e]);c.useEffect(()=>{t&&y.current!==t&&m()},[t]);const f=c.useCallback(async j=>{l(!0),u(null);try{const h=await e.fillAppropriatenessTest(j);return b(h),h}catch(h){throw u(h),h}finally{l(!1)}},[e]);return{test:s,result:x,isLoading:a,isSubmitting:o,error:d,load:m,submit:f}}function It(t){const{overviewService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),x=c.useRef(!1),b=c.useRef(null),g=c.useCallback(async()=>{if(t){if(x.current){console.log("[Overview] Load already in progress, skipping...");return}x.current=!0,i(!0),u(null);try{const m=await e.getOverviewData(t);n(m),b.current=t}catch(m){u(m)}finally{i(!1),x.current=!1}}},[t,e]);c.useEffect(()=>{t&&b.current!==t&&g()},[t]);const y=c.useCallback(async()=>{if(t){l(!0),u(null);try{await e.passOverview(t)}catch(m){throw u(m),m}finally{l(!1)}}},[t,e]);return{overview:s,isLoading:a,isSubmitting:o,error:d,load:g,passOverview:y}}function Rt(t){const{identityService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(null),d=c.useRef(!1),u=c.useCallback(async(g,y)=>{if(t){if(d.current){console.log("[Identity] Request already in progress, skipping...");return}d.current=!0,i(!0),l(null);try{const m={applicantId:t,restart:!1,redirectUrl:g||"",ttl:y||604800};console.log("Identity request input:",m);const f=await e.identityRequest(m);return console.log("Identity request result:",f),n(f),f}catch(m){throw l(m),m}finally{i(!1),d.current=!1}}},[t,e]),x=c.useCallback(async(g,y)=>{if(t){i(!0),l(null);try{const m={applicantId:t,restart:!1,redirectUrl:g,ttl:y},f=await e.identityCompanyRequest(m);return n(f),f}catch(m){throw l(m),m}finally{i(!1)}}},[t,e]),b=c.useCallback(async()=>{if(t){if(d.current){console.log("[Identity] Restart already in progress, skipping...");return}d.current=!0,i(!0),l(null);try{const g={applicantId:t,restart:!0,redirectUrl:"",ttl:604800};console.log("Restarting identity with input:",g);const y=await e.identityRequest(g);return console.log("Restart identity result:",y),n(y),y}catch(g){throw l(g),g}finally{i(!1),d.current=!1}}},[t,e]);return{identityData:s,provider:(s==null?void 0:s.provider)||null,token:(s==null?void 0:s.publicProviderTokenObject)||null,isLoading:a,error:o,requestIdentity:u,requestCompanyIdentity:x,restartIdentity:b}}function Dt(t){const{riskScoringService:e}=ee(),[s,n]=c.useState(null),[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),[x,b]=c.useState(null),g=c.useRef(!1),y=c.useRef(null),m=c.useCallback(async()=>{if(t){if(g.current){console.log("[RiskScoring] Load already in progress, skipping...");return}g.current=!0,i(!0),u(null);try{const j=await e.getRiskCriterias(t);n(j),y.current=t}catch(j){u(j)}finally{i(!1),g.current=!1}}},[t,e]);c.useEffect(()=>{t&&y.current!==t&&m()},[t]);const f=c.useCallback(async j=>{l(!0),u(null);try{const h=await e.submitRiskScoring(j);return b(h),h}catch(h){throw u(h),h}finally{l(!1)}},[e]);return{criteria:s,result:x,isLoading:a,isSubmitting:o,error:d,load:m,submit:f}}function Pt(){const{applicantService:t,config:e}=ee(),[s,n]=c.useState(!1),[a,i]=c.useState(null),o=c.useRef(!1),l=c.useRef(!1),d=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(y){const m=Math.random()*16|0;return(y==="x"?m:m&3|8).toString(16)}),u=c.useCallback(async y=>{var m;if(o.current)throw console.log("[Applicant] Create already in progress, skipping..."),new Error("Creation already in progress");o.current=!0,n(!0),i(null);try{if(y.applicantAdditionalDatas||(y.applicantAdditionalDatas=[]),(m=e.identityProviders)!=null&&m.sardinai){const j=d();console.log("[SardinAI] Generated session key:",j),y.applicantAdditionalDatas.push({paramName:"sessionKey",value:j})}return await t.createApplicant(y)}catch(f){throw i(f),f}finally{n(!1),o.current=!1}},[t,e]),x=c.useCallback(async y=>{n(!0),i(null);try{return await t.createCompanyApplicant(y)}catch(m){throw i(m),m}finally{n(!1)}},[t]),b=c.useCallback(async y=>{if(l.current)throw console.log("[Applicant] Data load already in progress, skipping..."),new Error("Data load already in progress");l.current=!0,n(!0),i(null);try{return await t.getApplicantData(y)}catch(m){throw i(m),m}finally{n(!1),l.current=!1}},[t]),g=c.useCallback(async y=>{n(!0),i(null);try{await t.stopProgress(y)}catch(m){throw i(m),m}finally{n(!1)}},[t]);return{isLoading:s,error:a,createApplicant:u,createCompanyApplicant:x,getApplicantData:b,stopProgress:g}}const _=({children:t,variant:e="primary",size:s="md",isLoading:n=!1,disabled:a,className:i,...o})=>{const l="inline-flex items-center justify-center rounded-lg font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",d={primary:"bg-primary-500 text-white hover:bg-primary-600 focus:ring-primary-500",secondary:"bg-gray-200 text-gray-900 hover:bg-gray-300 focus:ring-gray-400",outline:"border-2 border-primary-500 text-primary-500 hover:bg-primary-50 focus:ring-primary-500",danger:"bg-danger-500 text-white hover:bg-danger-600 focus:ring-danger-500",ghost:"text-gray-700 hover:bg-gray-100 focus:ring-gray-400"},u={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-base",lg:"px-6 py-3 text-lg"};return r.jsxs("button",{className:G(l,d[e],u[s],i),disabled:a||n,...o,children:[n&&r.jsxs("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t]})},W=c.forwardRef(({label:t,error:e,helperText:s,leftIcon:n,rightIcon:a,className:i,...o},l)=>r.jsxs("div",{className:"w-full",children:[t&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t,o.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"relative",children:[n&&r.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none",children:n}),r.jsx("input",{ref:l,className:G("block w-full rounded-lg border px-3 py-2 text-sm transition-colors","focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent","disabled:bg-gray-100 disabled:cursor-not-allowed",e?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",n?"pl-10":"",a?"pr-10":"",i),...o}),a&&r.jsx("div",{className:"absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none",children:a})]}),e&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:e}),!e&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));W.displayName="Input";const R=({children:t,className:e,...s})=>r.jsx("div",{className:G("rounded-xl shadow-sm border",e),style:{backgroundColor:"var(--metakyc-surface, #ffffff)",borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:t}),Q=({children:t,className:e,...s})=>r.jsx("div",{className:G("px-6 py-4 border-b",e),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:t}),D=({children:t,className:e,...s})=>r.jsx("div",{className:G("px-6 py-4",e),...s,children:t}),X=({children:t,className:e,...s})=>r.jsx("div",{className:G("px-6 py-4 border-t",e),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:t}),ie=({children:t,variant:e="default",className:s,...n})=>{const a={default:"bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300",success:"bg-success-100 text-success-800 dark:bg-success-900 dark:text-success-300",danger:"bg-danger-100 text-danger-800 dark:bg-danger-900 dark:text-danger-300",warning:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300",info:"bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-300"};return r.jsx("span",{className:G("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",a[e],s),...n,children:t})},se=({size:t="md",className:e,...s})=>{const n={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"};return r.jsx("div",{className:G("flex items-center justify-center",e),...s,children:r.jsxs("svg",{className:G("animate-spin text-primary-500",n[t]),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})})},ue=c.forwardRef(({label:t,error:e,helperText:s,options:n,placeholder:a,className:i,...o},l)=>r.jsxs("div",{className:"w-full",children:[t&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t,o.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("select",{ref:l,className:G("block w-full rounded-lg border px-3 py-2 text-sm transition-colors","focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent","disabled:bg-gray-100 disabled:cursor-not-allowed",e?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",i),...o,children:[a&&r.jsx("option",{value:"",disabled:!0,children:a},"__placeholder__"),n.map((d,u)=>r.jsx("option",{value:d.value,disabled:d.disabled,children:d.label},d.value||`option-${u}`))]}),e&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:e}),!e&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));ue.displayName="Select";const Ft=({label:t,error:e,accept:s,multiple:n=!1,maxSize:a,onChange:i,value:o=[],className:l})=>{const[d,u]=c.useState(!1),x=c.useRef(null),b=h=>{if(!h)return;const N=Array.from(h);if(a&&N.filter(w=>w.size>a).length>0){const w=ve(a);alert(`Some files exceed the maximum size of ${w}`);return}i==null||i(n?[...o,...N]:[N[0]])},g=h=>{h.preventDefault(),u(!0)},y=()=>{u(!1)},m=h=>{h.preventDefault(),u(!1),b(h.dataTransfer.files)},f=()=>{var h;(h=x.current)==null||h.click()},j=h=>{const N=o.filter((k,w)=>w!==h);i==null||i(N)};return r.jsxs("div",{className:G("w-full",l),children:[t&&r.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t}),r.jsxs("div",{className:G("border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors",d?"border-primary-500 bg-primary-50 dark:bg-primary-900/20":"border-gray-300 dark:border-gray-600 hover:border-primary-500",e&&"border-danger-500"),onDragOver:g,onDragLeave:y,onDrop:m,onClick:f,children:[r.jsx("input",{ref:x,type:"file",className:"hidden",accept:s,multiple:n,onChange:h=>b(h.target.files)}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("svg",{className:"mx-auto h-12 w-12 text-gray-400",stroke:"currentColor",fill:"none",viewBox:"0 0 48 48",children:r.jsx("path",{d:"M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})}),r.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[r.jsx("span",{className:"font-medium text-primary-500",children:"Click to upload"})," or drag and drop"]}),a&&r.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum file size: ",ve(a)]})]})]}),o.length>0&&r.jsx("div",{className:"mt-3 space-y-2",children:o.map((h,N)=>r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[r.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[r.jsx("svg",{className:"h-5 w-5 text-gray-400 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{fillRule:"evenodd",d:"M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z",clipRule:"evenodd"})}),r.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate",children:h.name}),r.jsxs("span",{className:"text-xs text-gray-500",children:["(",ve(h.size),")"]})]}),r.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),j(N)},className:"ml-2 text-danger-500 hover:text-danger-700 focus:outline-none",children:r.jsx("svg",{className:"h-5 w-5",fill:"currentColor",viewBox:"0 0 20 20",children:r.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]},N))}),e&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:e})]})},Lt=c.forwardRef(({countryCode:t="+1",onCountryCodeChange:e,className:s,...n},a)=>r.jsxs("div",{className:"w-full",children:[n.label&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[n.label,n.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:t,onChange:i=>e==null?void 0:e(i.target.value),className:G("w-20 rounded-lg border px-3 py-2 text-sm","focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent","border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white"),placeholder:"+1"}),r.jsx(W,{ref:a,type:"tel",className:G("flex-1",s),...n,label:""})]}),n.error&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:n.error})]}));Lt.displayName="PhoneInput";const Re=(t,e,s)=>{if(t&&"reportValidity"in t){const n=$.get(s,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},Se=(t,e)=>{for(const s in e.fields){const n=e.fields[s];n&&n.ref&&"reportValidity"in n.ref?Re(n.ref,s,t):n&&n.refs&&n.refs.forEach(a=>Re(a,s,t))}},De=(t,e)=>{e.shouldUseNativeValidation&&Se(t,e);const s={};for(const n in t){const a=$.get(e.fields,n),i=Object.assign(t[n]||{},{ref:a&&a.ref});if(mr(e.names||Object.keys(t),n)){const o=Object.assign({},$.get(s,n));$.set(o,"root",i),$.set(s,n,o)}else $.set(s,n,i)}return s},mr=(t,e)=>{const s=Pe(e);return t.some(n=>Pe(n).match(`^${s}\\.\\d+`))};function Pe(t){return t.replace(/\]|\[/g,"")}function Tt(t,e,s){function n(l,d){var u;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(u=l._zod).traits??(u.traits=new Set),l._zod.traits.add(t),e(l,d);for(const x in o.prototype)x in l||Object.defineProperty(l,x,{value:o.prototype[x].bind(l)});l._zod.constr=o,l._zod.def=d}const a=(s==null?void 0:s.Parent)??Object;class i extends a{}Object.defineProperty(i,"name",{value:t});function o(l){var d;const u=s!=null&&s.Parent?new i:this;n(u,l),(d=u._zod).deferred??(d.deferred=[]);for(const x of u._zod.deferred)x();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:l=>{var d,u;return s!=null&&s.Parent&&l instanceof s.Parent?!0:(u=(d=l==null?void 0:l._zod)==null?void 0:d.traits)==null?void 0:u.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class hr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const pr={};function Mt(t){return pr}function gr(t,e){return typeof e=="bigint"?e.toString():e}const Ot=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function be(t){return typeof t=="string"?t:t==null?void 0:t.message}function zt(t,e,s){var a,i,o,l,d,u;const n={...t,path:t.path??[]};if(!t.message){const x=be((o=(i=(a=t.inst)==null?void 0:a._zod.def)==null?void 0:i.error)==null?void 0:o.call(i,t))??be((l=e==null?void 0:e.error)==null?void 0:l.call(e,t))??be((d=s.customError)==null?void 0:d.call(s,t))??be((u=s.localeError)==null?void 0:u.call(s,t))??"Invalid input";n.message=x}return delete n.inst,delete n.continue,e!=null&&e.reportInput||delete n.input,n}const Bt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,gr,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},xr=Tt("$ZodError",Bt),_t=Tt("$ZodError",Bt,{Parent:Error}),fr=t=>(e,s,n,a)=>{const i=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:s,issues:[]},i);if(o instanceof Promise)throw new hr;if(o.issues.length){const l=new((a==null?void 0:a.Err)??t)(o.issues.map(d=>zt(d,i,Mt())));throw Ot(l,a==null?void 0:a.callee),l}return o.value},yr=fr(_t),br=t=>async(e,s,n,a)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:s,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const l=new((a==null?void 0:a.Err)??t)(o.issues.map(d=>zt(d,i,Mt())));throw Ot(l,a==null?void 0:a.callee),l}return o.value},vr=br(_t);function Fe(t,e){try{var s=t()}catch(n){return e(n)}return s&&s.then?s.then(void 0,e):s}function wr(t,e){for(var s={};t.length;){var n=t[0],a=n.code,i=n.message,o=n.path.join(".");if(!s[o])if("unionErrors"in n){var l=n.unionErrors[0].errors[0];s[o]={message:l.message,type:l.code}}else s[o]={message:i,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(x){return x.errors.forEach(function(b){return t.push(b)})}),e){var d=s[o].types,u=d&&d[n.code];s[o]=$.appendErrors(o,e,s,a,u?[].concat(u,n.message):n.message)}t.shift()}return s}function jr(t,e){for(var s={};t.length;){var n=t[0],a=n.code,i=n.message,o=n.path.join(".");if(!s[o])if(n.code==="invalid_union"&&n.errors.length>0){var l=n.errors[0][0];s[o]={message:l.message,type:l.code}}else s[o]={message:i,type:a};if(n.code==="invalid_union"&&n.errors.forEach(function(x){return x.forEach(function(b){return t.push(b)})}),e){var d=s[o].types,u=d&&d[n.code];s[o]=$.appendErrors(o,e,s,a,u?[].concat(u,n.message):n.message)}t.shift()}return s}function $t(t,e,s){if(s===void 0&&(s={}),function(n){return"_def"in n&&typeof n._def=="object"&&"typeName"in n._def}(t))return function(n,a,i){try{return Promise.resolve(Fe(function(){return Promise.resolve(t[s.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(o){return i.shouldUseNativeValidation&&Se({},i),{errors:{},values:s.raw?Object.assign({},n):o}})},function(o){if(function(l){return Array.isArray(l==null?void 0:l.issues)}(o))return{values:{},errors:De(wr(o.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw o}))}catch(o){return Promise.reject(o)}};if(function(n){return"_zod"in n&&typeof n._zod=="object"}(t))return function(n,a,i){try{return Promise.resolve(Fe(function(){return Promise.resolve((s.mode==="sync"?yr:vr)(t,n,e)).then(function(o){return i.shouldUseNativeValidation&&Se({},i),{errors:{},values:s.raw?Object.assign({},n):o}})},function(o){if(function(l){return l instanceof xr}(o))return{values:{},errors:De(jr(o.issues,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw o}))}catch(o){return Promise.reject(o)}};throw new Error("Invalid input: not a Zod schema")}function Kt(t){return oe.z.object({questionResults:oe.z.any()}).passthrough()}function kr(t){let e=oe.z.array(oe.z.instanceof(File));if(t.isRequired?e=e.min(1,`${t.displayName} is required`):e=e.optional(),t.multipleFile||(e=e.refine(s=>!s||s.length<=1,{message:"Only one file is allowed"})),t.maxEachFileSizeByte>0&&(e=e.refine(s=>!s||s.every(n=>n.size<=t.maxEachFileSizeByte),{message:`File size must not exceed ${Math.round(t.maxEachFileSizeByte/1024/1024)}MB`})),t.allowedTypes){const s=t.allowedTypes.split(",").map(n=>n.trim());e=e.refine(n=>n?n.every(a=>s.some(i=>i.endsWith("/*")?a.type.startsWith(i.slice(0,-2)):a.type===i)):!0,{message:"Invalid file type"})}return e}function Sr(t){const e={};return t.uploadDocumentFiles.forEach(s=>{const n=`file_${s.id}`;e[n]=kr(s)}),oe.z.object(e)}function Ut(t){return oe.z.any()}function Nr(t){return oe.z.string().min(1,"This question is required")}function Cr(t){const e={};return t.appropriatenessQuestions.forEach(s=>{const n=`question_${s.id}`;e[n]=Nr()}),oe.z.object(e)}const Ar=oe.z.any(),qt=({applicantId:t,onComplete:e,onBack:s})=>{const{questionnaire:n,isLoading:a,isSubmitting:i,error:o,submit:l}=At(t),d=c.useMemo(()=>n?{questionResults:n.questionGroups.map(f=>f.questions.map(j=>({questionId:j.id,values:[]})))}:{questionResults:[]},[n]),u=n?Kt():null,{control:x,handleSubmit:b,formState:{errors:g}}=$.useForm({resolver:u?$t(u):void 0,defaultValues:d}),y=async m=>{if(n)try{console.log("Form submitted with data:",m);const f=n.questionGroups.flatMap((h,N)=>h.questions.map((k,w)=>{var C,P,A;return{questionId:k.id,values:((A=(P=(C=m.questionResults)==null?void 0:C[N])==null?void 0:P[w])==null?void 0:A.values)||[]}}));console.log("Question results to submit:",f);const j={applicantId:t,questionnarieId:n.id,questionResults:f};console.log("Final input:",j),await l(j),e==null||e()}catch(f){console.error("Error submitting questionnaire:",f)}};return a?r.jsx(R,{children:r.jsx(D,{children:r.jsx(se,{className:"my-8"})})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading questionnaire: ",o.message]})})}):n?r.jsx("form",{onSubmit:b(y),children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.subtitle})]}),r.jsx(D,{className:"space-y-8",children:n.questionGroups.flatMap((m,f)=>m.questions.map((j,h)=>{const k=j.defaultAnswers&&j.defaultAnswers.length>0?j.showAsDropdown?j.canMultipleAnswer?"multi-select":"single-select":j.canMultipleAnswer?"checkbox":"radio":"text";return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300",children:[j.text,j.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),k==="text"&&r.jsx($.Controller,{control:x,name:`questionResults.${f}.${h}.values.0`,render:({field:w})=>{var C,P,A,S;return r.jsx(W,{value:w.value||"",onChange:w.onChange,onBlur:w.onBlur,name:w.name,placeholder:"Enter your answer...",error:(S=(A=(P=(C=g.questionResults)==null?void 0:C[f])==null?void 0:P[h])==null?void 0:A.values)==null?void 0:S.message})}}),(k==="single-select"||k==="radio")&&r.jsx($.Controller,{control:x,name:`questionResults.${f}.${h}.values.0`,render:({field:w})=>{var C,P,A,S;return r.jsx(ue,{value:w.value||"",onChange:w.onChange,onBlur:w.onBlur,name:w.name,options:j.defaultAnswers.map(F=>({value:F,label:F})),placeholder:"Select an option...",error:(S=(A=(P=(C=g.questionResults)==null?void 0:C[f])==null?void 0:P[h])==null?void 0:A.values)==null?void 0:S.message})}}),(k==="checkbox"||k==="multi-select")&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mb-2",children:"Choose one or more options"}),r.jsx($.Controller,{control:x,name:`questionResults.${f}.${h}.values`,render:({field:{value:w=[],onChange:C}})=>r.jsx("div",{className:"space-y-2",children:j.defaultAnswers.map((P,A)=>r.jsxs("label",{className:"flex items-center space-x-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Array.isArray(w)&&w.includes(P),onChange:S=>{const F=Array.isArray(w)?w:[],M=S.target.checked?[...F,P]:F.filter(q=>q!==P);C(M)},className:"h-4 w-4 text-primary-500 rounded border-gray-300 focus:ring-primary-500"}),r.jsx("span",{className:"text-sm",children:P})]},`answer-${f}-${h}-${A}`))})})]})]},j.id)}))}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{type:"submit",isLoading:i,onClick:()=>{console.log("Continue button clicked"),console.log("Form errors:",g)},children:"Continue"})]}),o&&r.jsx("div",{className:"mt-4 p-4 bg-red-50 border border-red-200 rounded",children:r.jsxs("p",{className:"text-red-600 text-sm",children:["Error: ",o.message]})})]})}):null},Ht=({applicantId:t,onComplete:e,onBack:s})=>{const{uploadDocument:n,isLoading:a,isSubmitting:i,error:o,submit:l}=Et(t),[d,u]=c.useState({}),x=async b=>{if(b.preventDefault(),!n)return;const g=await Promise.all(n.uploadDocumentFiles.map(async m=>{const f=d[m.id]||[],j=await Promise.all(f.map(async h=>({fileName:h.name,fileData:await vt(h)})));return{uploadDocumentFileId:m.id,valueList:j}})),y={applicantId:t,uploadDocumentId:n.id,uploadDocumentResults:g};await l(y),e==null||e()};return a?r.jsx(R,{children:r.jsx(D,{children:r.jsx(se,{className:"my-8"})})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading document requirements: ",o.message]})})}):n?r.jsx("form",{onSubmit:x,children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.subtitle})]}),r.jsx(D,{className:"space-y-6",children:n.uploadDocumentFiles.map(b=>r.jsx(Ft,{label:b.displayName,accept:b.allowedTypes,multiple:b.multipleFile,maxSize:b.maxEachFileSizeByte,value:d[b.id]||[],onChange:g=>{u(y=>({...y,[b.id]:g}))}},b.id))}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{type:"submit",isLoading:i,children:"Continue"})]})]})}):null},Vt=({applicantId:t,onComplete:e,onBack:s})=>{const{overview:n,isLoading:a,isSubmitting:i,error:o,passOverview:l}=It(t),d=async()=>{await l(),e==null||e()};return a?r.jsx(R,{children:r.jsx(D,{children:r.jsx(se,{className:"my-8"})})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading overview: ",o.message]})})}):n?r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:n.title||"Overview"}),n.description&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.description})]}),r.jsx(D,{className:"space-y-8",children:n.steps&&n.steps.length>0?n.steps.sort((u,x)=>u.order-x.order).map(u=>r.jsxs("div",{className:"metakyc-overview-step-item flex items-center space-x-3",children:[r.jsx("div",{className:"metakyc-step-icon flex-shrink-0",children:r.jsx("div",{className:"w-8 h-8 rounded-full bg-primary-500 text-white flex items-center justify-center font-medium text-sm",children:u.order+1})}),r.jsxs("div",{className:"metakyc-step-content",style:{flex:1,border:"none",height:"auto",background:"transparent"},children:[r.jsx("span",{className:"metakyc-step-title text-sm font-semibold text-gray-900 dark:text-white",children:u.title}),u.description&&r.jsx("p",{className:"metakyc-step-description text-sm text-gray-600 dark:text-gray-400",children:u.description})]})]},u.order)):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading overview data..."})})}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{onClick:d,isLoading:i,children:"Continue"})]})]}):null},Yt=({applicantId:t,onComplete:e,onBack:s})=>{const{criteria:n,isLoading:a,isSubmitting:i,error:o,submit:l}=Dt(t),[d,u]=c.useState(!1),x=c.useMemo(()=>!n||n.length===0?{criteriaValueInputs:[]}:{criteriaValueInputs:n.map(h=>({riskCriteriaId:h.id,values:[""]}))},[n]),b=n&&n.length>0?Ut():null,{control:g,handleSubmit:y,formState:{errors:m}}=$.useForm({resolver:b?$t(b):void 0,defaultValues:x});c.useEffect(()=>{!a&&n&&n.length===0&&!d&&!i&&(u(!0),l({applicantId:t,criteriaValueInputs:[]}).then(()=>e==null?void 0:e()).catch(console.error))},[a,n,d,i,l,t,e]);const f=async h=>{if(n)try{console.log("Risk scoring form submitted:",h),console.log("Criteria metadata:",n);const N=h.criteriaValueInputs.map((w,C)=>{const P=w.values||[],A=Array.isArray(P)?P.filter(S=>S&&S.trim()):P&&P.toString().trim()?[P.toString()]:[];return A.length===0?null:{riskCriteriaId:n[C].id,values:A}}).filter(w=>w!==null);console.log("Risk scoring criteriaValueInputs to submit:",N);const k={applicantId:t,criteriaValueInputs:N};console.log("Final risk scoring input:",k),await l(k),console.log("Risk scoring submitted successfully!"),e==null||e()}catch(N){throw console.error("Error submitting risk scoring:",N),N}},j=h=>h.builtInType===1?"country":!h.defaultValues||h.defaultValues.length===0?"text":h.multipleValue?"checkbox":"radio";return a?r.jsx(R,{children:r.jsxs(D,{children:[r.jsx(se,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading risk scoring criteria..."})]})}):o?r.jsx(R,{children:r.jsx(D,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading criteria: ",o.message]})})}):!a&&n&&n.length===0?r.jsx(R,{children:r.jsxs(D,{children:[r.jsx(se,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400",children:"No risk scoring criteria required. Moving to next step..."})]})}):n?r.jsx("form",{onSubmit:y(f),children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold",children:"Risk Assessment"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please answer the following questions for risk evaluation"})]}),r.jsx(D,{className:"space-y-8",children:n.map((h,N)=>{var w,C,P;const k=j(h);return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300",children:[h.displayName,h.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),h.description&&r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:h.description}),k==="text"&&r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values.0`,render:({field:A})=>{var S,F,M;return r.jsx(W,{...A,value:A.value||"",type:h.valueDataType===we.DigitOnly?"number":"text",placeholder:"Enter your answer...",error:(M=(F=(S=m.criteriaValueInputs)==null?void 0:S[N])==null?void 0:F.values)==null?void 0:M.message,onKeyDown:q=>{h.valueDataType===we.DigitOnly&&["e","E","+","-","."].includes(q.key)&&q.preventDefault()}})}}),k==="radio"&&h.defaultValues&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Choose one option"}),r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values.0`,render:({field:{value:A,onChange:S}})=>r.jsx("div",{className:"space-y-2",children:h.defaultValues.map((F,M)=>r.jsxs("label",{className:"flex items-center space-x-2 cursor-pointer",children:[r.jsx("input",{type:"radio",checked:A===F,onChange:()=>S(F),className:"h-4 w-4 text-primary-500 border-gray-300 focus:ring-primary-500"}),r.jsx("span",{className:"text-sm",children:F})]},`${N}-${M}`))})})]}),k==="checkbox"&&h.defaultValues&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Choose one or more options"}),r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values`,render:({field:{value:A=[],onChange:S}})=>r.jsx("div",{className:"space-y-2",children:h.defaultValues.map((F,M)=>r.jsxs("label",{className:"flex items-center space-x-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Array.isArray(A)&&A.includes(F),onChange:q=>{const K=Array.isArray(A)?A:[],p=q.target.checked?[...K,F]:K.filter(v=>v!==F);S(p)},className:"h-4 w-4 text-primary-500 rounded border-gray-300 focus:ring-primary-500"}),r.jsx("span",{className:"text-sm",children:F})]},`${N}-${M}`))})})]}),k==="country"&&r.jsx($.Controller,{control:g,name:`criteriaValueInputs.${N}.values.0`,render:({field:A})=>{var S,F,M;return r.jsx(ue,{...A,options:[{value:"US",label:"United States"},{value:"GB",label:"United Kingdom"},{value:"DE",label:"Germany"}],placeholder:"Select a country...",error:(M=(F=(S=m.criteriaValueInputs)==null?void 0:S[N])==null?void 0:F.values)==null?void 0:M.message})}}),((P=(C=(w=m.criteriaValueInputs)==null?void 0:w[N])==null?void 0:C.values)==null?void 0:P.message)&&r.jsx("p",{className:"text-sm text-danger-500 mt-1",children:m.criteriaValueInputs[N].values.message})]},h.id)})}),r.jsxs(X,{className:"flex justify-between",children:[s&&r.jsx(_,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(_,{type:"submit",isLoading:i,onClick:()=>{console.log("Risk scoring submit button clicked"),console.log("Form errors:",m)},children:"Continue"})]}),o&&r.jsx("div",{className:"mt-4 p-4 bg-red-50 border border-red-200 rounded",children:r.jsxs("p",{className:"text-red-600 text-sm",children:["Error: ",o.message]})})]})}):null},Wt=({applicantId:t,onComplete:e,onBack:s})=>{const{investorCategorizationService:n}=ee(),[a,i]=c.useState(null),[o,l]=c.useState(!1),[d,u]=c.useState(null),x=async b=>{if(b.preventDefault(),a===null){u("Please select an investor type");return}l(!0),u(null);try{const g={applicantId:t,investorType:a};console.log("Submitting investor categorization:",g);const y=await n.setInvestorCategorization(g);console.log("Investor categorization result:",y),e==null||e()}catch(g){console.error("Error submitting investor categorization:",g),u(g.message||"Failed to submit investor categorization")}finally{l(!1)}};return r.jsx("form",{onSubmit:x,children:r.jsxs(R,{children:[r.jsxs(Q,{children:[r.jsx("h2",{className:"text-lg font-bold text-gray-900 dark:text-white",children:"Which statement best describes you?"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"All Tokenise clients are treated as Retail Investors under EU regulation, which gives you the highest level of investor protection. For our internal purposes, we ask you to select the description that best matches your situation"})]}),r.jsxs(D,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-3",children:"Choose one"}),r.jsx("label",{className:`
2
2
  block p-4 border-2 rounded-lg cursor-pointer transition-all
3
3
  ${a===J.Individual?"border-primary-500 bg-primary-50 dark:bg-primary-900/20":"border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"}
4
4
  `,children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("input",{type:"radio",name:"investorType",value:J.Individual,checked:a===J.Individual,onChange:()=>i(J.Individual),className:"mt-1 h-4 w-4 text-primary-500 border-gray-300 focus:ring-primary-500"}),r.jsxs("div",{className:"ml-3",children:[r.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Individual investor"}),r.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:"(Recommended) Most of our clients choose this option. Provides the strongest protection and aligns with our mission to make investing accessible to everyone."})]})]})}),r.jsx("label",{className:`