@vpdev2/metakyc-sdk 1.0.35 → 1.0.36

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.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ht=Object.defineProperty;var qt=(e,t,s)=>t in e?Ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var U=(e,t,s)=>qt(e,typeof t!="symbol"?t+"":t,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Wt=require("axios"),o=require("react"),r=require("react/jsx-runtime"),ue=require("react-hook-form"),ce=require("zod");function Yt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const a=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,a.get?a:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const Re=Yt(o);var T=(e=>(e[e.IdentitySdk=0]="IdentitySdk",e[e.RiskScoring=1]="RiskScoring",e[e.Questionaries=2]="Questionaries",e[e.AdditionalData=3]="AdditionalData",e[e.AppropriatenessTest=4]="AppropriatenessTest",e[e.UploadDocument=5]="UploadDocument",e[e.ManualReview=6]="ManualReview",e[e.Overview=7]="Overview",e[e.InvestorCategorization=8]="InvestorCategorization",e))(T||{}),ye=(e=>(e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Success=2]="Success",e[e.PartialSuccess=3]="PartialSuccess",e[e.Failed=4]="Failed",e[e.Skipped=5]="Skipped",e[e.AdminReview=6]="AdminReview",e[e.SkippedAndAdminReview=7]="SkippedAndAdminReview",e))(ye||{}),se=(e=>(e[e.None=0]="None",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished",e[e.OnHold=3]="OnHold",e[e.IdentityPending=4]="IdentityPending",e))(se||{}),De=(e=>(e[e.None=0]="None",e[e.RepresentativeKYC=1]="RepresentativeKYC",e[e.ManualRiskCriteria=2]="ManualRiskCriteria",e[e.UploadDocumentReview=3]="UploadDocumentReview",e[e.AdminReview=4]="AdminReview",e))(De||{}),Fe=(e=>(e[e.LowRisk=0]="LowRisk",e[e.MediumRisk=1]="MediumRisk",e[e.HighRisk=2]="HighRisk",e[e.Alert=3]="Alert",e))(Fe||{}),me=(e=>(e[e.None=0]="None",e[e.Pending=1]="Pending",e[e.Approved=2]="Approved",e[e.Rejected=3]="Rejected",e[e.ResendRequested=4]="ResendRequested",e[e.Unknown=5]="Unknown",e[e.InProgress=6]="InProgress",e))(me||{}),pe=(e=>(e[e.Approved=0]="Approved",e[e.Reject=1]="Reject",e[e.UnderReview=2]="UnderReview",e[e.Closed=3]="Closed",e[e.AdminReview=4]="AdminReview",e[e.New=5]="New",e[e.InProgress=6]="InProgress",e))(pe||{}),Pe=(e=>(e[e.ProviderResultPending=0]="ProviderResultPending",e[e.ProviderResultReceived=1]="ProviderResultReceived",e[e.Canceled=2]="Canceled",e[e.ExtendedToNewApplicant=3]="ExtendedToNewApplicant",e))(Pe||{}),Le=(e=>(e[e.None=0]="None",e[e.ProviderResultPending=1]="ProviderResultPending",e[e.ProviderResultReceived=2]="ProviderResultReceived",e[e.Canceled=3]="Canceled",e))(Le||{}),re=(e=>(e[e.Onfido=0]="Onfido",e[e.Sumsub=2]="Sumsub",e[e.SardinAI=3]="SardinAI",e))(re||{}),Te=(e=>(e[e.Individual=0]="Individual",e[e.Company=1]="Company",e))(Te||{}),be=(e=>(e[e.Male=0]="Male",e[e.Female=1]="Female",e[e.Other=2]="Other",e))(be||{}),Me=(e=>(e[e.Image=0]="Image",e[e.Video=1]="Video",e[e.PDF=2]="PDF",e[e.OfficePDF=3]="OfficePDF",e[e.Custom=4]="Custom",e))(Me||{}),Oe=(e=>(e[e.Pending=0]="Pending",e[e.Approved=1]="Approved",e[e.Rejected=2]="Rejected",e[e.RequiresRevision=3]="RequiresRevision",e))(Oe||{}),ze=(e=>(e[e.SingleChoice=0]="SingleChoice",e[e.MultipleChoice=1]="MultipleChoice",e[e.Text=2]="Text",e))(ze||{}),oe=(e=>(e[e.String=0]="String",e[e.Integer=1]="Integer",e[e.Decimal=2]="Decimal",e[e.Boolean=3]="Boolean",e[e.Date=4]="Date",e[e.Country=5]="Country",e[e.DigitOnly=6]="DigitOnly",e))(oe||{}),Be=(e=>(e[e.Text=0]="Text",e[e.Radio=1]="Radio",e[e.Checkbox=2]="Checkbox",e[e.Dropdown=3]="Dropdown",e[e.Country=4]="Country",e))(Be||{}),Ke=(e=>(e[e.None=0]="None",e[e.Country=1]="Country",e))(Ke||{}),J=(e=>(e[e.Individual=0]="Individual",e[e.Sophisticated=1]="Sophisticated",e[e.HighNetWorth=2]="HighNetWorth",e[e.Business=3]="Business",e))(J||{}),Ue=(e=>(e[e.Retail=0]="Retail",e[e.Professional=1]="Professional",e[e.EligibleCounterparty=2]="EligibleCounterparty",e))(Ue||{});const ke=[{value:"EN",label:"English"},{value:"DE",label:"German"},{value:"FR",label:"French"},{value:"ES",label:"Spanish"},{value:"IT",label:"Italian"},{value:"PT",label:"Portuguese"},{value:"NL",label:"Dutch"},{value:"PL",label:"Polish"},{value:"RU",label:"Russian"},{value:"ZH",label:"Chinese"},{value:"JA",label:"Japanese"},{value:"AR",label:"Arabic"},{value:"TR",label:"Turkish"},{value:"SV",label:"Swedish"},{value:"DA",label:"Danish"},{value:"FI",label:"Finnish"},{value:"NO",label:"Norwegian"}],_e=["firstName","lastName","email","phonenumber","dateOfBirth","street","streetNumber","zip","city","country","nationality","taxCountry","taxNumber"],Qt=["firstName","lastName","title","email","dateOfBirth","phonenumber","mobileCountryCode","street","streetNumber","zip","city","country","nationality","otherNationality","defaultLanguage","taxCountry","placeOfBirth","countryOfBirth","salutation","educationLevel","occupation","taxNumber","externalRefId"],Se={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:"select"},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 W=(e=>(e.Default="default",e.Corporate="corporate",e.Fintech="fintech",e.Healthcare="healthcare",e.Modern="modern",e.Minimal="minimal",e))(W||{});const $e={timeout:3e4,retries:3,locale:"en",endpoints:{pattern:"host-controller"}};class He{constructor(t){this.config=t}build(t,s){const a=`${t}.${s}`;if(this.config.customPaths&&this.config.customPaths[a])return this.config.customPaths[a];switch(this.config.pattern){case"host-controller":return`/api/${t}/${s}`;case"application-service":return`/services/app/${this.getServiceName(t)}/${s}`;case"custom":throw new Error(`Custom endpoint path not found for ${a}. Please provide it in customPaths.`);default:throw new Error(`Unknown endpoint pattern: ${this.config.pattern}`)}}getServiceName(t){return{Applicant:"MetaKYCVerification",Questionnaire:"MetaKYCVerification",UploadDocument:"MetaKYCVerification",AppropriatenessTest:"MetaKYCVerification",BaseInformation:"MetaKYCVerification"}[t]||t}}class ne extends Error{constructor(s,a,n,i,l){super(s);U(this,"response");this.code=a,this.details=n,this.validationErrors=i,this.name="MetaKYCError",this.response=l,Object.setPrototypeOf(this,ne.prototype)}}class ge{static handleApiError(t){return new ne(t.message||"An unknown error occurred",t.code,t.details||void 0,t.validationErrors||void 0)}static handleAxiosError(t){if(t.response){const s=t.response.data;return s&&s.error?new ne(s.error.message||"An unknown error occurred",s.error.code,s.error.details||void 0,s.error.validationErrors||void 0,t.response):s&&s.result&&s.result.message?new ne(s.result.message,t.response.status,`HTTP ${t.response.status}: ${t.response.statusText}`,void 0,t.response):new ne((s==null?void 0:s.message)||t.message||"Request failed",t.response.status,`HTTP ${t.response.status}: ${t.response.statusText}`,void 0,t.response)}else return t.request?new ne("No response from server",0,"The request was made but no response was received. Please check your network connection."):new ne(t.message||"An unexpected error occurred",0,t.toString())}static isMetaKYCError(t){return t instanceof ne}}class qe{constructor(t){U(this,"axiosInstance");U(this,"endpointBuilder");U(this,"config");this.config={...$e,...t},this.endpointBuilder=new He(this.config.endpoints),this.axiosInstance=Wt.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 n;const a=s.config;return((n=s.response)==null?void 0:n.status)>=500&&!a._retry&&(a._retry=!0,a._retryCount=(a._retryCount||0)+1,a._retryCount<(this.config.retries||3))?(await new Promise(i=>setTimeout(i,1e3*a._retryCount)),this.axiosInstance(a)):Promise.reject(s)})}buildEndpoint(t,s){return this.endpointBuilder.build(t,s)}async get(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.get(n,{params:a});return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}async post(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.post(n,a);return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}async put(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.put(n,a);return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}async delete(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.delete(n,{params:a});return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}handleResponse(t){const s=t.data;if(!s.success&&s.error)throw ge.handleApiError(s.error);return s}getAxiosInstance(){return this.axiosInstance}}class We{constructor(t){this.httpClient=t}async createApplicant(t){return(await this.httpClient.post("Applicant","ApplicantRegistrationRequest",t)).result}async createCompanyApplicant(t){return(await this.httpClient.post("Applicant","ApplicantCompanyRegistrationRequest",t)).result}async duplicateApplicant(t){return(await this.httpClient.post("Applicant","DuplicateApplicantRegistrationRequest",t)).result}async getProgress(t){return(await this.httpClient.get("Applicant","GetApplicantProgress",{applicantId:t})).result}async getProgressStatus(t){return(await this.httpClient.get("Applicant","GetApplicantProgressStaus",{applicantId:t})).result}async getApplicantData(t){return(await this.httpClient.get("Applicant","GetApplicantData",{applicantId:t})).result}async getApplicantStatus(t){return(await this.httpClient.get("Applicant","GetApplicantStatus",{applicantId:t})).result}async stopProgress(t){await this.httpClient.get("Applicant","StopProgress",{applicantId:t})}async progressStepBack(t){await this.httpClient.get("Applicant","ProgressStepBack",{applicantId:t})}async setLanguage(t,s){await this.httpClient.post("Applicant","SetApplicantLng",{applicantId:t,language:s})}async activateApplicant(t){await this.httpClient.get("Applicant","ActivateApplicant",{applicantId:t})}async deleteApplicant(t){await this.httpClient.delete("Applicant","DeleteApplicant",{applicantId:t})}async checkApplicantExists(t){return(await this.httpClient.get("Applicant","CheckApplicantIfExists",{externalRefId:t})).result}}class Ye{constructor(t){this.httpClient=t}async getQuestionnaire(t){return(await this.httpClient.get("Questionnaire","GetQuestionnaire",{applicantid:t})).result}async fillQuestionnaire(t){return(await this.httpClient.post("Applicant","FillQuestionnarie",t)).result}}class Qe{constructor(t){this.httpClient=t}async getUploadDocument(t){return(await this.httpClient.get("UploadDocument","GetUploadDocument",{applicantid:t})).result}async fillUploadDocument(t){await this.httpClient.post("Applicant","FillUploadDocument",t)}async reviewUploadDocument(t){await this.httpClient.post("UploadDocument","ReviewUploadDocument",t)}}class Ve{constructor(t){this.httpClient=t}async getAppropriatenessTest(t){return(await this.httpClient.get("AppropriatenessTest","GetAppropriatenessTest",{applicantid:t})).result}async fillAppropriatenessTest(t){return(await this.httpClient.post("Applicant","FillAppropriatenessTest",t)).result}}class Ge{constructor(t){this.httpClient=t}async getOverviewData(t){return(await this.httpClient.get("Applicant","GetOverviewData",{ApplicantId:t})).result}async passOverview(t){await this.httpClient.get("Applicant","PassOverview",{applicantId:t})}}class Ze{constructor(t){this.httpClient=t}async getRiskScoringPlan(){return(await this.httpClient.get("Applicant","GetRiskScoringPlanInfo")).result}async getRiskCriterias(t){return(await this.httpClient.get("Risk","GetCriterias",{applicantId:t})).result}async submitRiskScoring(t){return(await this.httpClient.post("Applicant","RiskScoringRequest",t)).result}}class Je{constructor(t){this.httpClient=t}async identityRequest(t){console.log("[IdentityService] Calling IdentityRequest with input:",t);const s=await this.httpClient.post("Applicant","IdentityRequest",t);return console.log("[IdentityService] IdentityRequest response:",s),s.result}async identityCompanyRequest(t){return(await this.httpClient.post("Applicant","IdentityCompanyRequest",t)).result}async restartIdentityRequest(t){const s={applicantId:t,restart:!0,redirectUrl:"",ttl:604800};return console.log("[IdentityService] Restarting identity with restart=true:",s),this.identityRequest(s)}async restartIdentityCompanyRequest(t){const s={applicantId:t,restart:!0,redirectUrl:"",ttl:604800};return this.identityCompanyRequest(s)}}class Xe{constructor(t){this.httpClient=t}async getCountries(t,s,a){return(await this.httpClient.get("BaseInformation","GetAllCountries",{filter:t||"",lng:s||"en",type:a})).result}async getBranches(){return(await this.httpClient.get("BaseInformation","GetBranches")).result}async getLegalEntities(){return(await this.httpClient.get("BaseInformation","GetLegalEntities")).result}}class et{constructor(t){this.httpClient=t}async setInvestorCategorization(t){return(await this.httpClient.post("Applicant","SetInvestorCategorization",t)).result}async getInvestorCategorization(t){return(await this.httpClient.get("Applicant","GetInvestorCategorisation",{applicantId:t})).result}}const V={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"}}},tt={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"}},rt={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"}},st={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"}}},at={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"}},nt={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"}},it={[W.Default]:V,[W.Corporate]:tt,[W.Fintech]:rt,[W.Healthcare]:st,[W.Modern]:at,[W.Minimal]:nt};function xe(e){return it[e]||V}class ot{constructor(t){this.httpClient=t}async getThemeConfiguration(){var t;try{const s=await this.httpClient.get("Tenant","GetThemeConfiguration");if(!s.result.isEnabled)return xe(W.Default);let a=s.result.preset?xe(s.result.preset):xe(W.Default);return s.result.title&&(a.title=s.result.title),s.result.logo&&(a.logo={...a.logo,...s.result.logo}),s.result.colors&&(a.colors={...a.colors,...s.result.colors}),s.result.typography&&(a.typography={...a.typography,...s.result.typography}),s.result.spacing&&(a.spacing={...a.spacing,...s.result.spacing}),s.result.customCSS&&(a.customCSS=s.result.customCSS),s.result.darkMode&&(a.darkMode={colors:{...(t=a.darkMode)==null?void 0:t.colors,...s.result.darkMode.colors}}),s.result.applicantFormVisibleFields&&s.result.applicantFormVisibleFields.length>0&&(a.applicantFormVisibleFields=s.result.applicantFormVisibleFields),s.result.applicantFormRequiredFields&&s.result.applicantFormRequiredFields.length>0&&(a.applicantFormRequiredFields=s.result.applicantFormRequiredFields),s.result.allowedLanguages&&s.result.allowedLanguages.length>0&&(a.allowedLanguages=s.result.allowedLanguages),a}catch(s){return console.warn("[ThemeService] Failed to fetch theme configuration:",s),xe(W.Default)}}async saveThemeConfiguration(t){await this.httpClient.post("Tenant","SaveThemeConfiguration",t)}getAvailablePresets(){return[{id:W.Default,name:"Default"},{id:W.Corporate,name:"Corporate"},{id:W.Fintech,name:"Fintech"},{id:W.Healthcare,name:"Healthcare"},{id:W.Modern,name:"Modern"},{id:W.Minimal,name:"Minimal"}]}getPreviewTheme(t,s){const a=xe(t);return s?{...a,...s,logo:{...a.logo,...s.logo},colors:{...a.colors,...s.colors},typography:s.typography?{...a.typography,...s.typography}:a.typography,spacing:s.spacing?{...a.spacing,...s.spacing}:a.spacing}:a}}class lt{constructor(){U(this,"listeners",new Map)}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{this.off(t,s)}}off(t,s){const a=this.listeners.get(t);a&&a.delete(s)}emit(t,s){const a=this.listeners.get(t);a&&a.forEach(n=>{try{n(s)}catch(i){console.error(`Error in event listener for "${t}":`,i)}})}clear(){this.listeners.clear()}clearEvent(t){this.listeners.delete(t)}}class ct{constructor(){U(this,"events",new lt);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 t;return((t=this._progress)==null?void 0:t.currentStep)||null}get steps(){var t;return((t=this._progress)==null?void 0:t.stepInfoList)||[]}get status(){var t;return((t=this._progress)==null?void 0:t.status)||se.None}get workflowResult(){var t;return((t=this._progress)==null?void 0:t.workflowResult)||null}get error(){return this._error}get isComplete(){return this.status===se.Finished}get isOnHold(){return this.status===se.OnHold}get isInProgress(){return this.status===se.InProgress}setApplicantId(t){this._applicantId=t}updateProgress(t){var a,n;const s=(a=this._progress)==null?void 0:a.currentStep;this._progress=t,this._applicantId=t.applicantId,this._error=null,this.events.emit("progressUpdated",t),(s==null?void 0:s.order)!==((n=t.currentStep)==null?void 0:n.order)&&this.events.emit("stepChanged",t.currentStep),this.events.emit("statusChanged",t.status),t.status===se.Finished&&t.workflowResult&&this.events.emit("completed",t.workflowResult)}setError(t){this._error=t,this.events.emit("error",t)}clearError(){this._error=null}reset(){this._applicantId=null,this._progress=null,this._error=null}onProgressUpdated(t){return this.events.on("progressUpdated",t)}onStepChanged(t){return this.events.on("stepChanged",t)}onStatusChanged(t){return this.events.on("statusChanged",t)}onError(t){return this.events.on("error",t)}onCompleted(t){return this.events.on("completed",t)}clearListeners(){this.events.clear()}}class dt{constructor(){U(this,"handlers",new Map)}registerHandler(t,s){this.handlers.set(t,s)}getHandler(t){return this.handlers.get(t)}hasHandler(t){return this.handlers.has(t)}async loadStepData(t,s){const a=this.getHandler(t);if(!a)throw new Error(`No handler registered for step action: ${T[t]}`);return a.loadData(s)}async submitStepData(t,s){const a=this.getHandler(t);if(!a)throw new Error(`No handler registered for step action: ${T[t]}`);return a.submitData(s)}}class ut{constructor(t,s,a,n,i,l,c,d){U(this,"state");U(this,"stepRouter");this.applicantService=t,this.questionnaireService=s,this.uploadDocumentService=a,this.appropriatenessTestService=n,this.overviewService=i,this.riskScoringService=l,this.investorCategorizationService=d,this.state=new ct,this.stepRouter=new dt,this.registerStepHandlers()}registerStepHandlers(){this.stepRouter.registerHandler(T.Questionaries,{loadData:t=>this.questionnaireService.getQuestionnaire(t),submitData:async t=>{await this.questionnaireService.fillQuestionnaire(t)}}),this.stepRouter.registerHandler(T.UploadDocument,{loadData:t=>this.uploadDocumentService.getUploadDocument(t),submitData:t=>this.uploadDocumentService.fillUploadDocument(t)}),this.stepRouter.registerHandler(T.AppropriatenessTest,{loadData:t=>this.appropriatenessTestService.getAppropriatenessTest(t),submitData:async t=>{await this.appropriatenessTestService.fillAppropriatenessTest(t)}}),this.stepRouter.registerHandler(T.Overview,{loadData:t=>this.overviewService.getOverviewData(t),submitData:t=>this.overviewService.passOverview(t.applicantId)}),this.stepRouter.registerHandler(T.RiskScoring,{loadData:t=>this.riskScoringService.getRiskCriterias(t),submitData:async t=>{await this.riskScoringService.submitRiskScoring(t)}}),this.stepRouter.registerHandler(T.IdentitySdk,{loadData:async t=>({applicantId:t,message:"Identity verification required"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.InvestorCategorization,{loadData:t=>this.investorCategorizationService.getInvestorCategorization(t),submitData:async t=>{await this.investorCategorizationService.setInvestorCategorization(t)}}),this.stepRouter.registerHandler(T.ManualReview,{loadData:async t=>({applicantId:t,message:"Your application is under manual review"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.AdditionalData,{loadData:async t=>({applicantId:t,message:"Additional data required"}),submitData:async()=>{}})}async initialize(t){try{this.state.setApplicantId(t);const s=await this.applicantService.getProgress(t);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 t=await this.applicantService.getProgress(this.state.applicantId);return this.state.updateProgress(t),t}catch(t){throw this.state.setError(t),t}}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(t){throw this.state.setError(t),t}}async submitCurrentStep(t){if(!this.state.currentStep)throw new Error("No current step available");try{await this.stepRouter.submitStepData(this.state.currentStep.action,t),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(t){throw this.state.setError(t),t}}getState(){return this.state}getStepRouter(){return this.stepRouter}}function Ce(e,t){return new Promise((s,a)=>{if(t&&document.getElementById(t)){s();return}const n=document.createElement("script");n.src=e,t&&(n.id=t),n.async=!0,n.onload=()=>s(),n.onerror=()=>a(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}function Vt(e){return!!document.getElementById(e)}function Gt(e){const t=document.getElementById(e);t&&t.remove()}class mt{constructor(t){U(this,"sdk",null);U(this,"config");this.config=t}async loadSDK(){await Ce("https://cdn.sumsub.com/websdk/v2/production/websdk.js","sumsub-sdk")}async initialize(t){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(`#${t}`)}destroy(){this.sdk&&(this.sdk.destroy(),this.sdk=null)}onComplete(t){this.sdk&&this.sdk.on("idCheck.applicantStatus",s=>{s.applicantStatus==="completed"&&t(s)})}onError(t){this.sdk&&this.sdk.on("idCheck.onError",t)}}class pt{constructor(t){U(this,"sdk",null);U(this,"config");this.config=t}async loadSDK(){await Ce("https://sdk.onfido.com/v12.0.0/onfido.min.js","onfido-sdk")}async initialize(t){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:t,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 ht{constructor(t){U(this,"sardineContext",null);U(this,"config");U(this,"sessionKey");this.config=t,this.sessionKey=t.sessionKey||this.generateSessionKey()}generateSessionKey(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const s=Math.random()*16|0;return(t==="x"?s:s&3|8).toString(16)})}getSardineHost(){const{environment:t,region:s}=this.config;if(t==="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((t,s)=>{if(window._Sardine){t();return}const a=this.getSardineHost(),n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=`https://${a}/assets/loader.min.js`,n.onload=()=>{console.log("[SardinAI] SDK loaded successfully"),t()},n.onerror=()=>{s(new Error("Failed to load SardinAI SDK"))};const i=document.getElementsByTagName("script")[0];i&&i.parentNode?i.parentNode.insertBefore(n,i):document.head.appendChild(n)})}async initialize(){try{if(await this.loadSDK(),!window._Sardine)throw new Error("SardinAI SDK not available after loading");const t=this.getSardineHost(),{clientId:s,environment:a,flow:n,enableBiometrics:i,enablePortScanning:l}=this.config;this.sardineContext=window._Sardine.createContext({clientId:s,sessionKey:this.sessionKey,userIdHash:void 0,flow:n||window.location.pathname,environment:a||"production",parentElement:document.body,enableBiometrics:i!==!1,enablePortScanning:l===!0,region:this.config.region,onDeviceResponse:c=>{console.log(`[SardinAI] Device ID: ${c.deviceId}`)},onConfigUpdate:(c,d,u)=>{switch(c){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:",c)}}}),this.addNoScriptFallback(t),console.log("[SardinAI] SDK initialized with sessionKey:",this.sessionKey)}catch(t){throw console.error("[SardinAI] Initialization failed:",t),t}}addNoScriptFallback(t){const s=document.createElement("noscript"),a=document.createElement("img"),{clientId:n,flow:i}=this.config;a.src=`https://${t}/v1/a.png?clientId=${n}&sessionKey=${this.sessionKey}&flow=${i||"kyc"}&ns=1`,a.style.display="none",s.appendChild(a),document.body.appendChild(s)}updateConfig(t){if(!this.sardineContext){console.warn("[SardinAI] Cannot update config - SDK not initialized");return}t.sessionKey&&(this.sessionKey=t.sessionKey),this.sardineContext.updateConfig({...t,onConfigUpdate:(s,a,n)=>{switch(s){case"SESSION_UPDATE_FAILED":console.error("[SardinAI] Config update failed:",n);break;case"SESSION_UPDATED":console.log("[SardinAI] Config updated:",a);break;case"SESSION_NO_UPDATE":console.log("[SardinAI] No config update needed");break}}})}getSessionKey(){return this.sessionKey}destroy(){this.sardineContext&&(this.sardineContext=null)}}class he{static createProvider(t,s){switch(t){case re.Sumsub:return new mt(s);case re.Onfido:return new pt(s);case re.SardinAI:return new ht(s);default:throw new Error(`Unsupported identity provider: ${t}`)}}static parseProviderConfig(t,s,a){var n;switch(t){case re.Sumsub:return{accessToken:s.accessToken||s.token,applicantEmail:s.email,applicantPhone:s.phone,externalUserId:s.externalUserId,lang:s.lang||"en"};case re.Onfido:return{token:s.token||s.sdkToken};case re.SardinAI:const i=((n=a==null?void 0:a.identityProviders)==null?void 0:n.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: ${t}`)}}}class gt{constructor(t){U(this,"currentTheme",V);U(this,"customStyleElement",null);U(this,"container");this.container=t||document.documentElement}applyTheme(t){this.currentTheme=this.mergeWithDefault(t),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(t){var a;const s={primary:t.primary,"primary-hover":t.primaryHover,"primary-light":t.primaryLight,"primary-dark":t.primaryDark,secondary:t.secondary,"secondary-hover":t.secondaryHover,success:t.success,warning:t.warning,danger:t.danger,info:t.info,background:t.background,surface:t.surface,border:t.border,"text-primary":t.textPrimary,"text-secondary":t.textSecondary,"text-muted":t.textMuted};Object.entries(s).forEach(([n,i])=>{this.container.style.setProperty(`--metakyc-${n}`,i)}),(a=this.currentTheme.darkMode)!=null&&a.colors&&this.applyDarkModeColors(this.currentTheme.darkMode.colors)}applyDarkModeColors(t){Object.entries(t).forEach(([s,a])=>{if(a){const n=`--metakyc-dark-${this.kebabCase(s)}`;this.container.style.setProperty(n,a)}})}applyTypography(t){t&&(t.fontFamily&&this.container.style.setProperty("--metakyc-font-family",t.fontFamily),t.headingFont&&this.container.style.setProperty("--metakyc-heading-font",t.headingFont),t.fontSize&&Object.entries(t.fontSize).forEach(([s,a])=>{this.container.style.setProperty(`--metakyc-font-size-${s}`,a)}),t.fontWeight&&Object.entries(t.fontWeight).forEach(([s,a])=>{this.container.style.setProperty(`--metakyc-font-weight-${s}`,a.toString())}))}applySpacing(t){t&&Object.entries(t).forEach(([s,a])=>{const n=`--metakyc-${this.kebabCase(s)}`;this.container.style.setProperty(n,a)})}injectCustomCSS(t){this.customStyleElement&&this.customStyleElement.remove(),this.customStyleElement=document.createElement("style"),this.customStyleElement.id="metakyc-custom-css",this.customStyleElement.textContent=t,document.head.appendChild(this.customStyleElement)}mergeWithDefault(t){var s;return{name:t.name||V.name,title:t.title||V.title,logo:{...V.logo,...t.logo},colors:{...V.colors,...t.colors},typography:t.typography?{...V.typography,...t.typography}:V.typography,spacing:t.spacing?{...V.spacing,...t.spacing}:V.spacing,customCSS:t.customCSS,darkMode:t.darkMode?{colors:{...(s=V.darkMode)==null?void 0:s.colors,...t.darkMode.colors}}:V.darkMode,applicantFormVisibleFields:t.applicantFormVisibleFields,applicantFormRequiredFields:t.applicantFormRequiredFields,allowedLanguages:t.allowedLanguages}}getCurrentTheme(){return this.currentTheme}resetTheme(){this.applyTheme(V)}cleanup(){this.customStyleElement&&(this.customStyleElement.remove(),this.customStyleElement=null)}kebabCase(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}}const Ae=o.createContext(null),Zt=({config:e,children:t})=>{const[s,a]=o.useState(null),n=o.useRef(!1),i=o.useRef(!1),l=o.useMemo(()=>{const d=new qe(e),u=new We(d),w=new Ye(d),v=new Qe(d),p=new Ve(d),y=new Ge(d),m=new Ze(d),j=new Je(d),h=new Xe(d),b=new et(d),A=new ot(d),k=new gt;return{httpClient:d,applicantService:u,questionnaireService:w,uploadDocumentService:v,appropriatenessTestService:p,overviewService:y,riskScoringService:m,identityService:j,baseInformationService:h,investorCategorizationService:b,themeService:A,themeManager:k}},[e]),c=o.useMemo(()=>({config:e,...l,currentTheme:s,createOrchestrator:()=>new ut(l.applicantService,l.questionnaireService,l.uploadDocumentService,l.appropriatenessTestService,l.overviewService,l.riskScoringService,l.identityService,l.investorCategorizationService)}),[e,l,s]);return o.useEffect(()=>((async()=>{if(n.current||i.current){console.log("[MetaKYC] Theme already loading or loaded, skipping...");return}n.current=!0;try{if(e.theme){console.log("[MetaKYC] Applying static theme from config"),l.themeManager.applyTheme(e.theme),a(l.themeManager.getCurrentTheme()),i.current=!0;return}console.log("[MetaKYC] Fetching theme from backend...");const u=await l.themeService.getThemeConfiguration();l.themeManager.applyTheme(u),a(l.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),a(l.themeManager.getCurrentTheme()),i.current=!0}finally{n.current=!1}})(),()=>{l.themeManager.cleanup()}),[]),r.jsx(Ae.Provider,{value:c,children:t})};function te(){const e=o.useContext(Ae);if(!e)throw new Error("useMetaKYC must be used within a MetaKYCProvider");return e}async function xt(e){return new Promise((t,s)=>{const a=new FileReader;a.readAsDataURL(e),a.onload=()=>{const i=a.result.split(",")[1];t(i)},a.onerror=n=>s(n)})}function Jt(e,t){return e.size<=t}function Xt(e,t){return t.split(",").map(a=>a.trim()).some(a=>{if(a.endsWith("/*")){const n=a.slice(0,-2);return e.type.startsWith(n)}return e.type===a})}function ve(e){if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/Math.pow(t,a)*100)/100+" "+s[a]}function er(e){return e}function Y(...e){return e.filter(Boolean).join(" ")}const fe={APPLICANT_ID:"metakyc_applicant_id",WORKFLOW_STATE:"metakyc_workflow_state"};function ft(e){try{localStorage.setItem(fe.APPLICANT_ID,e.toString())}catch(t){console.warn("Failed to save applicant ID to storage:",t)}}function yt(){try{const e=localStorage.getItem(fe.APPLICANT_ID);return e?parseInt(e,10):null}catch(e){return console.warn("Failed to retrieve applicant ID from storage:",e),null}}function bt(){try{localStorage.removeItem(fe.APPLICANT_ID)}catch(e){console.warn("Failed to clear applicant ID from storage:",e)}}function vt(e){try{localStorage.setItem(fe.WORKFLOW_STATE,JSON.stringify(e))}catch(t){console.warn("Failed to save workflow state to storage:",t)}}function tr(){try{const e=localStorage.getItem(fe.WORKFLOW_STATE);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to retrieve workflow state from storage:",e),null}}function wt(){try{localStorage.removeItem(fe.WORKFLOW_STATE)}catch(e){console.warn("Failed to clear workflow state from storage:",e)}}function rr(){bt(),wt()}function jt(e){const{createOrchestrator:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(null),d=o.useRef(null),u=e||yt();o.useEffect(()=>{d.current||(d.current=t())},[t]),o.useEffect(()=>{var k;s&&u&&(ft(u),vt({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 w=o.useRef(!1),v=o.useRef(!1),p=o.useCallback(async()=>{if(!(!u||!d.current)){if(w.current){console.log("[Workflow] Load already in progress, skipping...");return}w.current=!0,i(!0),c(null);try{const k=await d.current.initialize(u);a(k),v.current=!0}catch(k){c(k)}finally{i(!1),w.current=!1}}},[u]);o.useEffect(()=>{u&&!v.current&&p()},[u,p]);const y=o.useCallback(async()=>{if(d.current){if(w.current){console.log("[Workflow] Refresh already in progress, skipping...");return}w.current=!0,i(!0),c(null);try{const k=await d.current.refreshProgress();a(k)}catch(k){c(k)}finally{i(!1),w.current=!1}}},[]),m=o.useCallback(async()=>{if(d.current){i(!0),c(null);try{const k=await d.current.moveToNextStep();a(k)}catch(k){c(k)}finally{i(!1)}}},[]),j=o.useCallback(async()=>{if(d.current){i(!0),c(null);try{const k=await d.current.moveToPreviousStep();a(k)}catch(k){c(k)}finally{i(!1)}}},[]),h=o.useCallback(async k=>{if(d.current){i(!0),c(null);try{await d.current.submitCurrentStep(k);const C=await d.current.refreshProgress();a(C)}catch(C){throw c(C),C}finally{i(!1)}}},[]),b=Re.useMemo(()=>s!=null&&s.stepInfoList?[...s.stepInfoList].sort((k,C)=>k.order-C.order):[],[s==null?void 0:s.stepInfoList]),A=Re.useMemo(()=>s?s.nextWorkflowKey&&s.nextWorkflowKey!==s.workFlowKey:!1,[s]);return{progress:s,applicantId:u,currentStep:(s==null?void 0:s.currentStep)||null,steps:b,status:(s==null?void 0:s.status)||se.None,workflowResult:(s==null?void 0:s.workflowResult)||null,workflowKey:s==null?void 0:s.workFlowKey,nextWorkflowKey:s==null?void 0:s.nextWorkflowKey,hasWorkflowChanged:A,isLoading:n,error:l,isComplete:(s==null?void 0:s.status)===se.Finished,isOnHold:(s==null?void 0:s.status)===se.OnHold,refreshProgress:y,moveToNext:m,moveBack:j,submitCurrentStep:h,orchestrator:d.current}}function kt(e){const{questionnaireService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),w=o.useRef(!1),v=o.useRef(null),p=o.useCallback(async()=>{if(e){if(w.current){console.log("[Questionnaire] Load already in progress, skipping...");return}w.current=!0,i(!0),u(null);try{const m=await t.getQuestionnaire(e);a(m),v.current=e}catch(m){u(m)}finally{i(!1),w.current=!1}}},[e,t]);o.useEffect(()=>{e&&v.current!==e&&p()},[e]);const y=o.useCallback(async m=>{c(!0),u(null);try{return await t.fillQuestionnaire(m)}catch(j){throw u(j),j}finally{c(!1)}},[t]);return{questionnaire:s,isLoading:n,isSubmitting:l,error:d,load:p,submit:y}}function St(e){const{uploadDocumentService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(0),[w,v]=o.useState(null),p=o.useRef(!1),y=o.useRef(null),m=o.useCallback(async()=>{if(e){if(p.current){console.log("[UploadDocument] Load already in progress, skipping...");return}p.current=!0,i(!0),v(null);try{const h=await t.getUploadDocument(e);a(h),y.current=e}catch(h){v(h)}finally{i(!1),p.current=!1}}},[e,t]);o.useEffect(()=>{e&&y.current!==e&&m()},[e]);const j=o.useCallback(async h=>{c(!0),u(0),v(null);try{await t.fillUploadDocument(h),u(100)}catch(b){throw v(b),b}finally{c(!1)}},[t]);return{uploadDocument:s,isLoading:n,isSubmitting:l,uploadProgress:d,error:w,load:m,submit:j}}function sr(e){const{appropriatenessTestService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),[w,v]=o.useState(null),p=o.useRef(!1),y=o.useRef(null),m=o.useCallback(async()=>{if(e){if(p.current){console.log("[AppropriatenessTest] Load already in progress, skipping...");return}p.current=!0,i(!0),u(null);try{const h=await t.getAppropriatenessTest(e);a(h),y.current=e}catch(h){u(h)}finally{i(!1),p.current=!1}}},[e,t]);o.useEffect(()=>{e&&y.current!==e&&m()},[e]);const j=o.useCallback(async h=>{c(!0),u(null);try{const b=await t.fillAppropriatenessTest(h);return v(b),b}catch(b){throw u(b),b}finally{c(!1)}},[t]);return{test:s,result:w,isLoading:n,isSubmitting:l,error:d,load:m,submit:j}}function Nt(e){const{overviewService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),w=o.useRef(!1),v=o.useRef(null),p=o.useCallback(async()=>{if(e){if(w.current){console.log("[Overview] Load already in progress, skipping...");return}w.current=!0,i(!0),u(null);try{const m=await t.getOverviewData(e);a(m),v.current=e}catch(m){u(m)}finally{i(!1),w.current=!1}}},[e,t]);o.useEffect(()=>{e&&v.current!==e&&p()},[e]);const y=o.useCallback(async()=>{if(e){c(!0),u(null);try{await t.passOverview(e)}catch(m){throw u(m),m}finally{c(!1)}}},[e,t]);return{overview:s,isLoading:n,isSubmitting:l,error:d,load:p,passOverview:y}}function Ct(e){const{identityService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(null),d=o.useRef(!1),u=o.useCallback(async(p,y)=>{if(e){if(d.current){console.log("[Identity] Request already in progress, skipping...");return}d.current=!0,i(!0),c(null);try{const m={applicantId:e,restart:!1,redirectUrl:p||"",ttl:y||604800};console.log("Identity request input:",m);const j=await t.identityRequest(m);return console.log("Identity request result:",j),a(j),j}catch(m){throw c(m),m}finally{i(!1),d.current=!1}}},[e,t]),w=o.useCallback(async(p,y)=>{if(e){i(!0),c(null);try{const m={applicantId:e,restart:!1,redirectUrl:p,ttl:y},j=await t.identityCompanyRequest(m);return a(j),j}catch(m){throw c(m),m}finally{i(!1)}}},[e,t]),v=o.useCallback(async()=>{if(e){if(d.current){console.log("[Identity] Restart already in progress, skipping...");return}d.current=!0,i(!0),c(null);try{const p={applicantId:e,restart:!0,redirectUrl:"",ttl:604800};console.log("Restarting identity with input:",p);const y=await t.identityRequest(p);return console.log("Restart identity result:",y),a(y),y}catch(p){throw c(p),p}finally{i(!1),d.current=!1}}},[e,t]);return{identityData:s,provider:(s==null?void 0:s.provider)||null,token:(s==null?void 0:s.publicProviderTokenObject)||null,isLoading:n,error:l,requestIdentity:u,requestCompanyIdentity:w,restartIdentity:v}}function At(e){const{riskScoringService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),[w,v]=o.useState(null),p=o.useRef(!1),y=o.useRef(null),m=o.useCallback(async()=>{if(e){if(p.current){console.log("[RiskScoring] Load already in progress, skipping...");return}p.current=!0,i(!0),u(null);try{const h=await t.getRiskCriterias(e);a(h),y.current=e}catch(h){u(h)}finally{i(!1),p.current=!1}}},[e,t]);o.useEffect(()=>{e&&y.current!==e&&m()},[e]);const j=o.useCallback(async h=>{c(!0),u(null);try{const b=await t.submitRiskScoring(h);return v(b),b}catch(b){throw u(b),b}finally{c(!1)}},[t]);return{criteria:s,result:w,isLoading:n,isSubmitting:l,error:d,load:m,submit:j}}function Et(){const{applicantService:e,config:t}=te(),[s,a]=o.useState(!1),[n,i]=o.useState(null),l=o.useRef(!1),c=o.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=o.useCallback(async y=>{var m;if(l.current)throw console.log("[Applicant] Create already in progress, skipping..."),new Error("Creation already in progress");l.current=!0,a(!0),i(null);try{if(y.applicantAdditionalDatas||(y.applicantAdditionalDatas=[]),(m=t.identityProviders)!=null&&m.sardinai){const h=d();console.log("[SardinAI] Generated session key:",h),y.applicantAdditionalDatas.push({paramName:"sessionKey",value:h})}return await e.createApplicant(y)}catch(j){throw i(j),j}finally{a(!1),l.current=!1}},[e,t]),w=o.useCallback(async y=>{a(!0),i(null);try{return await e.createCompanyApplicant(y)}catch(m){throw i(m),m}finally{a(!1)}},[e]),v=o.useCallback(async y=>{if(c.current)throw console.log("[Applicant] Data load already in progress, skipping..."),new Error("Data load already in progress");c.current=!0,a(!0),i(null);try{return await e.getApplicantData(y)}catch(m){throw i(m),m}finally{a(!1),c.current=!1}},[e]),p=o.useCallback(async y=>{a(!0),i(null);try{await e.stopProgress(y)}catch(m){throw i(m),m}finally{a(!1)}},[e]);return{isLoading:s,error:n,createApplicant:u,createCompanyApplicant:w,getApplicantData:v,stopProgress:p}}const z=({children:e,variant:t="primary",size:s="md",isLoading:a=!1,disabled:n,className:i,...l})=>{const c="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:Y(c,d[t],u[s],i),disabled:n||a,...l,children:[a&&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"})]}),e]})},X=o.forwardRef(({label:e,error:t,helperText:s,leftIcon:a,rightIcon:n,className:i,...l},c)=>r.jsxs("div",{className:"w-full",children:[e&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[e,l.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"relative",children:[a&&r.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none",children:a}),r.jsx("input",{ref:c,className:Y("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",t?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",a?"pl-10":"",n?"pr-10":"",i),...l}),n&&r.jsx("div",{className:"absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none",children:n})]}),t&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:t}),!t&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));X.displayName="Input";const F=({children:e,className:t,...s})=>r.jsx("div",{className:Y("metakyc-card rounded-xl shadow-sm border",t),style:{backgroundColor:"var(--metakyc-surface, #ffffff)",borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:e}),G=({children:e,className:t,...s})=>r.jsx("div",{className:Y("px-6 py-4 border-b",t),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:e}),P=({children:e,className:t,...s})=>r.jsx("div",{className:Y("px-6 py-4",t),...s,children:e}),ee=({children:e,className:t,...s})=>r.jsx("div",{className:Y("px-6 py-4 border-t",t),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:e}),ie=({children:e,variant:t="default",className:s,...a})=>{const n={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:Y("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",n[t],s),...a,children:e})},ae=({size:e="md",className:t,...s})=>{const a={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"};return r.jsx("div",{className:Y("flex items-center justify-center",t),...s,children:r.jsxs("svg",{className:Y("animate-spin text-primary-500",a[e]),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"})]})})},le=o.forwardRef(({label:e,error:t,helperText:s,options:a,placeholder:n,className:i,...l},c)=>r.jsxs("div",{className:"w-full",children:[e&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[e,l.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("select",{ref:c,className:Y("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",t?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",i),...l,children:[n&&r.jsx("option",{value:"",disabled:!0,children:n},"__placeholder__"),a.map((d,u)=>r.jsx("option",{value:d.value,disabled:d.disabled,children:d.label},d.value||`option-${u}`))]}),t&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:t}),!t&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));le.displayName="Select";const Rt=({label:e,value:t,onChange:s,options:a,placeholder:n="Select...",disabled:i=!1,required:l=!1})=>{const[c,d]=o.useState(!1),[u,w]=o.useState(""),v=o.useRef(null);o.useEffect(()=>{const h=b=>{v.current&&!v.current.contains(b.target)&&(d(!1),w(""))};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const p=a.filter(h=>h.label.toLowerCase().includes(u.toLowerCase())),y=h=>{i||(t.includes(h)?s(t.filter(b=>b!==h)):s([...t,h]))},m=(h,b)=>{b.stopPropagation(),i||s(t.filter(A=>A!==h))},j=h=>{var b;return((b=a.find(A=>A.value===h))==null?void 0:b.label)||h};return r.jsxs("div",{className:"w-full metakyc-multiselect",ref:v,children:[e&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[e,l&&r.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"relative",children:[r.jsxs("div",{onClick:()=>!i&&d(!c),className:Y("metakyc-multiselect-trigger","min-h-[42px] w-full px-3 py-2 rounded-lg border text-sm transition-colors","bg-white dark:bg-gray-800","border-gray-300 dark:border-gray-600",c&&"ring-2 ring-blue-500 border-transparent",i?"opacity-50 cursor-not-allowed":"cursor-pointer"),children:[t.length===0?r.jsx("span",{className:"metakyc-multiselect-placeholder text-gray-400 dark:text-gray-500 leading-6",children:n}):r.jsx("div",{className:"flex flex-wrap gap-1 pr-6",children:t.map(h=>r.jsxs("span",{className:"metakyc-multiselect-chip inline-flex items-center gap-1 px-2 py-0.5 rounded bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-300 text-xs font-medium",children:[j(h),!i&&r.jsx("button",{type:"button",onClick:b=>m(h,b),className:"metakyc-multiselect-chip-remove",style:{background:"transparent",border:"none",padding:"0 0 0 2px",margin:0,cursor:"pointer",fontSize:"14px",lineHeight:1,fontWeight:"bold",display:"inline-flex",alignItems:"center",boxShadow:"none",transform:"none",minWidth:0,width:"auto",height:"auto",letterSpacing:"normal",textTransform:"none"},children:"×"})]},h))}),r.jsx("span",{className:"metakyc-multiselect-arrow absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none text-xs",children:c?"▲":"▼"})]}),c&&r.jsxs("div",{className:"metakyc-multiselect-dropdown absolute z-50 w-full mt-1 rounded-lg shadow-lg",style:{background:"inherit",border:"1px solid #d1d5db"},children:[r.jsx("div",{className:"metakyc-multiselect-search-wrapper p-2",style:{borderBottom:"1px solid #e5e7eb"},children:r.jsx("input",{type:"text",value:u,onChange:h=>w(h.target.value),placeholder:"Search...",autoFocus:!0,onClick:h=>h.stopPropagation(),className:"metakyc-multiselect-search w-full px-2 py-1.5 text-sm rounded focus:outline-none focus:ring-1 focus:ring-blue-500",style:{border:"1px solid #d1d5db"}})}),r.jsx("ul",{className:"max-h-48 overflow-y-auto py-1",children:p.length===0?r.jsx("li",{className:"px-3 py-2 text-sm text-gray-500 dark:text-gray-400",children:"No results"}):p.map(h=>r.jsxs("li",{onClick:()=>y(h.value),className:Y("metakyc-multiselect-option","flex items-center gap-2 px-3 py-2 text-sm cursor-pointer","hover:bg-gray-50 dark:hover:bg-gray-700",t.includes(h.value)&&"metakyc-multiselect-option-selected bg-blue-50 dark:bg-blue-900/20"),children:[r.jsx("input",{type:"checkbox",checked:t.includes(h.value),readOnly:!0,className:"rounded border-gray-300 text-blue-600 pointer-events-none"}),r.jsx("span",{className:"text-gray-900 dark:text-gray-100",children:h.label})]},h.value))}),t.length>0&&r.jsx("div",{className:"metakyc-multiselect-clear p-2 border-t border-gray-100 dark:border-gray-700",children:r.jsxs("button",{type:"button",onClick:()=>{s([]),w("")},className:"text-xs text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300",children:["Clear all (",t.length," selected)"]})})]})]})]})},It=({label:e,error:t,accept:s,multiple:a=!1,maxSize:n,onChange:i,value:l=[],className:c})=>{const[d,u]=o.useState(!1),w=o.useRef(null),v=b=>{if(!b)return;const A=Array.from(b);if(n&&A.filter(C=>C.size>n).length>0){const C=ve(n);alert(`Some files exceed the maximum size of ${C}`);return}i==null||i(a?[...l,...A]:[A[0]])},p=b=>{b.preventDefault(),u(!0)},y=()=>{u(!1)},m=b=>{b.preventDefault(),u(!1),v(b.dataTransfer.files)},j=()=>{var b;(b=w.current)==null||b.click()},h=b=>{const A=l.filter((k,C)=>C!==b);i==null||i(A)};return r.jsxs("div",{className:Y("w-full",c),children:[e&&r.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e}),r.jsxs("div",{className:Y("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",t&&"border-danger-500"),onDragOver:p,onDragLeave:y,onDrop:m,onClick:j,children:[r.jsx("input",{ref:w,type:"file",className:"hidden",accept:s,multiple:a,onChange:b=>v(b.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"]}),n&&r.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum file size: ",ve(n)]})]})]}),l.length>0&&r.jsx("div",{className:"mt-3 space-y-2",children:l.map((b,A)=>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:b.name}),r.jsxs("span",{className:"text-xs text-gray-500",children:["(",ve(b.size),")"]})]}),r.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),h(A)},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"})})})]},A))}),t&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:t})]})},Dt=o.forwardRef(({countryCode:e="+1",onCountryCodeChange:t,className:s,...a},n)=>r.jsxs("div",{className:"w-full",children:[a.label&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[a.label,a.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:e,onChange:i=>t==null?void 0:t(i.target.value),className:Y("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(X,{ref:n,type:"tel",className:Y("flex-1",s),...a,label:""})]}),a.error&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:a.error})]}));Dt.displayName="PhoneInput";/**
1
+ "use strict";var Ht=Object.defineProperty;var qt=(e,t,s)=>t in e?Ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var U=(e,t,s)=>qt(e,typeof t!="symbol"?t+"":t,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Wt=require("axios"),o=require("react"),r=require("react/jsx-runtime"),ue=require("react-hook-form"),ce=require("zod");function Yt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const a=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,a.get?a:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const Re=Yt(o);var T=(e=>(e[e.IdentitySdk=0]="IdentitySdk",e[e.RiskScoring=1]="RiskScoring",e[e.Questionaries=2]="Questionaries",e[e.AdditionalData=3]="AdditionalData",e[e.AppropriatenessTest=4]="AppropriatenessTest",e[e.UploadDocument=5]="UploadDocument",e[e.ManualReview=6]="ManualReview",e[e.Overview=7]="Overview",e[e.InvestorCategorization=8]="InvestorCategorization",e))(T||{}),ye=(e=>(e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Success=2]="Success",e[e.PartialSuccess=3]="PartialSuccess",e[e.Failed=4]="Failed",e[e.Skipped=5]="Skipped",e[e.AdminReview=6]="AdminReview",e[e.SkippedAndAdminReview=7]="SkippedAndAdminReview",e))(ye||{}),se=(e=>(e[e.None=0]="None",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished",e[e.OnHold=3]="OnHold",e[e.IdentityPending=4]="IdentityPending",e))(se||{}),De=(e=>(e[e.None=0]="None",e[e.RepresentativeKYC=1]="RepresentativeKYC",e[e.ManualRiskCriteria=2]="ManualRiskCriteria",e[e.UploadDocumentReview=3]="UploadDocumentReview",e[e.AdminReview=4]="AdminReview",e))(De||{}),Fe=(e=>(e[e.LowRisk=0]="LowRisk",e[e.MediumRisk=1]="MediumRisk",e[e.HighRisk=2]="HighRisk",e[e.Alert=3]="Alert",e))(Fe||{}),me=(e=>(e[e.None=0]="None",e[e.Pending=1]="Pending",e[e.Approved=2]="Approved",e[e.Rejected=3]="Rejected",e[e.ResendRequested=4]="ResendRequested",e[e.Unknown=5]="Unknown",e[e.InProgress=6]="InProgress",e))(me||{}),pe=(e=>(e[e.Approved=0]="Approved",e[e.Reject=1]="Reject",e[e.UnderReview=2]="UnderReview",e[e.Closed=3]="Closed",e[e.AdminReview=4]="AdminReview",e[e.New=5]="New",e[e.InProgress=6]="InProgress",e))(pe||{}),Pe=(e=>(e[e.ProviderResultPending=0]="ProviderResultPending",e[e.ProviderResultReceived=1]="ProviderResultReceived",e[e.Canceled=2]="Canceled",e[e.ExtendedToNewApplicant=3]="ExtendedToNewApplicant",e))(Pe||{}),Le=(e=>(e[e.None=0]="None",e[e.ProviderResultPending=1]="ProviderResultPending",e[e.ProviderResultReceived=2]="ProviderResultReceived",e[e.Canceled=3]="Canceled",e))(Le||{}),re=(e=>(e[e.Onfido=0]="Onfido",e[e.Sumsub=2]="Sumsub",e[e.SardinAI=3]="SardinAI",e))(re||{}),Te=(e=>(e[e.Individual=0]="Individual",e[e.Company=1]="Company",e))(Te||{}),be=(e=>(e[e.Male=0]="Male",e[e.Female=1]="Female",e[e.Other=2]="Other",e))(be||{}),Me=(e=>(e[e.Image=0]="Image",e[e.Video=1]="Video",e[e.PDF=2]="PDF",e[e.OfficePDF=3]="OfficePDF",e[e.Custom=4]="Custom",e))(Me||{}),Oe=(e=>(e[e.Pending=0]="Pending",e[e.Approved=1]="Approved",e[e.Rejected=2]="Rejected",e[e.RequiresRevision=3]="RequiresRevision",e))(Oe||{}),ze=(e=>(e[e.SingleChoice=0]="SingleChoice",e[e.MultipleChoice=1]="MultipleChoice",e[e.Text=2]="Text",e))(ze||{}),oe=(e=>(e[e.String=0]="String",e[e.Integer=1]="Integer",e[e.Decimal=2]="Decimal",e[e.Boolean=3]="Boolean",e[e.Date=4]="Date",e[e.Country=5]="Country",e[e.DigitOnly=6]="DigitOnly",e))(oe||{}),Be=(e=>(e[e.Text=0]="Text",e[e.Radio=1]="Radio",e[e.Checkbox=2]="Checkbox",e[e.Dropdown=3]="Dropdown",e[e.Country=4]="Country",e))(Be||{}),Ke=(e=>(e[e.None=0]="None",e[e.Country=1]="Country",e))(Ke||{}),J=(e=>(e[e.Individual=0]="Individual",e[e.Sophisticated=1]="Sophisticated",e[e.HighNetWorth=2]="HighNetWorth",e[e.Business=3]="Business",e))(J||{}),Ue=(e=>(e[e.Retail=0]="Retail",e[e.Professional=1]="Professional",e[e.EligibleCounterparty=2]="EligibleCounterparty",e))(Ue||{});const je=[{value:"EN",label:"English"},{value:"DE",label:"German"},{value:"FR",label:"French"},{value:"ES",label:"Spanish"},{value:"IT",label:"Italian"},{value:"PT",label:"Portuguese"},{value:"NL",label:"Dutch"},{value:"PL",label:"Polish"},{value:"RU",label:"Russian"},{value:"ZH",label:"Chinese"},{value:"JA",label:"Japanese"},{value:"AR",label:"Arabic"},{value:"TR",label:"Turkish"},{value:"SV",label:"Swedish"},{value:"DA",label:"Danish"},{value:"FI",label:"Finnish"},{value:"NO",label:"Norwegian"}],_e=["firstName","lastName","email","phonenumber","dateOfBirth","street","streetNumber","zip","city","country","nationality","taxCountry","taxNumber"],Qt=["firstName","lastName","title","email","dateOfBirth","phonenumber","mobileCountryCode","street","streetNumber","zip","city","country","nationality","otherNationality","defaultLanguage","taxCountry","placeOfBirth","countryOfBirth","salutation","educationLevel","occupation","taxNumber","externalRefId"],Se={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:"select"},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 W=(e=>(e.Default="default",e.Corporate="corporate",e.Fintech="fintech",e.Healthcare="healthcare",e.Modern="modern",e.Minimal="minimal",e))(W||{});const $e={timeout:3e4,retries:3,locale:"en",endpoints:{pattern:"host-controller"}};class He{constructor(t){this.config=t}build(t,s){const a=`${t}.${s}`;if(this.config.customPaths&&this.config.customPaths[a])return this.config.customPaths[a];switch(this.config.pattern){case"host-controller":return`/api/${t}/${s}`;case"application-service":return`/services/app/${this.getServiceName(t)}/${s}`;case"custom":throw new Error(`Custom endpoint path not found for ${a}. Please provide it in customPaths.`);default:throw new Error(`Unknown endpoint pattern: ${this.config.pattern}`)}}getServiceName(t){return{Applicant:"MetaKYCVerification",Questionnaire:"MetaKYCVerification",UploadDocument:"MetaKYCVerification",AppropriatenessTest:"MetaKYCVerification",BaseInformation:"MetaKYCVerification"}[t]||t}}class ne extends Error{constructor(s,a,n,i,l){super(s);U(this,"response");this.code=a,this.details=n,this.validationErrors=i,this.name="MetaKYCError",this.response=l,Object.setPrototypeOf(this,ne.prototype)}}class ge{static handleApiError(t){return new ne(t.message||"An unknown error occurred",t.code,t.details||void 0,t.validationErrors||void 0)}static handleAxiosError(t){if(t.response){const s=t.response.data;return s&&s.error?new ne(s.error.message||"An unknown error occurred",s.error.code,s.error.details||void 0,s.error.validationErrors||void 0,t.response):s&&s.result&&s.result.message?new ne(s.result.message,t.response.status,`HTTP ${t.response.status}: ${t.response.statusText}`,void 0,t.response):new ne((s==null?void 0:s.message)||t.message||"Request failed",t.response.status,`HTTP ${t.response.status}: ${t.response.statusText}`,void 0,t.response)}else return t.request?new ne("No response from server",0,"The request was made but no response was received. Please check your network connection."):new ne(t.message||"An unexpected error occurred",0,t.toString())}static isMetaKYCError(t){return t instanceof ne}}class qe{constructor(t){U(this,"axiosInstance");U(this,"endpointBuilder");U(this,"config");this.config={...$e,...t},this.endpointBuilder=new He(this.config.endpoints),this.axiosInstance=Wt.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 n;const a=s.config;return((n=s.response)==null?void 0:n.status)>=500&&!a._retry&&(a._retry=!0,a._retryCount=(a._retryCount||0)+1,a._retryCount<(this.config.retries||3))?(await new Promise(i=>setTimeout(i,1e3*a._retryCount)),this.axiosInstance(a)):Promise.reject(s)})}buildEndpoint(t,s){return this.endpointBuilder.build(t,s)}async get(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.get(n,{params:a});return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}async post(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.post(n,a);return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}async put(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.put(n,a);return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}async delete(t,s,a){try{const n=this.buildEndpoint(t,s),i=await this.axiosInstance.delete(n,{params:a});return this.handleResponse(i)}catch(n){throw ge.handleAxiosError(n)}}handleResponse(t){const s=t.data;if(!s.success&&s.error)throw ge.handleApiError(s.error);return s}getAxiosInstance(){return this.axiosInstance}}class We{constructor(t){this.httpClient=t}async createApplicant(t){return(await this.httpClient.post("Applicant","ApplicantRegistrationRequest",t)).result}async createCompanyApplicant(t){return(await this.httpClient.post("Applicant","ApplicantCompanyRegistrationRequest",t)).result}async duplicateApplicant(t){return(await this.httpClient.post("Applicant","DuplicateApplicantRegistrationRequest",t)).result}async getProgress(t){return(await this.httpClient.get("Applicant","GetApplicantProgress",{applicantId:t})).result}async getProgressStatus(t){return(await this.httpClient.get("Applicant","GetApplicantProgressStaus",{applicantId:t})).result}async getApplicantData(t){return(await this.httpClient.get("Applicant","GetApplicantData",{applicantId:t})).result}async getApplicantStatus(t){return(await this.httpClient.get("Applicant","GetApplicantStatus",{applicantId:t})).result}async stopProgress(t){await this.httpClient.get("Applicant","StopProgress",{applicantId:t})}async progressStepBack(t){await this.httpClient.get("Applicant","ProgressStepBack",{applicantId:t})}async setLanguage(t,s){await this.httpClient.post("Applicant","SetApplicantLng",{applicantId:t,language:s})}async activateApplicant(t){await this.httpClient.get("Applicant","ActivateApplicant",{applicantId:t})}async deleteApplicant(t){await this.httpClient.delete("Applicant","DeleteApplicant",{applicantId:t})}async checkApplicantExists(t){return(await this.httpClient.get("Applicant","CheckApplicantIfExists",{externalRefId:t})).result}}class Ye{constructor(t){this.httpClient=t}async getQuestionnaire(t){return(await this.httpClient.get("Questionnaire","GetQuestionnaire",{applicantid:t})).result}async fillQuestionnaire(t){return(await this.httpClient.post("Applicant","FillQuestionnarie",t)).result}}class Qe{constructor(t){this.httpClient=t}async getUploadDocument(t){return(await this.httpClient.get("UploadDocument","GetUploadDocument",{applicantid:t})).result}async fillUploadDocument(t){await this.httpClient.post("Applicant","FillUploadDocument",t)}async reviewUploadDocument(t){await this.httpClient.post("UploadDocument","ReviewUploadDocument",t)}}class Ve{constructor(t){this.httpClient=t}async getAppropriatenessTest(t){return(await this.httpClient.get("AppropriatenessTest","GetAppropriatenessTest",{applicantid:t})).result}async fillAppropriatenessTest(t){return(await this.httpClient.post("Applicant","FillAppropriatenessTest",t)).result}}class Ge{constructor(t){this.httpClient=t}async getOverviewData(t){return(await this.httpClient.get("Applicant","GetOverviewData",{ApplicantId:t})).result}async passOverview(t){await this.httpClient.get("Applicant","PassOverview",{applicantId:t})}}class Ze{constructor(t){this.httpClient=t}async getRiskScoringPlan(){return(await this.httpClient.get("Applicant","GetRiskScoringPlanInfo")).result}async getRiskCriterias(t){return(await this.httpClient.get("Risk","GetCriterias",{applicantId:t})).result}async submitRiskScoring(t){return(await this.httpClient.post("Applicant","RiskScoringRequest",t)).result}}class Je{constructor(t){this.httpClient=t}async identityRequest(t){console.log("[IdentityService] Calling IdentityRequest with input:",t);const s=await this.httpClient.post("Applicant","IdentityRequest",t);return console.log("[IdentityService] IdentityRequest response:",s),s.result}async identityCompanyRequest(t){return(await this.httpClient.post("Applicant","IdentityCompanyRequest",t)).result}async restartIdentityRequest(t){const s={applicantId:t,restart:!0,redirectUrl:"",ttl:604800};return console.log("[IdentityService] Restarting identity with restart=true:",s),this.identityRequest(s)}async restartIdentityCompanyRequest(t){const s={applicantId:t,restart:!0,redirectUrl:"",ttl:604800};return this.identityCompanyRequest(s)}}class Xe{constructor(t){this.httpClient=t}async getCountries(t,s,a){return(await this.httpClient.get("BaseInformation","GetAllCountries",{filter:t||"",lng:s||"en",type:a})).result}async getBranches(){return(await this.httpClient.get("BaseInformation","GetBranches")).result}async getLegalEntities(){return(await this.httpClient.get("BaseInformation","GetLegalEntities")).result}}class et{constructor(t){this.httpClient=t}async setInvestorCategorization(t){return(await this.httpClient.post("Applicant","SetInvestorCategorization",t)).result}async getInvestorCategorization(t){return(await this.httpClient.get("Applicant","GetInvestorCategorisation",{applicantId:t})).result}}const V={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"}}},tt={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"}},rt={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"}},st={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"}}},at={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"}},nt={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"}},it={[W.Default]:V,[W.Corporate]:tt,[W.Fintech]:rt,[W.Healthcare]:st,[W.Modern]:at,[W.Minimal]:nt};function xe(e){return it[e]||V}class ot{constructor(t){this.httpClient=t}async getThemeConfiguration(){var t;try{const s=await this.httpClient.get("Tenant","GetThemeConfiguration");if(!s.result.isEnabled)return xe(W.Default);let a=s.result.preset?xe(s.result.preset):xe(W.Default);return s.result.title&&(a.title=s.result.title),s.result.logo&&(a.logo={...a.logo,...s.result.logo}),s.result.colors&&(a.colors={...a.colors,...s.result.colors}),s.result.typography&&(a.typography={...a.typography,...s.result.typography}),s.result.spacing&&(a.spacing={...a.spacing,...s.result.spacing}),s.result.customCSS&&(a.customCSS=s.result.customCSS),s.result.darkMode&&(a.darkMode={colors:{...(t=a.darkMode)==null?void 0:t.colors,...s.result.darkMode.colors}}),s.result.applicantFormVisibleFields&&s.result.applicantFormVisibleFields.length>0&&(a.applicantFormVisibleFields=s.result.applicantFormVisibleFields),s.result.applicantFormRequiredFields&&s.result.applicantFormRequiredFields.length>0&&(a.applicantFormRequiredFields=s.result.applicantFormRequiredFields),s.result.allowedLanguages&&s.result.allowedLanguages.length>0&&(a.allowedLanguages=s.result.allowedLanguages),a}catch(s){return console.warn("[ThemeService] Failed to fetch theme configuration:",s),xe(W.Default)}}async saveThemeConfiguration(t){await this.httpClient.post("Tenant","SaveThemeConfiguration",t)}getAvailablePresets(){return[{id:W.Default,name:"Default"},{id:W.Corporate,name:"Corporate"},{id:W.Fintech,name:"Fintech"},{id:W.Healthcare,name:"Healthcare"},{id:W.Modern,name:"Modern"},{id:W.Minimal,name:"Minimal"}]}getPreviewTheme(t,s){const a=xe(t);return s?{...a,...s,logo:{...a.logo,...s.logo},colors:{...a.colors,...s.colors},typography:s.typography?{...a.typography,...s.typography}:a.typography,spacing:s.spacing?{...a.spacing,...s.spacing}:a.spacing}:a}}class lt{constructor(){U(this,"listeners",new Map)}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{this.off(t,s)}}off(t,s){const a=this.listeners.get(t);a&&a.delete(s)}emit(t,s){const a=this.listeners.get(t);a&&a.forEach(n=>{try{n(s)}catch(i){console.error(`Error in event listener for "${t}":`,i)}})}clear(){this.listeners.clear()}clearEvent(t){this.listeners.delete(t)}}class ct{constructor(){U(this,"events",new lt);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 t;return((t=this._progress)==null?void 0:t.currentStep)||null}get steps(){var t;return((t=this._progress)==null?void 0:t.stepInfoList)||[]}get status(){var t;return((t=this._progress)==null?void 0:t.status)||se.None}get workflowResult(){var t;return((t=this._progress)==null?void 0:t.workflowResult)||null}get error(){return this._error}get isComplete(){return this.status===se.Finished}get isOnHold(){return this.status===se.OnHold}get isInProgress(){return this.status===se.InProgress}setApplicantId(t){this._applicantId=t}updateProgress(t){var a,n;const s=(a=this._progress)==null?void 0:a.currentStep;this._progress=t,this._applicantId=t.applicantId,this._error=null,this.events.emit("progressUpdated",t),(s==null?void 0:s.order)!==((n=t.currentStep)==null?void 0:n.order)&&this.events.emit("stepChanged",t.currentStep),this.events.emit("statusChanged",t.status),t.status===se.Finished&&t.workflowResult&&this.events.emit("completed",t.workflowResult)}setError(t){this._error=t,this.events.emit("error",t)}clearError(){this._error=null}reset(){this._applicantId=null,this._progress=null,this._error=null}onProgressUpdated(t){return this.events.on("progressUpdated",t)}onStepChanged(t){return this.events.on("stepChanged",t)}onStatusChanged(t){return this.events.on("statusChanged",t)}onError(t){return this.events.on("error",t)}onCompleted(t){return this.events.on("completed",t)}clearListeners(){this.events.clear()}}class dt{constructor(){U(this,"handlers",new Map)}registerHandler(t,s){this.handlers.set(t,s)}getHandler(t){return this.handlers.get(t)}hasHandler(t){return this.handlers.has(t)}async loadStepData(t,s){const a=this.getHandler(t);if(!a)throw new Error(`No handler registered for step action: ${T[t]}`);return a.loadData(s)}async submitStepData(t,s){const a=this.getHandler(t);if(!a)throw new Error(`No handler registered for step action: ${T[t]}`);return a.submitData(s)}}class ut{constructor(t,s,a,n,i,l,c,d){U(this,"state");U(this,"stepRouter");this.applicantService=t,this.questionnaireService=s,this.uploadDocumentService=a,this.appropriatenessTestService=n,this.overviewService=i,this.riskScoringService=l,this.investorCategorizationService=d,this.state=new ct,this.stepRouter=new dt,this.registerStepHandlers()}registerStepHandlers(){this.stepRouter.registerHandler(T.Questionaries,{loadData:t=>this.questionnaireService.getQuestionnaire(t),submitData:async t=>{await this.questionnaireService.fillQuestionnaire(t)}}),this.stepRouter.registerHandler(T.UploadDocument,{loadData:t=>this.uploadDocumentService.getUploadDocument(t),submitData:t=>this.uploadDocumentService.fillUploadDocument(t)}),this.stepRouter.registerHandler(T.AppropriatenessTest,{loadData:t=>this.appropriatenessTestService.getAppropriatenessTest(t),submitData:async t=>{await this.appropriatenessTestService.fillAppropriatenessTest(t)}}),this.stepRouter.registerHandler(T.Overview,{loadData:t=>this.overviewService.getOverviewData(t),submitData:t=>this.overviewService.passOverview(t.applicantId)}),this.stepRouter.registerHandler(T.RiskScoring,{loadData:t=>this.riskScoringService.getRiskCriterias(t),submitData:async t=>{await this.riskScoringService.submitRiskScoring(t)}}),this.stepRouter.registerHandler(T.IdentitySdk,{loadData:async t=>({applicantId:t,message:"Identity verification required"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.InvestorCategorization,{loadData:t=>this.investorCategorizationService.getInvestorCategorization(t),submitData:async t=>{await this.investorCategorizationService.setInvestorCategorization(t)}}),this.stepRouter.registerHandler(T.ManualReview,{loadData:async t=>({applicantId:t,message:"Your application is under manual review"}),submitData:async()=>{}}),this.stepRouter.registerHandler(T.AdditionalData,{loadData:async t=>({applicantId:t,message:"Additional data required"}),submitData:async()=>{}})}async initialize(t){try{this.state.setApplicantId(t);const s=await this.applicantService.getProgress(t);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 t=await this.applicantService.getProgress(this.state.applicantId);return this.state.updateProgress(t),t}catch(t){throw this.state.setError(t),t}}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(t){throw this.state.setError(t),t}}async submitCurrentStep(t){if(!this.state.currentStep)throw new Error("No current step available");try{await this.stepRouter.submitStepData(this.state.currentStep.action,t),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(t){throw this.state.setError(t),t}}getState(){return this.state}getStepRouter(){return this.stepRouter}}function Ce(e,t){return new Promise((s,a)=>{if(t&&document.getElementById(t)){s();return}const n=document.createElement("script");n.src=e,t&&(n.id=t),n.async=!0,n.onload=()=>s(),n.onerror=()=>a(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}function Vt(e){return!!document.getElementById(e)}function Gt(e){const t=document.getElementById(e);t&&t.remove()}class mt{constructor(t){U(this,"sdk",null);U(this,"config");this.config=t}async loadSDK(){await Ce("https://cdn.sumsub.com/websdk/v2/production/websdk.js","sumsub-sdk")}async initialize(t){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(`#${t}`)}destroy(){this.sdk&&(this.sdk.destroy(),this.sdk=null)}onComplete(t){this.sdk&&this.sdk.on("idCheck.applicantStatus",s=>{s.applicantStatus==="completed"&&t(s)})}onError(t){this.sdk&&this.sdk.on("idCheck.onError",t)}}class pt{constructor(t){U(this,"sdk",null);U(this,"config");this.config=t}async loadSDK(){await Ce("https://sdk.onfido.com/v12.0.0/onfido.min.js","onfido-sdk")}async initialize(t){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:t,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 ht{constructor(t){U(this,"sardineContext",null);U(this,"config");U(this,"sessionKey");this.config=t,this.sessionKey=t.sessionKey||this.generateSessionKey()}generateSessionKey(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const s=Math.random()*16|0;return(t==="x"?s:s&3|8).toString(16)})}getSardineHost(){const{environment:t,region:s}=this.config;if(t==="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((t,s)=>{if(window._Sardine){t();return}const a=this.getSardineHost(),n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=`https://${a}/assets/loader.min.js`,n.onload=()=>{console.log("[SardinAI] SDK loaded successfully"),t()},n.onerror=()=>{s(new Error("Failed to load SardinAI SDK"))};const i=document.getElementsByTagName("script")[0];i&&i.parentNode?i.parentNode.insertBefore(n,i):document.head.appendChild(n)})}async initialize(){try{if(await this.loadSDK(),!window._Sardine)throw new Error("SardinAI SDK not available after loading");const t=this.getSardineHost(),{clientId:s,environment:a,flow:n,enableBiometrics:i,enablePortScanning:l}=this.config;this.sardineContext=window._Sardine.createContext({clientId:s,sessionKey:this.sessionKey,userIdHash:void 0,flow:n||window.location.pathname,environment:a||"production",parentElement:document.body,enableBiometrics:i!==!1,enablePortScanning:l===!0,region:this.config.region,onDeviceResponse:c=>{console.log(`[SardinAI] Device ID: ${c.deviceId}`)},onConfigUpdate:(c,d,u)=>{switch(c){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:",c)}}}),this.addNoScriptFallback(t),console.log("[SardinAI] SDK initialized with sessionKey:",this.sessionKey)}catch(t){throw console.error("[SardinAI] Initialization failed:",t),t}}addNoScriptFallback(t){const s=document.createElement("noscript"),a=document.createElement("img"),{clientId:n,flow:i}=this.config;a.src=`https://${t}/v1/a.png?clientId=${n}&sessionKey=${this.sessionKey}&flow=${i||"kyc"}&ns=1`,a.style.display="none",s.appendChild(a),document.body.appendChild(s)}updateConfig(t){if(!this.sardineContext){console.warn("[SardinAI] Cannot update config - SDK not initialized");return}t.sessionKey&&(this.sessionKey=t.sessionKey),this.sardineContext.updateConfig({...t,onConfigUpdate:(s,a,n)=>{switch(s){case"SESSION_UPDATE_FAILED":console.error("[SardinAI] Config update failed:",n);break;case"SESSION_UPDATED":console.log("[SardinAI] Config updated:",a);break;case"SESSION_NO_UPDATE":console.log("[SardinAI] No config update needed");break}}})}getSessionKey(){return this.sessionKey}destroy(){this.sardineContext&&(this.sardineContext=null)}}class he{static createProvider(t,s){switch(t){case re.Sumsub:return new mt(s);case re.Onfido:return new pt(s);case re.SardinAI:return new ht(s);default:throw new Error(`Unsupported identity provider: ${t}`)}}static parseProviderConfig(t,s,a){var n;switch(t){case re.Sumsub:return{accessToken:s.accessToken||s.token,applicantEmail:s.email,applicantPhone:s.phone,externalUserId:s.externalUserId,lang:s.lang||"en"};case re.Onfido:return{token:s.token||s.sdkToken};case re.SardinAI:const i=((n=a==null?void 0:a.identityProviders)==null?void 0:n.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: ${t}`)}}}class gt{constructor(t){U(this,"currentTheme",V);U(this,"customStyleElement",null);U(this,"container");this.container=t||document.documentElement}applyTheme(t){this.currentTheme=this.mergeWithDefault(t),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(t){var a;const s={primary:t.primary,"primary-hover":t.primaryHover,"primary-light":t.primaryLight,"primary-dark":t.primaryDark,secondary:t.secondary,"secondary-hover":t.secondaryHover,success:t.success,warning:t.warning,danger:t.danger,info:t.info,background:t.background,surface:t.surface,border:t.border,"text-primary":t.textPrimary,"text-secondary":t.textSecondary,"text-muted":t.textMuted};Object.entries(s).forEach(([n,i])=>{this.container.style.setProperty(`--metakyc-${n}`,i)}),(a=this.currentTheme.darkMode)!=null&&a.colors&&this.applyDarkModeColors(this.currentTheme.darkMode.colors)}applyDarkModeColors(t){Object.entries(t).forEach(([s,a])=>{if(a){const n=`--metakyc-dark-${this.kebabCase(s)}`;this.container.style.setProperty(n,a)}})}applyTypography(t){t&&(t.fontFamily&&this.container.style.setProperty("--metakyc-font-family",t.fontFamily),t.headingFont&&this.container.style.setProperty("--metakyc-heading-font",t.headingFont),t.fontSize&&Object.entries(t.fontSize).forEach(([s,a])=>{this.container.style.setProperty(`--metakyc-font-size-${s}`,a)}),t.fontWeight&&Object.entries(t.fontWeight).forEach(([s,a])=>{this.container.style.setProperty(`--metakyc-font-weight-${s}`,a.toString())}))}applySpacing(t){t&&Object.entries(t).forEach(([s,a])=>{const n=`--metakyc-${this.kebabCase(s)}`;this.container.style.setProperty(n,a)})}injectCustomCSS(t){this.customStyleElement&&this.customStyleElement.remove(),this.customStyleElement=document.createElement("style"),this.customStyleElement.id="metakyc-custom-css",this.customStyleElement.textContent=t,document.head.appendChild(this.customStyleElement)}mergeWithDefault(t){var s;return{name:t.name||V.name,title:t.title||V.title,logo:{...V.logo,...t.logo},colors:{...V.colors,...t.colors},typography:t.typography?{...V.typography,...t.typography}:V.typography,spacing:t.spacing?{...V.spacing,...t.spacing}:V.spacing,customCSS:t.customCSS,darkMode:t.darkMode?{colors:{...(s=V.darkMode)==null?void 0:s.colors,...t.darkMode.colors}}:V.darkMode,applicantFormVisibleFields:t.applicantFormVisibleFields,applicantFormRequiredFields:t.applicantFormRequiredFields,allowedLanguages:t.allowedLanguages}}getCurrentTheme(){return this.currentTheme}resetTheme(){this.applyTheme(V)}cleanup(){this.customStyleElement&&(this.customStyleElement.remove(),this.customStyleElement=null)}kebabCase(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}}const Ae=o.createContext(null),Zt=({config:e,children:t})=>{const[s,a]=o.useState(null),n=o.useRef(!1),i=o.useRef(!1),l=o.useMemo(()=>{const d=new qe(e),u=new We(d),w=new Ye(d),v=new Qe(d),p=new Ve(d),y=new Ge(d),m=new Ze(d),k=new Je(d),h=new Xe(d),b=new et(d),A=new ot(d),j=new gt;return{httpClient:d,applicantService:u,questionnaireService:w,uploadDocumentService:v,appropriatenessTestService:p,overviewService:y,riskScoringService:m,identityService:k,baseInformationService:h,investorCategorizationService:b,themeService:A,themeManager:j}},[e]),c=o.useMemo(()=>({config:e,...l,currentTheme:s,createOrchestrator:()=>new ut(l.applicantService,l.questionnaireService,l.uploadDocumentService,l.appropriatenessTestService,l.overviewService,l.riskScoringService,l.identityService,l.investorCategorizationService)}),[e,l,s]);return o.useEffect(()=>((async()=>{if(n.current||i.current){console.log("[MetaKYC] Theme already loading or loaded, skipping...");return}n.current=!0;try{if(e.theme){console.log("[MetaKYC] Applying static theme from config"),l.themeManager.applyTheme(e.theme),a(l.themeManager.getCurrentTheme()),i.current=!0;return}console.log("[MetaKYC] Fetching theme from backend...");const u=await l.themeService.getThemeConfiguration();l.themeManager.applyTheme(u),a(l.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),a(l.themeManager.getCurrentTheme()),i.current=!0}finally{n.current=!1}})(),()=>{l.themeManager.cleanup()}),[]),r.jsx(Ae.Provider,{value:c,children:t})};function te(){const e=o.useContext(Ae);if(!e)throw new Error("useMetaKYC must be used within a MetaKYCProvider");return e}async function xt(e){return new Promise((t,s)=>{const a=new FileReader;a.readAsDataURL(e),a.onload=()=>{const i=a.result.split(",")[1];t(i)},a.onerror=n=>s(n)})}function Jt(e,t){return e.size<=t}function Xt(e,t){return t.split(",").map(a=>a.trim()).some(a=>{if(a.endsWith("/*")){const n=a.slice(0,-2);return e.type.startsWith(n)}return e.type===a})}function ve(e){if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/Math.pow(t,a)*100)/100+" "+s[a]}function er(e){return e}function Y(...e){return e.filter(Boolean).join(" ")}const fe={APPLICANT_ID:"metakyc_applicant_id",WORKFLOW_STATE:"metakyc_workflow_state"};function ft(e){try{localStorage.setItem(fe.APPLICANT_ID,e.toString())}catch(t){console.warn("Failed to save applicant ID to storage:",t)}}function yt(){try{const e=localStorage.getItem(fe.APPLICANT_ID);return e?parseInt(e,10):null}catch(e){return console.warn("Failed to retrieve applicant ID from storage:",e),null}}function bt(){try{localStorage.removeItem(fe.APPLICANT_ID)}catch(e){console.warn("Failed to clear applicant ID from storage:",e)}}function vt(e){try{localStorage.setItem(fe.WORKFLOW_STATE,JSON.stringify(e))}catch(t){console.warn("Failed to save workflow state to storage:",t)}}function tr(){try{const e=localStorage.getItem(fe.WORKFLOW_STATE);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to retrieve workflow state from storage:",e),null}}function wt(){try{localStorage.removeItem(fe.WORKFLOW_STATE)}catch(e){console.warn("Failed to clear workflow state from storage:",e)}}function rr(){bt(),wt()}function kt(e){const{createOrchestrator:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(null),d=o.useRef(null),u=e||yt();o.useEffect(()=>{d.current||(d.current=t())},[t]),o.useEffect(()=>{var j;s&&u&&(ft(u),vt({applicantId:u,currentStepOrder:(j=s.currentStep)==null?void 0:j.order,status:s.status,lastUpdated:new Date().toISOString(),workflowKey:s.workFlowKey,nextWorkflowKey:s.nextWorkflowKey}))},[s,u]);const w=o.useRef(!1),v=o.useRef(!1),p=o.useCallback(async()=>{if(!(!u||!d.current)){if(w.current){console.log("[Workflow] Load already in progress, skipping...");return}w.current=!0,i(!0),c(null);try{const j=await d.current.initialize(u);a(j),v.current=!0}catch(j){c(j)}finally{i(!1),w.current=!1}}},[u]);o.useEffect(()=>{u&&!v.current&&p()},[u,p]);const y=o.useCallback(async()=>{if(d.current){if(w.current){console.log("[Workflow] Refresh already in progress, skipping...");return}w.current=!0,i(!0),c(null);try{const j=await d.current.refreshProgress();a(j)}catch(j){c(j)}finally{i(!1),w.current=!1}}},[]),m=o.useCallback(async()=>{if(d.current){i(!0),c(null);try{const j=await d.current.moveToNextStep();a(j)}catch(j){c(j)}finally{i(!1)}}},[]),k=o.useCallback(async()=>{if(d.current){i(!0),c(null);try{const j=await d.current.moveToPreviousStep();a(j)}catch(j){c(j)}finally{i(!1)}}},[]),h=o.useCallback(async j=>{if(d.current){i(!0),c(null);try{await d.current.submitCurrentStep(j);const C=await d.current.refreshProgress();a(C)}catch(C){throw c(C),C}finally{i(!1)}}},[]),b=Re.useMemo(()=>s!=null&&s.stepInfoList?[...s.stepInfoList].sort((j,C)=>j.order-C.order):[],[s==null?void 0:s.stepInfoList]),A=Re.useMemo(()=>s?s.nextWorkflowKey&&s.nextWorkflowKey!==s.workFlowKey:!1,[s]);return{progress:s,applicantId:u,currentStep:(s==null?void 0:s.currentStep)||null,steps:b,status:(s==null?void 0:s.status)||se.None,workflowResult:(s==null?void 0:s.workflowResult)||null,workflowKey:s==null?void 0:s.workFlowKey,nextWorkflowKey:s==null?void 0:s.nextWorkflowKey,hasWorkflowChanged:A,isLoading:n,error:l,isComplete:(s==null?void 0:s.status)===se.Finished,isOnHold:(s==null?void 0:s.status)===se.OnHold,refreshProgress:y,moveToNext:m,moveBack:k,submitCurrentStep:h,orchestrator:d.current}}function jt(e){const{questionnaireService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),w=o.useRef(!1),v=o.useRef(null),p=o.useCallback(async()=>{if(e){if(w.current){console.log("[Questionnaire] Load already in progress, skipping...");return}w.current=!0,i(!0),u(null);try{const m=await t.getQuestionnaire(e);a(m),v.current=e}catch(m){u(m)}finally{i(!1),w.current=!1}}},[e,t]);o.useEffect(()=>{e&&v.current!==e&&p()},[e]);const y=o.useCallback(async m=>{c(!0),u(null);try{return await t.fillQuestionnaire(m)}catch(k){throw u(k),k}finally{c(!1)}},[t]);return{questionnaire:s,isLoading:n,isSubmitting:l,error:d,load:p,submit:y}}function St(e){const{uploadDocumentService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(0),[w,v]=o.useState(null),p=o.useRef(!1),y=o.useRef(null),m=o.useCallback(async()=>{if(e){if(p.current){console.log("[UploadDocument] Load already in progress, skipping...");return}p.current=!0,i(!0),v(null);try{const h=await t.getUploadDocument(e);a(h),y.current=e}catch(h){v(h)}finally{i(!1),p.current=!1}}},[e,t]);o.useEffect(()=>{e&&y.current!==e&&m()},[e]);const k=o.useCallback(async h=>{c(!0),u(0),v(null);try{await t.fillUploadDocument(h),u(100)}catch(b){throw v(b),b}finally{c(!1)}},[t]);return{uploadDocument:s,isLoading:n,isSubmitting:l,uploadProgress:d,error:w,load:m,submit:k}}function sr(e){const{appropriatenessTestService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),[w,v]=o.useState(null),p=o.useRef(!1),y=o.useRef(null),m=o.useCallback(async()=>{if(e){if(p.current){console.log("[AppropriatenessTest] Load already in progress, skipping...");return}p.current=!0,i(!0),u(null);try{const h=await t.getAppropriatenessTest(e);a(h),y.current=e}catch(h){u(h)}finally{i(!1),p.current=!1}}},[e,t]);o.useEffect(()=>{e&&y.current!==e&&m()},[e]);const k=o.useCallback(async h=>{c(!0),u(null);try{const b=await t.fillAppropriatenessTest(h);return v(b),b}catch(b){throw u(b),b}finally{c(!1)}},[t]);return{test:s,result:w,isLoading:n,isSubmitting:l,error:d,load:m,submit:k}}function Nt(e){const{overviewService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),w=o.useRef(!1),v=o.useRef(null),p=o.useCallback(async()=>{if(e){if(w.current){console.log("[Overview] Load already in progress, skipping...");return}w.current=!0,i(!0),u(null);try{const m=await t.getOverviewData(e);a(m),v.current=e}catch(m){u(m)}finally{i(!1),w.current=!1}}},[e,t]);o.useEffect(()=>{e&&v.current!==e&&p()},[e]);const y=o.useCallback(async()=>{if(e){c(!0),u(null);try{await t.passOverview(e)}catch(m){throw u(m),m}finally{c(!1)}}},[e,t]);return{overview:s,isLoading:n,isSubmitting:l,error:d,load:p,passOverview:y}}function Ct(e){const{identityService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(null),d=o.useRef(!1),u=o.useCallback(async(p,y)=>{if(e){if(d.current){console.log("[Identity] Request already in progress, skipping...");return}d.current=!0,i(!0),c(null);try{const m={applicantId:e,restart:!1,redirectUrl:p||"",ttl:y||604800};console.log("Identity request input:",m);const k=await t.identityRequest(m);return console.log("Identity request result:",k),a(k),k}catch(m){throw c(m),m}finally{i(!1),d.current=!1}}},[e,t]),w=o.useCallback(async(p,y)=>{if(e){i(!0),c(null);try{const m={applicantId:e,restart:!1,redirectUrl:p,ttl:y},k=await t.identityCompanyRequest(m);return a(k),k}catch(m){throw c(m),m}finally{i(!1)}}},[e,t]),v=o.useCallback(async()=>{if(e){if(d.current){console.log("[Identity] Restart already in progress, skipping...");return}d.current=!0,i(!0),c(null);try{const p={applicantId:e,restart:!0,redirectUrl:"",ttl:604800};console.log("Restarting identity with input:",p);const y=await t.identityRequest(p);return console.log("Restart identity result:",y),a(y),y}catch(p){throw c(p),p}finally{i(!1),d.current=!1}}},[e,t]);return{identityData:s,provider:(s==null?void 0:s.provider)||null,token:(s==null?void 0:s.publicProviderTokenObject)||null,isLoading:n,error:l,requestIdentity:u,requestCompanyIdentity:w,restartIdentity:v}}function At(e){const{riskScoringService:t}=te(),[s,a]=o.useState(null),[n,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),[w,v]=o.useState(null),p=o.useRef(!1),y=o.useRef(null),m=o.useCallback(async()=>{if(e){if(p.current){console.log("[RiskScoring] Load already in progress, skipping...");return}p.current=!0,i(!0),u(null);try{const h=await t.getRiskCriterias(e);a(h),y.current=e}catch(h){u(h)}finally{i(!1),p.current=!1}}},[e,t]);o.useEffect(()=>{e&&y.current!==e&&m()},[e]);const k=o.useCallback(async h=>{c(!0),u(null);try{const b=await t.submitRiskScoring(h);return v(b),b}catch(b){throw u(b),b}finally{c(!1)}},[t]);return{criteria:s,result:w,isLoading:n,isSubmitting:l,error:d,load:m,submit:k}}function Et(){const{applicantService:e,config:t}=te(),[s,a]=o.useState(!1),[n,i]=o.useState(null),l=o.useRef(!1),c=o.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=o.useCallback(async y=>{var m;if(l.current)throw console.log("[Applicant] Create already in progress, skipping..."),new Error("Creation already in progress");l.current=!0,a(!0),i(null);try{if(y.applicantAdditionalDatas||(y.applicantAdditionalDatas=[]),(m=t.identityProviders)!=null&&m.sardinai){const h=d();console.log("[SardinAI] Generated session key:",h),y.applicantAdditionalDatas.push({paramName:"sessionKey",value:h})}return await e.createApplicant(y)}catch(k){throw i(k),k}finally{a(!1),l.current=!1}},[e,t]),w=o.useCallback(async y=>{a(!0),i(null);try{return await e.createCompanyApplicant(y)}catch(m){throw i(m),m}finally{a(!1)}},[e]),v=o.useCallback(async y=>{if(c.current)throw console.log("[Applicant] Data load already in progress, skipping..."),new Error("Data load already in progress");c.current=!0,a(!0),i(null);try{return await e.getApplicantData(y)}catch(m){throw i(m),m}finally{a(!1),c.current=!1}},[e]),p=o.useCallback(async y=>{a(!0),i(null);try{await e.stopProgress(y)}catch(m){throw i(m),m}finally{a(!1)}},[e]);return{isLoading:s,error:n,createApplicant:u,createCompanyApplicant:w,getApplicantData:v,stopProgress:p}}const z=({children:e,variant:t="primary",size:s="md",isLoading:a=!1,disabled:n,className:i,...l})=>{const c="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:Y(c,d[t],u[s],i),disabled:n||a,...l,children:[a&&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"})]}),e]})},X=o.forwardRef(({label:e,error:t,helperText:s,leftIcon:a,rightIcon:n,className:i,...l},c)=>r.jsxs("div",{className:"w-full",children:[e&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[e,l.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"relative",children:[a&&r.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none",children:a}),r.jsx("input",{ref:c,className:Y("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",t?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",a?"pl-10":"",n?"pr-10":"",i),...l}),n&&r.jsx("div",{className:"absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none",children:n})]}),t&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:t}),!t&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));X.displayName="Input";const F=({children:e,className:t,...s})=>r.jsx("div",{className:Y("metakyc-card rounded-xl shadow-sm border",t),style:{backgroundColor:"var(--metakyc-surface, #ffffff)",borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:e}),G=({children:e,className:t,...s})=>r.jsx("div",{className:Y("px-6 py-4 border-b",t),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:e}),P=({children:e,className:t,...s})=>r.jsx("div",{className:Y("px-6 py-4",t),...s,children:e}),ee=({children:e,className:t,...s})=>r.jsx("div",{className:Y("px-6 py-4 border-t",t),style:{borderColor:"var(--metakyc-border, #e5e7eb)"},...s,children:e}),ie=({children:e,variant:t="default",className:s,...a})=>{const n={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:Y("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",n[t],s),...a,children:e})},ae=({size:e="md",className:t,...s})=>{const a={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"};return r.jsx("div",{className:Y("flex items-center justify-center",t),...s,children:r.jsxs("svg",{className:Y("animate-spin text-primary-500",a[e]),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"})]})})},le=o.forwardRef(({label:e,error:t,helperText:s,options:a,placeholder:n,className:i,...l},c)=>r.jsxs("div",{className:"w-full",children:[e&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[e,l.required&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),r.jsxs("select",{ref:c,className:Y("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",t?"border-danger-500 focus:ring-danger-500":"border-gray-300 dark:border-gray-600","dark:bg-gray-800 dark:text-white",i),...l,children:[n&&r.jsx("option",{value:"",disabled:!0,children:n},"__placeholder__"),a.map((d,u)=>r.jsx("option",{value:d.value,disabled:d.disabled,children:d.label},d.value||`option-${u}`))]}),t&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:t}),!t&&s&&r.jsx("p",{className:"mt-1 text-sm text-gray-500",children:s})]}));le.displayName="Select";const Rt=({label:e,value:t,onChange:s,options:a,placeholder:n="Select...",disabled:i=!1,required:l=!1})=>{const[c,d]=o.useState(!1),[u,w]=o.useState(""),v=o.useRef(null);o.useEffect(()=>{const h=b=>{v.current&&!v.current.contains(b.target)&&(d(!1),w(""))};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const p=a.filter(h=>h.label.toLowerCase().includes(u.toLowerCase())),y=h=>{i||(t.includes(h)?s(t.filter(b=>b!==h)):s([...t,h]))},m=(h,b)=>{b.stopPropagation(),i||s(t.filter(A=>A!==h))},k=h=>{var b;return((b=a.find(A=>A.value===h))==null?void 0:b.label)||h};return r.jsxs("div",{className:"w-full metakyc-multiselect",ref:v,children:[e&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[e,l&&r.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),r.jsxs("div",{className:"relative",children:[r.jsxs("div",{onClick:()=>!i&&d(!c),className:Y("metakyc-multiselect-trigger","min-h-[42px] w-full px-3 py-2 rounded-lg border text-sm transition-colors","bg-white dark:bg-gray-800","border-gray-300 dark:border-gray-600",c&&"ring-2 ring-blue-500 border-transparent",i?"opacity-50 cursor-not-allowed":"cursor-pointer"),children:[t.length===0?r.jsx("span",{className:"metakyc-multiselect-placeholder text-gray-400 dark:text-gray-500 leading-6",children:n}):r.jsx("div",{className:"flex flex-wrap gap-1 pr-6",children:t.map(h=>r.jsxs("span",{className:"metakyc-multiselect-chip inline-flex items-center gap-1 px-2 py-0.5 rounded bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-300 text-xs font-medium",children:[k(h),!i&&r.jsx("button",{type:"button",onClick:b=>m(h,b),className:"metakyc-multiselect-chip-remove",style:{background:"transparent",border:"none",padding:"0 0 0 2px",margin:0,cursor:"pointer",fontSize:"14px",lineHeight:1,fontWeight:"bold",display:"inline-flex",alignItems:"center",boxShadow:"none",transform:"none",minWidth:0,width:"auto",height:"auto",letterSpacing:"normal",textTransform:"none"},children:"×"})]},h))}),r.jsx("span",{className:"metakyc-multiselect-arrow absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none text-xs",children:c?"▲":"▼"})]}),c&&r.jsxs("div",{className:"metakyc-multiselect-dropdown absolute z-50 w-full mt-1 rounded-lg shadow-lg",style:{background:"inherit",border:"1px solid #d1d5db"},children:[r.jsx("div",{className:"metakyc-multiselect-search-wrapper p-2",style:{borderBottom:"1px solid #e5e7eb"},children:r.jsx("input",{type:"text",value:u,onChange:h=>w(h.target.value),placeholder:"Search...",autoFocus:!0,onClick:h=>h.stopPropagation(),className:"metakyc-multiselect-search w-full px-2 py-1.5 text-sm rounded focus:outline-none focus:ring-1 focus:ring-blue-500",style:{border:"1px solid #d1d5db"}})}),r.jsx("ul",{className:"max-h-48 overflow-y-auto py-1",children:p.length===0?r.jsx("li",{className:"px-3 py-2 text-sm text-gray-500 dark:text-gray-400",children:"No results"}):p.map(h=>r.jsxs("li",{onClick:()=>y(h.value),className:Y("metakyc-multiselect-option","flex items-center gap-2 px-3 py-2 text-sm cursor-pointer","hover:bg-gray-50 dark:hover:bg-gray-700",t.includes(h.value)&&"metakyc-multiselect-option-selected bg-blue-50 dark:bg-blue-900/20"),children:[r.jsx("input",{type:"checkbox",checked:t.includes(h.value),readOnly:!0,className:"rounded border-gray-300 text-blue-600 pointer-events-none"}),r.jsx("span",{className:"text-gray-900 dark:text-gray-100",children:h.label})]},h.value))}),t.length>0&&r.jsx("div",{className:"metakyc-multiselect-clear p-2 border-t border-gray-100 dark:border-gray-700",children:r.jsxs("button",{type:"button",onClick:()=>{s([]),w("")},className:"text-xs text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300",children:["Clear all (",t.length," selected)"]})})]})]})]})},It=({label:e,error:t,accept:s,multiple:a=!1,maxSize:n,onChange:i,value:l=[],className:c})=>{const[d,u]=o.useState(!1),w=o.useRef(null),v=b=>{if(!b)return;const A=Array.from(b);if(n&&A.filter(C=>C.size>n).length>0){const C=ve(n);alert(`Some files exceed the maximum size of ${C}`);return}i==null||i(a?[...l,...A]:[A[0]])},p=b=>{b.preventDefault(),u(!0)},y=()=>{u(!1)},m=b=>{b.preventDefault(),u(!1),v(b.dataTransfer.files)},k=()=>{var b;(b=w.current)==null||b.click()},h=b=>{const A=l.filter((j,C)=>C!==b);i==null||i(A)};return r.jsxs("div",{className:Y("w-full",c),children:[e&&r.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e}),r.jsxs("div",{className:Y("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",t&&"border-danger-500"),onDragOver:p,onDragLeave:y,onDrop:m,onClick:k,children:[r.jsx("input",{ref:w,type:"file",className:"hidden",accept:s,multiple:a,onChange:b=>v(b.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"]}),n&&r.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum file size: ",ve(n)]})]})]}),l.length>0&&r.jsx("div",{className:"mt-3 space-y-2",children:l.map((b,A)=>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:b.name}),r.jsxs("span",{className:"text-xs text-gray-500",children:["(",ve(b.size),")"]})]}),r.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),h(A)},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"})})})]},A))}),t&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:t})]})},Dt=o.forwardRef(({countryCode:e="+1",onCountryCodeChange:t,className:s,...a},n)=>r.jsxs("div",{className:"w-full",children:[a.label&&r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[a.label,a.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:e,onChange:i=>t==null?void 0:t(i.target.value),className:Y("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(X,{ref:n,type:"tel",className:Y("flex-1",s),...a,label:""})]}),a.error&&r.jsx("p",{className:"mt-1 text-sm text-danger-500",children:a.error})]}));Dt.displayName="PhoneInput";/**
2
2
  * @license lucide-react v0.574.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -48,7 +48,7 @@
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const dr=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Tt=Pt("chevron-right",dr);function ur(e,t){const s=!t||t.length===0||t.every(a=>!a||!a.trim());if(e.isRequired&&s)return e.errorMessage||"This field is required";if(!s){const a=t[0]??"";if(a&&e.regex)try{if(!new RegExp(e.regex).test(a))return e.errorMessage||"Invalid format"}catch{}if(a!==""){const n=Number(a);if(!isNaN(n)&&a.trim()!==""){if(e.min!==void 0&&e.min!==null&&n<e.min)return`Minimum value is ${e.min}`;if(e.max!==void 0&&e.max!==null&&n>e.max)return`Maximum value is ${e.max}`}else{if(e.min!==void 0&&e.min!==null&&a.length<e.min)return`Minimum length is ${e.min} characters`;if(e.max!==void 0&&e.max!==null&&a.length>e.max)return`Maximum length is ${e.max} characters`}}}return null}function mr(e){const t=e.flatMap((a,n)=>(a.questions??[]).map((i,l)=>({question:i,groupIndex:n,qIdx:l}))),s=new Map;for(const a of t){const n=a.question.pageNumber??1;s.has(n)||s.set(n,[]),s.get(n).push(a)}return Array.from(s.entries()).sort(([a],[n])=>a-n).map(([,a])=>a)}const Mt=({applicantId:e,onComplete:t,onBack:s})=>{const{questionnaire:a,isLoading:n,isSubmitting:i,error:l,submit:c}=kt(e),[d,u]=o.useState({}),[w,v]=o.useState({}),[p,y]=o.useState(0),m=o.useMemo(()=>a?mr(a.questionGroups):[],[a]),j=p===m.length-1,h=m[p]??[],b=o.useCallback((R,O)=>{u(g=>({...g,[R]:O})),v(g=>{const L={...g};return delete L[R],L})},[]),A=o.useCallback(()=>{const R={};for(const{question:O}of h){const g=ur(O,d[O.id]??[]);g&&(R[O.id]=g)}return v(O=>({...O,...R})),Object.keys(R).length===0},[h,d]),k=()=>{A()&&y(R=>R+1)},C=()=>{p>0?y(R=>R-1):s==null||s()},H=async()=>{if(!(!A()||!a))try{const R=a.questionGroups.flatMap(g=>(g.questions??[]).map(L=>({questionId:L.id,values:d[L.id]??[]}))),O={applicantId:e,questionnarieId:a.id,questionResults:R};await c(O),t==null||t()}catch(R){console.error("Questionnaire submit error:",R)}};return n?r.jsx(F,{children:r.jsx(P,{children:r.jsx(ae,{className:"my-8"})})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading questionnaire: ",l.message]})})}):a?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:a.displayName}),a.subtitle&&r.jsx("p",{className:"text-sm",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:a.subtitle}),m.length>1&&r.jsxs("div",{className:"flex items-center justify-between mt-3",children:[r.jsxs("span",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:["Page ",p+1," of ",m.length]}),r.jsx("div",{className:"flex items-center gap-1.5",children:m.map((R,O)=>r.jsx("div",{className:"rounded-full transition-all duration-200",style:{height:"6px",width:O===p?"20px":"6px",backgroundColor:O<=p?"var(--metakyc-primary, #2563eb)":"var(--metakyc-border, #e5e7eb)"}},O))})]})]}),r.jsx(P,{className:"space-y-6",children:h.map(({question:R})=>r.jsx(pr,{question:R,value:d[R.id]??[],error:w[R.id],onChange:O=>b(R.id,O)},R.id))}),r.jsxs(ee,{className:"flex items-center justify-between",children:[r.jsxs(z,{type:"button",variant:"outline",onClick:C,style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx(Lt,{size:14}),p>0?"Previous":"Back"]}),j?r.jsx(z,{type:"button",isLoading:i,onClick:H,children:"Continue"}):r.jsxs(z,{type:"button",onClick:k,style:{display:"flex",alignItems:"center",gap:"4px"},children:["Next",r.jsx(Tt,{size:14})]})]}),l&&r.jsx("div",{className:"mx-6 mb-4 p-3 bg-red-50 border border-red-200 rounded",children:r.jsx("p",{className:"text-red-600 text-sm",children:l.message})})]}):null},pr=({question:e,value:t,error:s,onChange:a})=>{var l;const i=(((l=e.defaultAnswers)==null?void 0:l.length)??0)>0?e.showAsDropdown?e.canMultipleAnswer?"multi-select":"single-select":e.canMultipleAnswer?"checkbox":"radio":"text";return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium",style:{color:"var(--metakyc-text-primary, #111827)"},children:[e.text,e.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),e.subtitle&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:e.subtitle}),e.description&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:e.description}),i==="text"&&r.jsx(X,{value:t[0]??"",onChange:c=>a([c.target.value]),placeholder:e.subtitle?void 0:"Enter your answer…",error:s,required:e.isRequired}),i==="single-select"&&r.jsx(le,{value:t[0]??"",onChange:c=>a([c.target.value]),options:(e.defaultAnswers??[]).map(c=>({value:c,label:c})),placeholder:"Select an option…",error:s,required:e.isRequired}),i==="radio"&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultAnswers??[]).map(c=>r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0},children:[r.jsx("input",{type:"radio",checked:t[0]===c,onChange:()=>a([c]),style:{width:"16px",height:"16px",flexShrink:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0}}),r.jsx("span",{style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4"},children:c})]},c)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),(i==="checkbox"||i==="multi-select")&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultAnswers??[]).map(c=>r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0},children:[r.jsx("input",{type:"checkbox",checked:t.includes(c),onChange:d=>{d.target.checked?a([...t,c]):a(t.filter(u=>u!==c))},style:{width:"16px",height:"16px",flexShrink:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0,borderRadius:"3px"}}),r.jsx("span",{style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4"},children:c})]},c)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),s&&i==="text"&&null]})},Ot=({applicantId:e,onComplete:t,onBack:s})=>{const{uploadDocument:a,isLoading:n,isSubmitting:i,error:l,submit:c}=St(e),[d,u]=o.useState({}),w=async v=>{if(v.preventDefault(),!a)return;const p=await Promise.all(a.uploadDocumentFiles.map(async m=>{const j=d[m.id]||[],h=await Promise.all(j.map(async b=>({fileName:b.name,fileData:await xt(b)})));return{uploadDocumentFileId:m.id,valueList:h}})),y={applicantId:e,uploadDocumentId:a.id,uploadDocumentResults:p};await c(y),t==null||t()};return n?r.jsx(F,{children:r.jsx(P,{children:r.jsx(ae,{className:"my-8"})})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading document requirements: ",l.message]})})}):a?r.jsx("form",{onSubmit:w,children:r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:a.displayName}),a.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:a.subtitle})]}),r.jsx(P,{className:"space-y-6",children:a.uploadDocumentFiles.map(v=>r.jsx(It,{label:v.displayName,accept:v.allowedTypes,multiple:v.multipleFile,maxSize:v.maxEachFileSizeByte,value:d[v.id]||[],onChange:p=>{u(y=>({...y,[v.id]:p}))}},v.id))}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"submit",isLoading:i,children:"Continue"})]})]})}):null},zt=({applicantId:e,onComplete:t,onBack:s})=>{const{overview:a,isLoading:n,isSubmitting:i,error:l,passOverview:c}=Nt(e),d=async()=>{await c(),t==null||t()};return n?r.jsx(F,{children:r.jsx(P,{children:r.jsx(ae,{className:"my-8"})})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading overview: ",l.message]})})}):a?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:a.title||"Overview"}),a.description&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:a.description})]}),r.jsx(P,{className:"space-y-8",children:a.steps&&a.steps.length>0?a.steps.sort((u,w)=>u.order-w.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(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{onClick:d,isLoading:i,children:"Continue"})]})]}):null};function hr(e,t){const s=!t||t.length===0||t.every(a=>!a||!a.trim());if(e.isRequired&&s)return e.errorMessage||`${e.displayName} is required`;if(!s){const a=t[0]??"";if(a&&e.regex)try{if(!new RegExp(e.regex).test(a))return e.errorMessage||"Invalid format"}catch{}const n=e.valueDataType===oe.Integer||e.valueDataType===oe.Decimal||e.valueDataType===oe.DigitOnly;if(n&&a.trim()!==""){const i=Number(a);if(!isNaN(i)){if(e.min!==void 0&&e.min!==null&&i<e.min)return`Minimum value is ${e.min}`;if(e.max!==void 0&&e.max!==null&&i>e.max)return`Maximum value is ${e.max}`}}else if(!n&&a!==""){if(e.min!==void 0&&e.min!==null&&a.length<e.min)return`Minimum length is ${e.min} characters`;if(e.max!==void 0&&e.max!==null&&a.length>e.max)return`Maximum length is ${e.max} characters`}}return null}function gr(e){const t=new Map;return e.forEach((s,a)=>{const n=s.pageNumber??1;t.has(n)||t.set(n,[]),t.get(n).push({criterion:s,idx:a})}),Array.from(t.entries()).sort(([s],[a])=>s-a).map(([,s])=>s)}function xr(e){return e.builtInType===1?"country":!e.defaultValues||e.defaultValues.length===0?"text":e.multipleValue?"checkbox":"radio"}const Bt=({applicantId:e,onComplete:t,onBack:s})=>{const{criteria:a,isLoading:n,isSubmitting:i,error:l,submit:c}=At(e),[d,u]=o.useState({}),[w,v]=o.useState({}),[p,y]=o.useState(0),[m,j]=o.useState(!1),h=o.useMemo(()=>a&&a.length>0?gr(a):[],[a]),b=p===h.length-1,A=h[p]??[];o.useEffect(()=>{!n&&a&&a.length===0&&!m&&!i&&(j(!0),c({applicantId:e,criteriaValueInputs:[]}).then(()=>t==null?void 0:t()).catch(console.error))},[n,a,m,i,c,e,t]);const k=o.useCallback((g,L)=>{u(I=>({...I,[g]:L})),v(I=>{const Q={...I};return delete Q[g],Q})},[]),C=o.useCallback(()=>{const g={};for(const{criterion:L}of A){const I=hr(L,d[L.id]??[]);I&&(g[L.id]=I)}return v(L=>({...L,...g})),Object.keys(g).length===0},[A,d]),H=()=>{C()&&y(g=>g+1)},R=()=>{p>0?y(g=>g-1):s==null||s()},O=async()=>{if(!(!C()||!a))try{const g=a.map(I=>{const Q=(d[I.id]??[]).filter(_=>_&&_.trim());return Q.length>0?{riskCriteriaId:I.id,values:Q}:null}).filter(I=>I!==null);await c({applicantId:e,criteriaValueInputs:g}),t==null||t()}catch(g){console.error("Risk scoring submit error:",g)}};return n?r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-sm mt-4",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:"Loading risk scoring criteria…"})]})}):!n&&a&&a.length===0?r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-sm mt-4",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:"No criteria required. Moving to next step…"})]})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading criteria: ",l.message]})})}):a?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:"Risk Assessment"}),r.jsx("p",{className:"text-sm",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:"Please answer the following questions for risk evaluation"}),h.length>1&&r.jsxs("div",{className:"flex items-center justify-between mt-3",children:[r.jsxs("span",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:["Page ",p+1," of ",h.length]}),r.jsx("div",{className:"flex items-center gap-1.5",children:h.map((g,L)=>r.jsx("div",{className:"rounded-full transition-all duration-200",style:{height:"6px",width:L===p?"20px":"6px",backgroundColor:L<=p?"var(--metakyc-primary, #2563eb)":"var(--metakyc-border, #e5e7eb)"}},L))})]})]}),r.jsx(P,{className:"space-y-6",children:A.map(({criterion:g})=>r.jsx(fr,{criterion:g,value:d[g.id]??[],error:w[g.id],onChange:L=>k(g.id,L)},g.id))}),r.jsxs(ee,{className:"flex items-center justify-between",children:[r.jsxs(z,{type:"button",variant:"outline",onClick:R,style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx(Lt,{size:14}),p>0?"Previous":"Back"]}),b?r.jsx(z,{type:"button",isLoading:i,onClick:O,children:"Continue"}):r.jsxs(z,{type:"button",onClick:H,style:{display:"flex",alignItems:"center",gap:"4px"},children:["Next",r.jsx(Tt,{size:14})]})]}),l&&r.jsx("div",{className:"mx-6 mb-4 p-3 bg-red-50 border border-red-200 rounded",children:r.jsx("p",{className:"text-red-600 text-sm",children:l.message})})]}):null},fr=({criterion:e,value:t,error:s,onChange:a})=>{const n=xr(e),i=e.valueDataType===oe.Integer||e.valueDataType===oe.Decimal||e.valueDataType===oe.DigitOnly;return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium",style:{color:"var(--metakyc-text-primary, #111827)"},children:[e.displayName,e.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),e.description&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:e.description}),i&&(e.min!==void 0||e.max!==void 0)&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:e.min!==void 0&&e.max!==void 0?`Range: ${e.min} – ${e.max}`:e.min!==void 0?`Minimum: ${e.min}`:`Maximum: ${e.max}`}),n==="text"&&r.jsx(X,{value:t[0]??"",onChange:l=>a([l.target.value]),type:i?"number":"text",placeholder:"Enter your answer…",error:s,required:e.isRequired,min:e.min,max:e.max,onKeyDown:l=>{e.valueDataType===oe.DigitOnly&&["e","E","+","-","."].includes(l.key)&&l.preventDefault()}}),n==="radio"&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultValues??[]).map(l=>r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0},children:[r.jsx("input",{type:"radio",checked:t[0]===l,onChange:()=>a([l]),style:{width:"16px",height:"16px",flexShrink:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0}}),r.jsx("span",{style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4"},children:l})]},l)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),n==="checkbox"&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultValues??[]).map(l=>r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0},children:[r.jsx("input",{type:"checkbox",checked:t.includes(l),onChange:c=>{c.target.checked?a([...t,l]):a(t.filter(d=>d!==l))},style:{width:"16px",height:"16px",flexShrink:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0,borderRadius:"3px"}}),r.jsx("span",{style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4"},children:l})]},l)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),n==="country"&&r.jsx(le,{value:t[0]??"",onChange:l=>a([l.target.value]),options:[{value:"US",label:"United States"},{value:"GB",label:"United Kingdom"},{value:"DE",label:"Germany"},{value:"FR",label:"France"},{value:"AE",label:"United Arab Emirates"}],placeholder:"Select a country…",error:s,required:e.isRequired})]})},Kt=({applicantId:e,onComplete:t,onBack:s})=>{const{investorCategorizationService:a}=te(),[n,i]=o.useState(null),[l,c]=o.useState(!1),[d,u]=o.useState(null),w=async v=>{if(v.preventDefault(),n===null){u("Please select an investor type");return}c(!0),u(null);try{const p={applicantId:e,investorType:n};console.log("Submitting investor categorization:",p);const y=await a.setInvestorCategorization(p);console.log("Investor categorization result:",y),t==null||t()}catch(p){console.error("Error submitting investor categorization:",p),u(p.message||"Failed to submit investor categorization")}finally{c(!1)}};return r.jsx("form",{onSubmit:w,children:r.jsxs(F,{children:[r.jsxs(G,{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(P,{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:`
51
+ */const dr=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Tt=Pt("chevron-right",dr);function ur(e,t){const s=!t||t.length===0||t.every(a=>!a||!a.trim());if(e.isRequired&&s)return e.errorMessage||"This field is required";if(!s){const a=t[0]??"";if(a&&e.regex)try{if(!new RegExp(e.regex).test(a))return e.errorMessage||"Invalid format"}catch{}if(a!==""){const n=Number(a);if(!isNaN(n)&&a.trim()!==""){if(e.min!==void 0&&e.min!==null&&n<e.min)return`Minimum value is ${e.min}`;if(e.max!==void 0&&e.max!==null&&n>e.max)return`Maximum value is ${e.max}`}else{if(e.min!==void 0&&e.min!==null&&a.length<e.min)return`Minimum length is ${e.min} characters`;if(e.max!==void 0&&e.max!==null&&a.length>e.max)return`Maximum length is ${e.max} characters`}}}return null}function mr(e){const t=e.flatMap((a,n)=>(a.questions??[]).map((i,l)=>({question:i,groupIndex:n,qIdx:l}))),s=new Map;for(const a of t){const n=a.question.pageNumber??1;s.has(n)||s.set(n,[]),s.get(n).push(a)}return Array.from(s.entries()).sort(([a],[n])=>a-n).map(([,a])=>a)}const Mt=({applicantId:e,onComplete:t,onBack:s})=>{const{questionnaire:a,isLoading:n,isSubmitting:i,error:l,submit:c}=jt(e),[d,u]=o.useState({}),[w,v]=o.useState({}),[p,y]=o.useState(0),m=o.useMemo(()=>a?mr(a.questionGroups):[],[a]),k=p===m.length-1,h=m[p]??[],b=o.useCallback((R,O)=>{u(g=>({...g,[R]:O})),v(g=>{const L={...g};return delete L[R],L})},[]),A=o.useCallback(()=>{const R={};for(const{question:O}of h){const g=ur(O,d[O.id]??[]);g&&(R[O.id]=g)}return v(O=>({...O,...R})),Object.keys(R).length===0},[h,d]),j=()=>{A()&&y(R=>R+1)},C=()=>{p>0?y(R=>R-1):s==null||s()},H=async()=>{if(!(!A()||!a))try{const R=a.questionGroups.flatMap(g=>(g.questions??[]).map(L=>({questionId:L.id,values:d[L.id]??[]}))),O={applicantId:e,questionnarieId:a.id,questionResults:R};await c(O),t==null||t()}catch(R){console.error("Questionnaire submit error:",R)}};return n?r.jsx(F,{children:r.jsx(P,{children:r.jsx(ae,{className:"my-8"})})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading questionnaire: ",l.message]})})}):a?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:a.displayName}),a.subtitle&&r.jsx("p",{className:"text-sm",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:a.subtitle}),m.length>1&&r.jsxs("div",{className:"flex items-center justify-between mt-3",children:[r.jsxs("span",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:["Page ",p+1," of ",m.length]}),r.jsx("div",{className:"flex items-center gap-1.5",children:m.map((R,O)=>r.jsx("div",{className:"rounded-full transition-all duration-200",style:{height:"6px",width:O===p?"20px":"6px",backgroundColor:O<=p?"var(--metakyc-primary, #2563eb)":"var(--metakyc-border, #e5e7eb)"}},O))})]})]}),r.jsx(P,{className:"space-y-6",children:h.map(({question:R})=>r.jsx(pr,{question:R,value:d[R.id]??[],error:w[R.id],onChange:O=>b(R.id,O)},R.id))}),r.jsxs(ee,{className:"flex items-center justify-between",children:[r.jsxs(z,{type:"button",variant:"outline",onClick:C,style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx(Lt,{size:14}),p>0?"Previous":"Back"]}),k?r.jsx(z,{type:"button",isLoading:i,onClick:H,children:"Continue"}):r.jsxs(z,{type:"button",onClick:j,style:{display:"flex",alignItems:"center",gap:"4px"},children:["Next",r.jsx(Tt,{size:14})]})]}),l&&r.jsx("div",{className:"mx-6 mb-4 p-3 bg-red-50 border border-red-200 rounded",children:r.jsx("p",{className:"text-red-600 text-sm",children:l.message})})]}):null},pr=({question:e,value:t,error:s,onChange:a})=>{var l;const i=(((l=e.defaultAnswers)==null?void 0:l.length)??0)>0?e.showAsDropdown?e.canMultipleAnswer?"multi-select":"single-select":e.canMultipleAnswer?"checkbox":"radio":"text";return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium",style:{color:"var(--metakyc-text-primary, #111827)"},children:[e.text,e.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),e.subtitle&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:e.subtitle}),e.description&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:e.description}),i==="text"&&r.jsx(X,{value:t[0]??"",onChange:c=>a([c.target.value]),placeholder:e.subtitle?void 0:"Enter your answer…",error:s,required:e.isRequired}),i==="single-select"&&r.jsx(le,{value:t[0]??"",onChange:c=>a([c.target.value]),options:(e.defaultAnswers??[]).map(c=>({value:c,label:c})),placeholder:"Select an option…",error:s,required:e.isRequired}),i==="radio"&&r.jsxs("div",{className:"metakyc-options-group",style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultAnswers??[]).map(c=>r.jsxs("label",{className:"metakyc-option-label",style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0,padding:0},children:[r.jsx("input",{type:"radio",checked:t[0]===c,onChange:()=>a([c]),className:"metakyc-option-input",style:{width:"16px",height:"16px",minWidth:"16px",flexShrink:0,flexGrow:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0,padding:0,display:"inline-block",verticalAlign:"middle"}}),r.jsx("span",{className:"metakyc-option-text",style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4",marginLeft:0},children:c})]},c)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),(i==="checkbox"||i==="multi-select")&&r.jsxs("div",{className:"metakyc-options-group",style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultAnswers??[]).map(c=>r.jsxs("label",{className:"metakyc-option-label",style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0,padding:0},children:[r.jsx("input",{type:"checkbox",checked:t.includes(c),onChange:d=>{d.target.checked?a([...t,c]):a(t.filter(u=>u!==c))},className:"metakyc-option-input",style:{width:"16px",height:"16px",minWidth:"16px",flexShrink:0,flexGrow:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0,padding:0,display:"inline-block",verticalAlign:"middle"}}),r.jsx("span",{className:"metakyc-option-text",style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4",marginLeft:0},children:c})]},c)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),s&&i==="text"&&null]})},Ot=({applicantId:e,onComplete:t,onBack:s})=>{const{uploadDocument:a,isLoading:n,isSubmitting:i,error:l,submit:c}=St(e),[d,u]=o.useState({}),w=async v=>{if(v.preventDefault(),!a)return;const p=await Promise.all(a.uploadDocumentFiles.map(async m=>{const k=d[m.id]||[],h=await Promise.all(k.map(async b=>({fileName:b.name,fileData:await xt(b)})));return{uploadDocumentFileId:m.id,valueList:h}})),y={applicantId:e,uploadDocumentId:a.id,uploadDocumentResults:p};await c(y),t==null||t()};return n?r.jsx(F,{children:r.jsx(P,{children:r.jsx(ae,{className:"my-8"})})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading document requirements: ",l.message]})})}):a?r.jsx("form",{onSubmit:w,children:r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:a.displayName}),a.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:a.subtitle})]}),r.jsx(P,{className:"space-y-6",children:a.uploadDocumentFiles.map(v=>r.jsx(It,{label:v.displayName,accept:v.allowedTypes,multiple:v.multipleFile,maxSize:v.maxEachFileSizeByte,value:d[v.id]||[],onChange:p=>{u(y=>({...y,[v.id]:p}))}},v.id))}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"submit",isLoading:i,children:"Continue"})]})]})}):null},zt=({applicantId:e,onComplete:t,onBack:s})=>{const{overview:a,isLoading:n,isSubmitting:i,error:l,passOverview:c}=Nt(e),d=async()=>{await c(),t==null||t()};return n?r.jsx(F,{children:r.jsx(P,{children:r.jsx(ae,{className:"my-8"})})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading overview: ",l.message]})})}):a?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:a.title||"Overview"}),a.description&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:a.description})]}),r.jsx(P,{className:"space-y-8",children:a.steps&&a.steps.length>0?a.steps.sort((u,w)=>u.order-w.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(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{onClick:d,isLoading:i,children:"Continue"})]})]}):null};function hr(e,t){const s=!t||t.length===0||t.every(a=>!a||!a.trim());if(e.isRequired&&s)return e.errorMessage||`${e.displayName} is required`;if(!s){const a=t[0]??"";if(a&&e.regex)try{if(!new RegExp(e.regex).test(a))return e.errorMessage||"Invalid format"}catch{}const n=e.valueDataType===oe.Integer||e.valueDataType===oe.Decimal||e.valueDataType===oe.DigitOnly;if(n&&a.trim()!==""){const i=Number(a);if(!isNaN(i)){if(e.min!==void 0&&e.min!==null&&i<e.min)return`Minimum value is ${e.min}`;if(e.max!==void 0&&e.max!==null&&i>e.max)return`Maximum value is ${e.max}`}}else if(!n&&a!==""){if(e.min!==void 0&&e.min!==null&&a.length<e.min)return`Minimum length is ${e.min} characters`;if(e.max!==void 0&&e.max!==null&&a.length>e.max)return`Maximum length is ${e.max} characters`}}return null}function gr(e){const t=new Map;return e.forEach((s,a)=>{const n=s.pageNumber??1;t.has(n)||t.set(n,[]),t.get(n).push({criterion:s,idx:a})}),Array.from(t.entries()).sort(([s],[a])=>s-a).map(([,s])=>s)}function xr(e){return e.builtInType===1?"country":!e.defaultValues||e.defaultValues.length===0?"text":e.multipleValue?"checkbox":"radio"}const Bt=({applicantId:e,onComplete:t,onBack:s})=>{const{criteria:a,isLoading:n,isSubmitting:i,error:l,submit:c}=At(e),[d,u]=o.useState({}),[w,v]=o.useState({}),[p,y]=o.useState(0),[m,k]=o.useState(!1),h=o.useMemo(()=>a&&a.length>0?gr(a):[],[a]),b=p===h.length-1,A=h[p]??[];o.useEffect(()=>{!n&&a&&a.length===0&&!m&&!i&&(k(!0),c({applicantId:e,criteriaValueInputs:[]}).then(()=>t==null?void 0:t()).catch(console.error))},[n,a,m,i,c,e,t]);const j=o.useCallback((g,L)=>{u(I=>({...I,[g]:L})),v(I=>{const Q={...I};return delete Q[g],Q})},[]),C=o.useCallback(()=>{const g={};for(const{criterion:L}of A){const I=hr(L,d[L.id]??[]);I&&(g[L.id]=I)}return v(L=>({...L,...g})),Object.keys(g).length===0},[A,d]),H=()=>{C()&&y(g=>g+1)},R=()=>{p>0?y(g=>g-1):s==null||s()},O=async()=>{if(!(!C()||!a))try{const g=a.map(I=>{const Q=(d[I.id]??[]).filter(_=>_&&_.trim());return Q.length>0?{riskCriteriaId:I.id,values:Q}:null}).filter(I=>I!==null);await c({applicantId:e,criteriaValueInputs:g}),t==null||t()}catch(g){console.error("Risk scoring submit error:",g)}};return n?r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-sm mt-4",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:"Loading risk scoring criteria…"})]})}):!n&&a&&a.length===0?r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-sm mt-4",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:"No criteria required. Moving to next step…"})]})}):l?r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error loading criteria: ",l.message]})})}):a?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold",children:"Risk Assessment"}),r.jsx("p",{className:"text-sm",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:"Please answer the following questions for risk evaluation"}),h.length>1&&r.jsxs("div",{className:"flex items-center justify-between mt-3",children:[r.jsxs("span",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:["Page ",p+1," of ",h.length]}),r.jsx("div",{className:"flex items-center gap-1.5",children:h.map((g,L)=>r.jsx("div",{className:"rounded-full transition-all duration-200",style:{height:"6px",width:L===p?"20px":"6px",backgroundColor:L<=p?"var(--metakyc-primary, #2563eb)":"var(--metakyc-border, #e5e7eb)"}},L))})]})]}),r.jsx(P,{className:"space-y-6",children:A.map(({criterion:g})=>r.jsx(fr,{criterion:g,value:d[g.id]??[],error:w[g.id],onChange:L=>j(g.id,L)},g.id))}),r.jsxs(ee,{className:"flex items-center justify-between",children:[r.jsxs(z,{type:"button",variant:"outline",onClick:R,style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx(Lt,{size:14}),p>0?"Previous":"Back"]}),b?r.jsx(z,{type:"button",isLoading:i,onClick:O,children:"Continue"}):r.jsxs(z,{type:"button",onClick:H,style:{display:"flex",alignItems:"center",gap:"4px"},children:["Next",r.jsx(Tt,{size:14})]})]}),l&&r.jsx("div",{className:"mx-6 mb-4 p-3 bg-red-50 border border-red-200 rounded",children:r.jsx("p",{className:"text-red-600 text-sm",children:l.message})})]}):null},fr=({criterion:e,value:t,error:s,onChange:a})=>{const n=xr(e),i=e.valueDataType===oe.Integer||e.valueDataType===oe.Decimal||e.valueDataType===oe.DigitOnly;return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"block text-sm font-medium",style:{color:"var(--metakyc-text-primary, #111827)"},children:[e.displayName,e.isRequired&&r.jsx("span",{className:"text-danger-500 ml-1",children:"*"})]}),e.description&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-secondary, #6b7280)"},children:e.description}),i&&(e.min!==void 0||e.max!==void 0)&&r.jsx("p",{className:"text-xs",style:{color:"var(--metakyc-text-muted, #9ca3af)"},children:e.min!==void 0&&e.max!==void 0?`Range: ${e.min} – ${e.max}`:e.min!==void 0?`Minimum: ${e.min}`:`Maximum: ${e.max}`}),n==="text"&&r.jsx(X,{value:t[0]??"",onChange:l=>a([l.target.value]),type:i?"number":"text",placeholder:"Enter your answer…",error:s,required:e.isRequired,min:e.min,max:e.max,onKeyDown:l=>{e.valueDataType===oe.DigitOnly&&["e","E","+","-","."].includes(l.key)&&l.preventDefault()}}),n==="radio"&&r.jsxs("div",{className:"metakyc-options-group",style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultValues??[]).map(l=>r.jsxs("label",{className:"metakyc-option-label",style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0,padding:0},children:[r.jsx("input",{type:"radio",checked:t[0]===l,onChange:()=>a([l]),className:"metakyc-option-input",style:{width:"16px",height:"16px",minWidth:"16px",flexShrink:0,flexGrow:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0,padding:0,display:"inline-block",verticalAlign:"middle"}}),r.jsx("span",{className:"metakyc-option-text",style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4",marginLeft:0},children:l})]},l)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),n==="checkbox"&&r.jsxs("div",{className:"metakyc-options-group",style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(e.defaultValues??[]).map(l=>r.jsxs("label",{className:"metakyc-option-label",style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",margin:0,padding:0},children:[r.jsx("input",{type:"checkbox",checked:t.includes(l),onChange:c=>{c.target.checked?a([...t,l]):a(t.filter(d=>d!==l))},className:"metakyc-option-input",style:{width:"16px",height:"16px",minWidth:"16px",flexShrink:0,flexGrow:0,accentColor:"var(--metakyc-primary, #2563eb)",cursor:"pointer",margin:0,padding:0,display:"inline-block",verticalAlign:"middle"}}),r.jsx("span",{className:"metakyc-option-text",style:{fontSize:"14px",color:"var(--metakyc-text-primary, #111827)",lineHeight:"1.4",marginLeft:0},children:l})]},l)),s&&r.jsx("p",{className:"text-sm text-danger-500",children:s})]}),n==="country"&&r.jsx(le,{value:t[0]??"",onChange:l=>a([l.target.value]),options:[{value:"US",label:"United States"},{value:"GB",label:"United Kingdom"},{value:"DE",label:"Germany"},{value:"FR",label:"France"},{value:"AE",label:"United Arab Emirates"}],placeholder:"Select a country…",error:s,required:e.isRequired})]})},Kt=({applicantId:e,onComplete:t,onBack:s})=>{const{investorCategorizationService:a}=te(),[n,i]=o.useState(null),[l,c]=o.useState(!1),[d,u]=o.useState(null),w=async v=>{if(v.preventDefault(),n===null){u("Please select an investor type");return}c(!0),u(null);try{const p={applicantId:e,investorType:n};console.log("Submitting investor categorization:",p);const y=await a.setInvestorCategorization(p);console.log("Investor categorization result:",y),t==null||t()}catch(p){console.error("Error submitting investor categorization:",p),u(p.message||"Failed to submit investor categorization")}finally{c(!1)}};return r.jsx("form",{onSubmit:w,children:r.jsxs(F,{children:[r.jsxs(G,{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(P,{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:`
52
52
  block p-4 border-2 rounded-lg cursor-pointer transition-all
53
53
  ${n===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"}
54
54
  `,children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("input",{type:"radio",name:"investorType",value:J.Individual,checked:n===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:`
@@ -57,13 +57,13 @@
57
57
  `,children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("input",{type:"radio",name:"investorType",value:J.Sophisticated,checked:n===J.Sophisticated,onChange:()=>i(J.Sophisticated),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:"Sophisticated investor"}),r.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:"In the last 2 years, I have done one or more of the following:"}),r.jsxs("ul",{className:"text-sm text-gray-600 dark:text-gray-400 mt-2 space-y-1 list-none",children:[r.jsx("li",{children:"Worked in private equity or provided capital to small and medium enterprises, and/or"}),r.jsx("li",{children:"Been the director of a company with an annual turnover of at least (USD) $2m million, and/or"}),r.jsx("li",{children:"Invested directly in at least 2 private (not listed) companies."})]})]})]})}),r.jsx("label",{className:`
58
58
  block p-4 border-2 rounded-lg cursor-pointer transition-all
59
59
  ${n===J.HighNetWorth?"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"}
60
- `,children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("input",{type:"radio",name:"investorType",value:J.HighNetWorth,checked:n===J.HighNetWorth,onChange:()=>i(J.HighNetWorth),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:"High networth investor"}),r.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:["I earn more than (USD/EUR) $150,000 per year, and/or",r.jsx("br",{}),"I have net assets (excluding my main property) of at least $/EUR 300,000"]})]})]})}),d&&r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Error:"})," ",d]})})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"submit",isLoading:l,disabled:n===null,children:"Submit"})]})]})})},Ut=({applicantId:e,onComplete:t,onBack:s})=>{const{appropriatenessTestService:a}=te(),[n,i]=o.useState(null),[l,c]=o.useState(!0),[d,u]=o.useState(!1),[w,v]=o.useState(null),[p,y]=o.useState({}),[m,j]=o.useState(0),[h,b]=o.useState(!1),[A,k]=o.useState(!1),[C,H]=o.useState(0);o.useEffect(()=>{(async()=>{try{c(!0),v(null),console.log("Loading appropriateness test for applicant:",e);const S=await a.getAppropriatenessTest(e);if(console.log("Appropriateness test data:",S),i(S),S.waitTimeSpanForNextTry&&S.waitTimeSpanForNextTry!=="00:00:00"){const $=R(S.waitTimeSpanForNextTry);$>0&&H($)}}catch(S){console.error("Error loading appropriateness test:",S),v(S.message||"Failed to load appropriateness test")}finally{c(!1)}})()},[e,a]);const R=E=>{const S=E.split(":").map(Number);if(S.length===3){const[$,f,D]=S;return $*3600+f*60+D}return 0},O=E=>{const S=Math.floor(E/60),$=E%60;return`${S.toString().padStart(2,"0")}:${$.toString().padStart(2,"0")}`};o.useEffect(()=>{if(!h||m<=0)return;const E=setInterval(()=>{j(S=>S<=1?(k(!0),0):S-1)},1e3);return()=>clearInterval(E)},[h,m]),o.useEffect(()=>{if(C<=0)return;const E=setInterval(()=>{H(S=>S<=1?0:S-1)},1e3);return()=>clearInterval(E)},[C]),o.useEffect(()=>{A&&!d&&I()},[A]);const g=()=>{n&&(b(!0),j(n.testDurationSec))},L=(E,S)=>{y($=>({...$,[E]:S}))},I=async E=>{if(E&&E.preventDefault(),!!n){if(!A){const S=n.appropriatenessQuestions.length-Object.keys(p).length;if(S>0){v(`Please answer all questions. ${S} question(s) remaining.`);return}}u(!0),v(null);try{const S=n.appropriatenessQuestions.map(f=>({appropriatenessQuestionId:f.id,value:p[f.id]||""})),$={applicantId:e,appropriatenessTestId:n.id,appropriatenessQuestionResults:S};console.log("Submitting appropriateness test:",$);try{const f=await a.fillAppropriatenessTest($);console.log("Appropriateness test result:",f),f.message&&(f.message.toLowerCase().includes("pass")||f.message.toLowerCase().includes("success")||f.message.toLowerCase().includes("congratulations"))?t==null||t():(v(f.message||"Test completed. Please check the result."),b(!1),k(!1),y({}),setTimeout(()=>Q(),1e3))}catch(f){if(f.code===400&&f.message){const D=f.message;console.log("Test failed:",D),v(D),b(!1),k(!1),y({}),setTimeout(()=>Q(),1500)}else throw f}}catch(S){console.error("Error submitting appropriateness test:",S),v(S.message||"Failed to submit test. Please try again."),b(!1),k(!1),y({})}finally{u(!1)}}},Q=async()=>{try{const E=await a.getAppropriatenessTest(e);if(console.log("Reloaded test data:",E),i(E),E.waitTimeSpanForNextTry&&E.waitTimeSpanForNextTry!=="00:00:00"){const S=R(E.waitTimeSpanForNextTry);S>0&&H(S)}}catch(E){console.error("Error reloading test data:",E),v(S=>S+`
60
+ `,children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("input",{type:"radio",name:"investorType",value:J.HighNetWorth,checked:n===J.HighNetWorth,onChange:()=>i(J.HighNetWorth),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:"High networth investor"}),r.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:["I earn more than (USD/EUR) $150,000 per year, and/or",r.jsx("br",{}),"I have net assets (excluding my main property) of at least $/EUR 300,000"]})]})]})}),d&&r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Error:"})," ",d]})})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"submit",isLoading:l,disabled:n===null,children:"Submit"})]})]})})},Ut=({applicantId:e,onComplete:t,onBack:s})=>{const{appropriatenessTestService:a}=te(),[n,i]=o.useState(null),[l,c]=o.useState(!0),[d,u]=o.useState(!1),[w,v]=o.useState(null),[p,y]=o.useState({}),[m,k]=o.useState(0),[h,b]=o.useState(!1),[A,j]=o.useState(!1),[C,H]=o.useState(0);o.useEffect(()=>{(async()=>{try{c(!0),v(null),console.log("Loading appropriateness test for applicant:",e);const S=await a.getAppropriatenessTest(e);if(console.log("Appropriateness test data:",S),i(S),S.waitTimeSpanForNextTry&&S.waitTimeSpanForNextTry!=="00:00:00"){const $=R(S.waitTimeSpanForNextTry);$>0&&H($)}}catch(S){console.error("Error loading appropriateness test:",S),v(S.message||"Failed to load appropriateness test")}finally{c(!1)}})()},[e,a]);const R=E=>{const S=E.split(":").map(Number);if(S.length===3){const[$,f,D]=S;return $*3600+f*60+D}return 0},O=E=>{const S=Math.floor(E/60),$=E%60;return`${S.toString().padStart(2,"0")}:${$.toString().padStart(2,"0")}`};o.useEffect(()=>{if(!h||m<=0)return;const E=setInterval(()=>{k(S=>S<=1?(j(!0),0):S-1)},1e3);return()=>clearInterval(E)},[h,m]),o.useEffect(()=>{if(C<=0)return;const E=setInterval(()=>{H(S=>S<=1?0:S-1)},1e3);return()=>clearInterval(E)},[C]),o.useEffect(()=>{A&&!d&&I()},[A]);const g=()=>{n&&(b(!0),k(n.testDurationSec))},L=(E,S)=>{y($=>({...$,[E]:S}))},I=async E=>{if(E&&E.preventDefault(),!!n){if(!A){const S=n.appropriatenessQuestions.length-Object.keys(p).length;if(S>0){v(`Please answer all questions. ${S} question(s) remaining.`);return}}u(!0),v(null);try{const S=n.appropriatenessQuestions.map(f=>({appropriatenessQuestionId:f.id,value:p[f.id]||""})),$={applicantId:e,appropriatenessTestId:n.id,appropriatenessQuestionResults:S};console.log("Submitting appropriateness test:",$);try{const f=await a.fillAppropriatenessTest($);console.log("Appropriateness test result:",f),f.message&&(f.message.toLowerCase().includes("pass")||f.message.toLowerCase().includes("success")||f.message.toLowerCase().includes("congratulations"))?t==null||t():(v(f.message||"Test completed. Please check the result."),b(!1),j(!1),y({}),setTimeout(()=>Q(),1e3))}catch(f){if(f.code===400&&f.message){const D=f.message;console.log("Test failed:",D),v(D),b(!1),j(!1),y({}),setTimeout(()=>Q(),1500)}else throw f}}catch(S){console.error("Error submitting appropriateness test:",S),v(S.message||"Failed to submit test. Please try again."),b(!1),j(!1),y({})}finally{u(!1)}}},Q=async()=>{try{const E=await a.getAppropriatenessTest(e);if(console.log("Reloaded test data:",E),i(E),E.waitTimeSpanForNextTry&&E.waitTimeSpanForNextTry!=="00:00:00"){const S=R(E.waitTimeSpanForNextTry);S>0&&H(S)}}catch(E){console.error("Error reloading test data:",E),v(S=>S+`
61
61
 
62
62
  Failed to reload test data. Please refresh the page.`)}};if(l)return r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading appropriateness test..."})]})});if(!n)return r.jsx(F,{children:r.jsxs(P,{className:"py-12 text-center",children:[r.jsx("p",{className:"text-danger-500 text-lg mb-4",children:"No test data available"}),w&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:w})]})});if(C>0)return r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold text-gray-900 dark:text-white",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:n.subtitle})]}),r.jsxs(P,{className:"py-12 text-center",children:[r.jsxs("div",{className:"mb-6",children:[r.jsx("div",{className:"text-6xl font-bold text-primary-500 mb-2",children:O(C)}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Please wait before attempting the test again"})]}),w&&r.jsx("div",{className:"mt-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsx("p",{className:"text-red-600 dark:text-red-400 text-sm",children:w})})]})]});const _=n.testAllowedMaxTry-n.totalFailedTries;return h?r.jsx("form",{onSubmit:I,children:r.jsxs(F,{children:[r.jsx(G,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-bold text-gray-900 dark:text-white",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:n.subtitle})]}),r.jsxs("div",{className:"text-right",children:[r.jsx("div",{className:`text-3xl font-bold ${m<=60?"text-danger-500":"text-primary-500"}`,children:O(m)}),r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Time Remaining"})]})]})}),r.jsxs(P,{className:"space-y-6",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs(ie,{variant:"info",children:["Question ",Object.keys(p).length," of ",n.totalQuestionCount]}),r.jsxs(ie,{variant:_>1?"success":"warning",children:[_," attempt",_!==1?"s":""," remaining"]})]}),n.appropriatenessQuestions.map((E,S)=>r.jsxs("div",{className:"p-4 border border-gray-200 dark:border-gray-700 rounded-lg",children:[r.jsxs("div",{className:"mb-4",children:[r.jsxs("span",{className:"inline-block px-2 py-1 text-xs font-semibold text-primary-700 bg-primary-100 dark:text-primary-300 dark:bg-primary-900/30 rounded mb-2",children:["Question ",S+1]}),E.groupName&&r.jsx("span",{className:"ml-2 text-xs text-gray-500 dark:text-gray-400",children:E.groupName}),r.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mt-2",children:E.question})]}),r.jsx("div",{className:"space-y-2",children:E.answers.map(($,f)=>r.jsxs("label",{className:`
63
63
  flex items-center p-3 border-2 rounded-lg cursor-pointer transition-all
64
64
  ${p[E.id]===$?"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"}
65
- `,children:[r.jsx("input",{type:"radio",name:`question-${E.id}`,value:$,checked:p[E.id]===$,onChange:D=>L(E.id,D.target.value),className:"h-4 w-4 text-primary-500 border-gray-300 focus:ring-primary-500",disabled:d}),r.jsx("span",{className:"ml-3 text-gray-700 dark:text-gray-300",children:$})]},f))})]},E.id)),w&&!A&&r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Error:"})," ",w]})}),A&&r.jsx("div",{className:"p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:r.jsxs("p",{className:"text-yellow-700 dark:text-yellow-400 text-sm",children:[r.jsx("strong",{children:"Time's up!"})," Your answers are being submitted automatically."]})})]}),r.jsxs(ee,{className:"flex justify-between",children:[r.jsx(z,{type:"button",variant:"outline",onClick:s,disabled:d,children:"Cancel"}),r.jsx(z,{type:"submit",isLoading:d,disabled:Object.keys(p).length<n.totalQuestionCount,children:A?"Submitting...":"Submit Test"})]})]})}):r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold text-gray-900 dark:text-white",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:n.subtitle})]}),r.jsxs(P,{children:[n.description&&r.jsx("div",{className:"mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg",children:r.jsx("p",{className:"text-gray-700 dark:text-gray-300",children:n.description})}),r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Total Questions:"}),r.jsx(ie,{variant:"info",children:n.totalQuestionCount})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Time Limit:"}),r.jsx(ie,{variant:"info",children:O(n.testDurationSec)})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Correct Answers Required:"}),r.jsx(ie,{variant:"info",children:n.testCorrectAnswerPassLimit})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Attempts Remaining:"}),r.jsx(ie,{variant:_>1?"success":"warning",children:_})]})]}),w&&r.jsx("div",{className:"mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Previous Attempt:"})," ",w]})}),_<=0&&r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsx("p",{className:"text-red-600 dark:text-red-400",children:"You have used all your attempts. Please contact support for assistance."})})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"button",onClick:g,disabled:_<=0,children:"Start Test"})]})]})},_t=({applicantId:e,onComplete:t,onBack:s})=>{var $,f,D,B;const{applicantService:a,baseInformationService:n,config:i}=te(),{identityData:l,provider:c,token:d,isLoading:u,error:w,requestIdentity:v,restartIdentity:p}=Ct(e),[y,m]=o.useState(null),[j,h]=o.useState(null),[b,A]=o.useState([]),[k,C]=o.useState(!0),[H,R]=o.useState(!1),[O,g]=o.useState(null),[L,I]=o.useState(!1),Q=o.useRef(!1),_=ue.useForm({defaultValues:{street:"",streetNumber:"",city:"",zip:"",country:"",nationality:"",phonenumber:""}});o.useEffect(()=>{(async()=>{try{const[x,M]=await Promise.all([a.getApplicantData(e),n.getCountries("","en")]);h(x);const q=new Set,Z=M.filter(de=>{const je=de.abbreviation3||de.abbreviation;return!je||q.has(je)?!1:(q.add(je),!0)});A(Z);const K=x.applicantRequestData;if(_.reset({street:(K==null?void 0:K.street)||"",streetNumber:(K==null?void 0:K.streetNumber)||"",city:(K==null?void 0:K.city)||"",zip:(K==null?void 0:K.zip)||"",country:(K==null?void 0:K.country)||"",nationality:(K==null?void 0:K.nationality)||"",phonenumber:(K==null?void 0:K.phonenumber)||""}),x.kycRecords&&x.kycRecords.length>0&&x.kycRecords[0].providerTokenObject!==null&&!Q.current){console.log("[Identity] Found existing identity verification, auto-requesting..."),Q.current=!0;try{await v(),R(!0)}catch(de){console.error("[Identity] Auto-request failed:",de)}}}catch(x){console.error("Error loading applicant data:",x)}finally{C(!1)}})()},[e]),o.useEffect(()=>{l&&!H&&(console.log("[Identity] Identity data already loaded, showing provider"),R(!0))},[l,H]),o.useEffect(()=>{if(d){if(d.expiresAt){const N=new Date(d.expiresAt).getTime();if(Date.now()>=N){console.warn("[Identity] Token has expired (expiresAt)"),I(!0),g("Your verification session has expired. Please restart.");return}}if(d.url)try{const x=new URL(d.url).toString().toLowerCase();if(x.includes("expired")||x.includes("invalid")||x.includes("error")){console.warn("[Identity] Token URL indicates expiration"),I(!0),g("Your verification link has expired. Please restart.");return}}catch{console.error("[Identity] Invalid token URL")}if(d.status==="expired"||d.error==="expired"||d.expired===!0){console.warn("[Identity] Token object indicates expiration"),I(!0),g("Your verification session has expired. Please restart.");return}}},[d]),o.useEffect(()=>{if(c!==null&&d&&!y&&H&&!L){const N=c;if(d.url){console.log("[Identity] Loading provider URL for user verification:",d.url),g(null);try{if(new URL(d.url),N===re.SardinAI){console.log("[SardinAI] Initializing Risk SDK in background...");try{const x=he.parseProviderConfig(c,d,i);he.createProvider(c,x).initialize().then(()=>{console.log("[SardinAI] Risk SDK initialized successfully in background")}).catch(q=>{console.warn("[SardinAI] Risk SDK initialization failed (non-blocking):",q)})}catch(x){console.warn("[SardinAI] Risk SDK setup failed (non-blocking):",x)}}m({type:"url",url:d.url})}catch(x){console.error("[Identity] Invalid URL:",x),g("Invalid verification URL. Please restart."),I(!0)}return}if(N===re.SardinAI){console.log("[SardinAI] No URL provided - initializing Risk SDK only..."),g(null);try{const x=he.parseProviderConfig(c,d,i),M=he.createProvider(c,x);M.initialize().then(()=>{console.log("[SardinAI] Risk SDK initialized successfully"),m(M),setTimeout(()=>{t==null||t()},2e3)}).catch(q=>{var K;console.error("[SardinAI] Failed to initialize:",q);const Z=((K=q.message)==null?void 0:K.toLowerCase())||"";Z.includes("expired")||Z.includes("invalid")||Z.includes("401")||Z.includes("400")?(I(!0),g("Session expired or invalid. Please restart verification.")):g(`Failed to initialize: ${q.message}`)})}catch(x){console.error("[SardinAI] Error creating provider:",x),g(`Configuration error: ${x.message}`)}return}try{g(null);const x=he.parseProviderConfig(c,d,i),M=he.createProvider(c,x);N===re.Sumsub?(M.initialize("identity-container").catch(q=>{var Z;console.error("[Sumsub] Initialization error:",q),g(`Failed to initialize: ${q.message}`),(Z=q.message)!=null&&Z.toLowerCase().includes("expired")&&I(!0)}),M.onComplete&&M.onComplete(()=>{t==null||t()})):N===re.Onfido&&M.initialize("identity-container").catch(q=>{console.error("[Onfido] Initialization error:",q),g(`Failed to initialize: ${q.message}`)}),m(M)}catch(x){console.error("[Identity] Provider setup error:",x),g(`Setup error: ${x.message}`)}}return()=>{if(y&&y.destroy)try{y.destroy()}catch(N){console.error("[Identity] Error destroying provider:",N)}}},[c,d,y,H,t,L]);const E=async()=>{try{g(null),I(!1),await v(),R(!0)}catch(N){console.error("Error starting identity verification:",N)}},S=async()=>{try{g(null),I(!1),m(null),console.log("[Identity] Restarting verification..."),await p(),R(!0)}catch(N){console.error("Error restarting identity verification:",N),g(N.message||"Failed to restart verification")}};if(k||u)return r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading identity verification..."})]})});if(w)return r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error: ",w.message]})})});if(H&&(O||L))return r.jsxs(F,{children:[r.jsx(G,{children:r.jsx("h2",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:"Verification Session Issue"})}),r.jsxs(P,{children:[r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg mb-6",children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("svg",{className:"h-6 w-6 text-red-600 dark:text-red-400 mr-3 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"font-semibold text-red-900 dark:text-red-100 mb-1",children:L?"Session Expired":"Verification Error"}),r.jsx("p",{className:"text-red-800 dark:text-red-200 text-sm",children:O||"Your verification session has expired and needs to be restarted."})]})]})}),r.jsxs("div",{className:"bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4",children:[r.jsx("h3",{className:"font-semibold text-blue-900 dark:text-blue-100 mb-2",children:"What to do next:"}),r.jsxs("ul",{className:"text-blue-800 dark:text-blue-200 text-sm space-y-1 list-disc list-inside",children:[r.jsx("li",{children:'Click "Restart Verification" below to generate a new session'}),r.jsx("li",{children:"Complete the verification process without delays"}),r.jsx("li",{children:"If issues persist, contact support"})]})]})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"button",onClick:S,disabled:u,children:u?"Restarting...":"Restart Verification"})]})]});if(H&&l){const N=c;return d!=null&&d.url?r.jsxs(F,{children:[r.jsx(G,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Identity Verification"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please complete the identity verification process"})]}),r.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:u,children:"Restart"})]})}),r.jsxs(P,{children:[r.jsx("div",{className:"mb-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:r.jsxs("p",{className:"text-yellow-800 dark:text-yellow-200 text-sm",children:[r.jsx("strong",{children:"Important:"}),' If you see an "expired" or "invalid link" message below, click the "Restart" button above to generate a new verification session.']})}),r.jsx("div",{className:"w-full",style:{height:"600px"},children:r.jsx("iframe",{src:d.url,className:"w-full h-full border-0 rounded-lg",allow:"camera; microphone; geolocation",title:"Identity Verification",onLoad:x=>{var M,q,Z;console.log("[Identity] Iframe loaded");try{const K=x.target,we=K.contentDocument||((M=K.contentWindow)==null?void 0:M.document);if(we){const de=((Z=(q=we.body)==null?void 0:q.textContent)==null?void 0:Z.toLowerCase())||"";(de.includes("expired")||de.includes("invalid")||de.includes("error"))&&(console.warn("[Identity] Iframe shows expiration message"),I(!0),g("Your verification link has expired."))}}catch{console.log("[Identity] Cannot check iframe content (CORS)")}}})})]}),s&&r.jsx(ee,{children:r.jsx(z,{variant:"outline",onClick:s,children:"Back"})})]}):N===re.SardinAI?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Device Risk Assessment"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Analyzing device security and behavioral patterns..."})]}),r.jsx(P,{children:r.jsxs("div",{className:"text-center py-12",children:[r.jsx(ae,{className:"mb-4"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Please wait while we verify your device security"}),r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-500 mt-2",children:"This process is automatic and will complete in a few seconds"})]})})]}):r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Identity Verification"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please complete the identity verification process"})]}),r.jsx(P,{children:r.jsx("div",{id:"identity-container",className:"min-h-[400px]"})}),s&&r.jsx(ee,{children:r.jsx(z,{variant:"outline",onClick:s,children:"Back"})})]})}return r.jsx("form",{onSubmit:_.handleSubmit(E),children:r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Review Your Information"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please review and confirm your information before starting identity verification"})]}),r.jsxs(P,{className:"space-y-6",children:[r.jsxs("div",{className:"space-y-4 pb-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:"Name"}),r.jsxs("p",{className:"mt-1 text-base",children:[($=j==null?void 0:j.applicantRequestData)==null?void 0:$.firstName," ",(f=j==null?void 0:j.applicantRequestData)==null?void 0:f.lastName]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:"Email"}),r.jsx("p",{className:"mt-1 text-base",children:(D=j==null?void 0:j.applicantRequestData)==null?void 0:D.email})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:"Date of Birth"}),r.jsx("p",{className:"mt-1 text-base",children:((B=j==null?void 0:j.applicantRequestData)==null?void 0:B.dateOfBirth)||"Not provided"})]})]}),r.jsxs("div",{className:"space-y-4",children:[r.jsx("h3",{className:"text-lg font-semibold",children:"Address Information"}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsx(ue.Controller,{control:_.control,name:"country",render:({field:N})=>r.jsx(le,{...N,label:"Country",options:[{value:"",label:"Select country..."},...b.map(x=>({value:x.abbreviation3||x.abbreviation,label:x.name}))]})}),r.jsx(ue.Controller,{control:_.control,name:"nationality",render:({field:N})=>r.jsx(le,{...N,label:"Nationality",options:[{value:"",label:"Select nationality..."},...b.map(x=>({value:x.abbreviation3||x.abbreviation,label:x.name}))]})})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsx(ue.Controller,{control:_.control,name:"street",render:({field:N})=>r.jsx(X,{...N,label:"Street"})}),r.jsx(ue.Controller,{control:_.control,name:"streetNumber",render:({field:N})=>r.jsx(X,{...N,label:"Street Number"})})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsx(ue.Controller,{control:_.control,name:"city",render:({field:N})=>r.jsx(X,{...N,label:"City"})}),r.jsx(ue.Controller,{control:_.control,name:"zip",render:({field:N})=>r.jsx(X,{...N,label:"ZIP/Postal Code"})})]}),r.jsx(ue.Controller,{control:_.control,name:"phonenumber",render:({field:N})=>r.jsx(X,{...N,label:"Phone Number",type:"tel"})})]})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"submit",isLoading:u,children:"Confirm and Start Verification"})]})]})})},Ne=({kycStatus:e,reviewStatus:t,workflowResult:s,customMessage:a,onContinue:n,onContactSupport:i})=>{const c=e===me.Approved?{type:"success",title:"Verification Approved",icon:"✓",iconBg:"bg-green-100 dark:bg-green-900/30",iconColor:"text-green-600 dark:text-green-400",message:"Your identity verification has been successfully approved."}:e===me.Rejected?{type:"error",title:"Verification Rejected",icon:"✕",iconBg:"bg-red-100 dark:bg-red-900/30",iconColor:"text-red-600 dark:text-red-400",message:"Unfortunately, your identity verification was not approved."}:e===me.Pending||e===me.InProgress?{type:"pending",title:"Verification Pending",icon:"⏱",iconBg:"bg-blue-100 dark:bg-blue-900/30",iconColor:"text-blue-600 dark:text-blue-400",message:"Your identity verification is currently being processed."}:t===pe.Approved?{type:"success",title:"Application Approved",icon:"✓",iconBg:"bg-green-100 dark:bg-green-900/30",iconColor:"text-green-600 dark:text-green-400",message:"Your application has been approved."}:t===pe.Reject?{type:"error",title:"Application Rejected",icon:"✕",iconBg:"bg-red-100 dark:bg-red-900/30",iconColor:"text-red-600 dark:text-red-400",message:"Your application has been rejected."}:t===pe.UnderReview||t===pe.AdminReview?{type:"pending",title:"Under Review",icon:"📋",iconBg:"bg-yellow-100 dark:bg-yellow-900/30",iconColor:"text-yellow-700 dark:text-yellow-400",message:"Your application is currently under manual review."}:s===ye.Success?{type:"success",title:"Process Complete",icon:"✓",iconBg:"bg-green-100 dark:bg-green-900/30",iconColor:"text-green-600 dark:text-green-400",message:"Your verification process has been completed successfully."}:s===ye.Failed?{type:"error",title:"Process Failed",icon:"✕",iconBg:"bg-red-100 dark:bg-red-900/30",iconColor:"text-red-600 dark:text-red-400",message:"The verification process could not be completed."}:s===ye.AdminReview?{type:"pending",title:"Admin Review Required",icon:"📋",iconBg:"bg-yellow-100 dark:bg-yellow-900/30",iconColor:"text-yellow-700 dark:text-yellow-400",message:"Your application requires administrator review."}:{type:"pending",title:"Processing",icon:"⏱",iconBg:"bg-blue-100 dark:bg-blue-900/30",iconColor:"text-blue-600 dark:text-blue-400",message:"Your application is being reviewed."};return r.jsxs(F,{children:[r.jsxs(P,{className:"py-12",children:[r.jsx("div",{className:"flex justify-center mb-6",children:r.jsx("div",{className:`w-24 h-24 rounded-full flex items-center justify-center ${c.iconBg}`,children:r.jsx("span",{className:`text-5xl ${c.iconColor}`,children:c.icon})})}),r.jsx("h2",{className:"text-3xl font-bold text-center text-gray-900 dark:text-white mb-4",children:c.title}),r.jsx("div",{className:"flex justify-center mb-6",children:r.jsx(ie,{variant:c.type==="success"?"success":c.type==="error"?"danger":c.type==="pending"?"warning":"info",children:e!=null?me[e]:pe[t]})}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mb-6 max-w-md mx-auto",children:a||c.message}),c.type==="success"&&r.jsxs("div",{className:"bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 mb-6",children:[r.jsx("h3",{className:"font-semibold text-green-900 dark:text-green-100 mb-2",children:"What's Next?"}),r.jsxs("ul",{className:"text-sm text-green-800 dark:text-green-200 space-y-1",children:[r.jsx("li",{children:"✓ Your identity has been verified"}),r.jsx("li",{children:"✓ You can now proceed with your application"}),r.jsx("li",{children:"✓ All features are now accessible"})]})]}),c.type==="error"&&r.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6",children:[r.jsx("h3",{className:"font-semibold text-red-900 dark:text-red-100 mb-2",children:"What Can You Do?"}),r.jsxs("ul",{className:"text-sm text-red-800 dark:text-red-200 space-y-2",children:[r.jsx("li",{children:"• Review the requirements and ensure all information is correct"}),r.jsx("li",{children:"• Contact our support team for assistance"}),r.jsx("li",{children:"• You may be able to resubmit your application"})]})]}),c.type==="pending"&&r.jsxs("div",{className:"bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6",children:[r.jsx("h3",{className:"font-semibold text-blue-900 dark:text-blue-100 mb-2",children:"What Happens Next?"}),r.jsxs("ul",{className:"text-sm text-blue-800 dark:text-blue-200 space-y-2",children:[r.jsx("li",{children:"• Our team is reviewing your information"}),r.jsx("li",{children:"• You will be notified via email once the review is complete"}),r.jsx("li",{children:"• This typically takes 24-48 hours"}),r.jsx("li",{children:"• No action is required from you at this time"})]})]}),r.jsx("div",{className:"mt-6 pt-6 border-t border-gray-200 dark:border-gray-700",children:r.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"KYC Status:"}),r.jsx("div",{className:"font-medium text-gray-900 dark:text-white mt-1",children:e!=null?me[e]:"Not Available"})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"Review Status:"}),r.jsx("div",{className:"font-medium text-gray-900 dark:text-white mt-1",children:pe[t]})]})]})})]}),r.jsxs(ee,{className:"flex justify-center gap-4",children:[c.type==="success"&&n&&r.jsx(z,{onClick:n,size:"lg",children:"Continue"}),c.type==="error"&&r.jsxs(r.Fragment,{children:[i&&r.jsx(z,{variant:"outline",onClick:i,children:"Contact Support"}),n&&r.jsx(z,{onClick:n,children:"Try Again"})]}),c.type==="pending"&&r.jsx("div",{className:"text-center",children:r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Please check back later or wait for our email notification"})})]})]})},$t=({config:e,className:t=""})=>!(e!=null&&e.visible)||!(e!=null&&e.url)?null:r.jsx("div",{className:`metakyc-logo ${t}`,children:r.jsx("img",{src:e.url,alt:e.alt||"Company Logo",style:{width:e.width||"auto",height:e.height||"40px",maxWidth:"100%",objectFit:"contain"},onError:s=>{console.warn("[Logo] Failed to load logo:",e.url),s.target.style.display="none"}})}),Ee=({title:e,subtitle:t,className:s=""})=>{const{currentTheme:a}=te(),n=e||(a==null?void 0:a.title)||"",i=!!(a!=null&&a.logo&&a.logo.visible&&a.logo.url),l=!!n;return!i&&!l?null:r.jsxs("div",{className:`metakyc-header ${s}`,children:[r.jsxs("div",{className:"metakyc-header-title flex items-center text-xl font-bold text-gray-900 dark:text-white",children:[i&&r.jsx($t,{config:a.logo}),i&&l&&r.jsx("span",{className:"text-gray-400 dark:text-gray-500 mx-3",style:{fontSize:"1.5rem",fontWeight:300},children:"|"}),l&&r.jsx("span",{children:n})]}),t&&r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:t})]})},yr=({workflowKey:e,externalRefId:t,onSuccess:s,onCancel:a})=>{var E,S,$;const{config:n,baseInformationService:i,currentTheme:l}=te(),{createApplicant:c,isLoading:d}=Et(),[u,w]=o.useState([]),[v,p]=o.useState(!0),[y,m]=o.useState(!1),[j,h]=o.useState(null),b=o.useRef(!1),A=o.useRef(!1),k=e||((E=n.applicantForm)==null?void 0:E.workflowKey);if(!k)throw new Error("workflowKey is required. Provide it either as a prop to CreateApplicantForm or set it in config.applicantForm.workflowKey");const C=t||((S=n.applicantForm)==null?void 0:S.externalRefId)||"",H=["firstName","lastName","email","phonenumber","dateOfBirth"],R=o.useMemo(()=>{const f=new Set(H),D=l==null?void 0:l.applicantFormRequiredFields;if(D&&D.length>0)for(const B of D)f.add(B);return Array.from(f)},[l==null?void 0:l.applicantFormRequiredFields]),O=o.useMemo(()=>{var B;let f;(B=n.applicantForm)!=null&&B.visibleFields?f=n.applicantForm.visibleFields:l!=null&&l.applicantFormVisibleFields&&l.applicantFormVisibleFields.length>0?f=l.applicantFormVisibleFields:f=_e;const D=new Set(f);for(const N of H)D.add(N);return Array.from(D)},[($=n.applicantForm)==null?void 0:$.visibleFields,l==null?void 0:l.applicantFormVisibleFields]),[g,L]=o.useState({workflowKey:k,firstName:"",lastName:"",title:"",email:"",dateOfBirth:"",phonenumber:"",externalRefId:C,mobileCountryCode:"",street:"",streetNumber:"",zip:"",city:"",country:"",nationality:"",otherNationality:[],defaultLanguage:"EN",taxCountry:"",placeOfBirth:"",countryOfBirth:"",salutation:null,educationLevel:"",occupation:"",taxNumber:""});o.useEffect(()=>{(async()=>{if(b.current||A.current){console.log("[CreateApplicant] Countries already loading or loaded, skipping...");return}b.current=!0,p(!0);try{const D=await i.getCountries("",n.locale||"en"),B=new Set,N=D.map(x=>({value:x.abbreviation3||x.abbreviation,label:x.name})).filter(x=>!x.value||B.has(x.value)?!1:(B.add(x.value),!0));w(N),A.current=!0}catch(D){console.error("Failed to load countries:",D)}finally{p(!1),b.current=!1}})()},[]);const I=(f,D)=>{L(B=>({...B,[f]:D}))},Q=async f=>{var D;f.preventDefault(),m(!0),h(null);try{if(!g.externalRefId||g.externalRefId.trim()===""){h("External Reference ID is required. Please pass it via config.applicantForm.externalRefId."),m(!1);return}for(const x of R){const M=g[x];if(M==null||M===""||Array.isArray(M)&&M.length===0){const Z=((D=Se[x])==null?void 0:D.label)||x;h(`${Z} is required.`),m(!1);return}}const B={workflowKey:g.workflowKey,externalRefId:g.externalRefId.trim()};O.forEach(x=>{if(x==="externalRefId")return;const M=g[x];M!=null&&M!==""&&!(Array.isArray(M)&&M.length===0)&&(B[x]=M)}),console.log("Creating applicant with data:",B);const N=await c(B);console.log("Applicant created:",N),s(N.applicantId)}catch(B){console.error("Error creating applicant:",B),h(B.message||"Failed to create applicant")}finally{m(!1)}},_=f=>{var N;const D=Se[f],B=R.includes(f);switch(D.type){case"select":if(f==="country"||f==="nationality"||f==="taxCountry"||f==="countryOfBirth")return r.jsx(le,{label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),options:[{value:"",label:`Select ${D.label.toLowerCase()}...`},...u],disabled:v,required:B},f);if(f==="salutation")return r.jsx(le,{label:D.label,value:((N=g[f])==null?void 0:N.toString())||"",onChange:x=>I(f,x.target.value?Number(x.target.value):null),options:[{value:"",label:"Select salutation..."},{value:be.Male.toString(),label:"Male"},{value:be.Female.toString(),label:"Female"},{value:be.Other.toString(),label:"Other"}],required:B},f);if(f==="defaultLanguage"){const x=l!=null&&l.allowedLanguages&&l.allowedLanguages.length>0?ke.filter(M=>l.allowedLanguages.includes(M.value)):ke;return r.jsx(le,{label:D.label,value:g[f]||"",onChange:M=>I(f,M.target.value),options:[{value:"",label:"Select language..."},...x],required:B},f)}return null;case"multiselect":return f==="otherNationality"?r.jsx(Rt,{label:D.label,value:g[f]||[],onChange:x=>I(f,x),options:u,placeholder:"Select other nationalities...",disabled:v,required:B},f):null;case"date":return r.jsx(X,{type:"date",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f);case"email":return r.jsx(X,{type:"email",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f);case"tel":return r.jsx(X,{type:"tel",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f);case"text":default:return r.jsx(X,{type:"text",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f)}};return v?r.jsx("div",{className:"metakyc-sdk",children:r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading form..."})]})})}):r.jsx("div",{className:"metakyc-sdk",children:r.jsx("form",{onSubmit:Q,children:r.jsxs(F,{children:[r.jsx(G,{children:r.jsx(Ee,{title:"Create Applicant",subtitle:"Please fill in the required information to begin the KYC verification process."})}),r.jsxs(P,{children:[j&&r.jsx("div",{className:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Error:"})," ",j]})}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:O.map(f=>_(f))})]}),r.jsxs(ee,{className:"flex justify-between",children:[a&&r.jsx(z,{type:"button",variant:"outline",onClick:a,disabled:y||d,children:"Cancel"}),r.jsx(z,{type:"submit",isLoading:y||d,children:"Create Applicant"})]})]})})})},br=({applicantId:e,onComplete:t,onError:s,theme:a="light",className:n})=>{const{progress:i,currentStep:l,steps:c,workflowKey:d,nextWorkflowKey:u,hasWorkflowChanged:w,isLoading:v,error:p,moveBack:y,refreshProgress:m}=jt(e),[j,h]=o.useState(!1);if(o.useEffect(()=>{p&&s&&s(p)},[p,s]),o.useEffect(()=>{i!=null&&i.workflowResult&&t&&t(i.workflowResult)},[i==null?void 0:i.workflowResult,t]),o.useEffect(()=>{a==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},[a]),o.useEffect(()=>{w&&h(!1)},[w]),v||!i)return r.jsx("div",{className:n,children:r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading workflow..."})]})})});if(p)return r.jsx("div",{className:n,children:r.jsx(F,{children:r.jsx(P,{children:r.jsxs("div",{className:"text-center py-8",children:[r.jsx("p",{className:"text-danger-500 text-lg mb-4",children:"An error occurred"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:p.message})]})})})});if(w&&!j)return r.jsx("div",{className:`metakyc-sdk ${n||""}`,children:r.jsx(F,{children:r.jsx(P,{children:r.jsxs("div",{className:"text-center py-8",children:[r.jsx("div",{className:"mb-6",children:r.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900 mb-4",children:r.jsx("svg",{className:"w-8 h-8 text-blue-600 dark:text-blue-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})})}),r.jsx("h3",{className:"text-xl font-semibold text-gray-900 dark:text-white mb-2",children:"Workflow Transition"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mb-6",children:"Your application workflow has been updated based on your progress."}),r.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6 max-w-md mx-auto",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsxs("div",{className:"text-left",children:[r.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"Previous Workflow"}),r.jsx("p",{className:"font-medium text-gray-900 dark:text-white",children:d})]}),r.jsx("svg",{className:"w-6 h-6 text-gray-400 mx-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7l5 5m0 0l-5 5m5-5H6"})}),r.jsxs("div",{className:"text-right",children:[r.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"New Workflow"}),r.jsx("p",{className:"font-medium text-blue-600 dark:text-blue-400",children:u})]})]}),i.nextWorkflowName&&r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-2 text-xs",children:i.nextWorkflowName})]}),r.jsx("button",{onClick:()=>h(!0),className:"px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors",children:"Continue with New Workflow"})]})})})});if(i.status===se.Finished||i.status===se.OnHold)return r.jsx("div",{className:`metakyc-sdk ${n||""}`,children:r.jsx(Ne,{kycStatus:i.kycStatus,reviewStatus:i.reviewStatus,workflowResult:i.workflowResult,customMessage:i.customMessage,onContinue:t&&i.workflowResult?()=>t(i.workflowResult):void 0,onContactSupport:()=>{typeof window<"u"&&(window.location.href="mailto:support@example.com")}})});if(!l)return r.jsx("div",{className:`metakyc-sdk ${n||""}`,children:r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:i.status===se.IdentityPending?"Loading identity verification...":"Loading current step..."})]})})});const b=C=>{switch(C){case T.Overview:return"Overview";case T.Questionaries:return"Questionnaire";case T.UploadDocument:return"Documents";case T.IdentitySdk:return"Identity";case T.RiskScoring:return"Risk Assessment";case T.InvestorCategorization:return"Investor Categorization";case T.AppropriatenessTest:return"Appropriateness Test";case T.AdditionalData:return"Additional Data";case T.ManualReview:return"Review";default:return""}},A=()=>{const C=c.filter(g=>g.visibility!==!1),H=C.findIndex(g=>g.order===l.order),R=H>=0?H+1:1,O=C.length;return r.jsxs("div",{className:"mb-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsx(Ee,{}),r.jsxs(ie,{variant:i.status===1?"info":"success",children:["Step ",R," of ",O]})]}),r.jsx("div",{className:"flex items-center",children:C.map((g,L)=>{const I=L<H,Q=g.order===l.order;return r.jsxs(o.Fragment,{children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("div",{className:`
65
+ `,children:[r.jsx("input",{type:"radio",name:`question-${E.id}`,value:$,checked:p[E.id]===$,onChange:D=>L(E.id,D.target.value),className:"h-4 w-4 text-primary-500 border-gray-300 focus:ring-primary-500",disabled:d}),r.jsx("span",{className:"ml-3 text-gray-700 dark:text-gray-300",children:$})]},f))})]},E.id)),w&&!A&&r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Error:"})," ",w]})}),A&&r.jsx("div",{className:"p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:r.jsxs("p",{className:"text-yellow-700 dark:text-yellow-400 text-sm",children:[r.jsx("strong",{children:"Time's up!"})," Your answers are being submitted automatically."]})})]}),r.jsxs(ee,{className:"flex justify-between",children:[r.jsx(z,{type:"button",variant:"outline",onClick:s,disabled:d,children:"Cancel"}),r.jsx(z,{type:"submit",isLoading:d,disabled:Object.keys(p).length<n.totalQuestionCount,children:A?"Submitting...":"Submit Test"})]})]})}):r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-lg font-bold text-gray-900 dark:text-white",children:n.displayName}),n.subtitle&&r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:n.subtitle})]}),r.jsxs(P,{children:[n.description&&r.jsx("div",{className:"mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg",children:r.jsx("p",{className:"text-gray-700 dark:text-gray-300",children:n.description})}),r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Total Questions:"}),r.jsx(ie,{variant:"info",children:n.totalQuestionCount})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Time Limit:"}),r.jsx(ie,{variant:"info",children:O(n.testDurationSec)})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Correct Answers Required:"}),r.jsx(ie,{variant:"info",children:n.testCorrectAnswerPassLimit})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[r.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-medium",children:"Attempts Remaining:"}),r.jsx(ie,{variant:_>1?"success":"warning",children:_})]})]}),w&&r.jsx("div",{className:"mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Previous Attempt:"})," ",w]})}),_<=0&&r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsx("p",{className:"text-red-600 dark:text-red-400",children:"You have used all your attempts. Please contact support for assistance."})})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"button",onClick:g,disabled:_<=0,children:"Start Test"})]})]})},_t=({applicantId:e,onComplete:t,onBack:s})=>{var $,f,D,B;const{applicantService:a,baseInformationService:n,config:i}=te(),{identityData:l,provider:c,token:d,isLoading:u,error:w,requestIdentity:v,restartIdentity:p}=Ct(e),[y,m]=o.useState(null),[k,h]=o.useState(null),[b,A]=o.useState([]),[j,C]=o.useState(!0),[H,R]=o.useState(!1),[O,g]=o.useState(null),[L,I]=o.useState(!1),Q=o.useRef(!1),_=ue.useForm({defaultValues:{street:"",streetNumber:"",city:"",zip:"",country:"",nationality:"",phonenumber:""}});o.useEffect(()=>{(async()=>{try{const[x,M]=await Promise.all([a.getApplicantData(e),n.getCountries("","en")]);h(x);const q=new Set,Z=M.filter(de=>{const ke=de.abbreviation3||de.abbreviation;return!ke||q.has(ke)?!1:(q.add(ke),!0)});A(Z);const K=x.applicantRequestData;if(_.reset({street:(K==null?void 0:K.street)||"",streetNumber:(K==null?void 0:K.streetNumber)||"",city:(K==null?void 0:K.city)||"",zip:(K==null?void 0:K.zip)||"",country:(K==null?void 0:K.country)||"",nationality:(K==null?void 0:K.nationality)||"",phonenumber:(K==null?void 0:K.phonenumber)||""}),x.kycRecords&&x.kycRecords.length>0&&x.kycRecords[0].providerTokenObject!==null&&!Q.current){console.log("[Identity] Found existing identity verification, auto-requesting..."),Q.current=!0;try{await v(),R(!0)}catch(de){console.error("[Identity] Auto-request failed:",de)}}}catch(x){console.error("Error loading applicant data:",x)}finally{C(!1)}})()},[e]),o.useEffect(()=>{l&&!H&&(console.log("[Identity] Identity data already loaded, showing provider"),R(!0))},[l,H]),o.useEffect(()=>{if(d){if(d.expiresAt){const N=new Date(d.expiresAt).getTime();if(Date.now()>=N){console.warn("[Identity] Token has expired (expiresAt)"),I(!0),g("Your verification session has expired. Please restart.");return}}if(d.url)try{const x=new URL(d.url).toString().toLowerCase();if(x.includes("expired")||x.includes("invalid")||x.includes("error")){console.warn("[Identity] Token URL indicates expiration"),I(!0),g("Your verification link has expired. Please restart.");return}}catch{console.error("[Identity] Invalid token URL")}if(d.status==="expired"||d.error==="expired"||d.expired===!0){console.warn("[Identity] Token object indicates expiration"),I(!0),g("Your verification session has expired. Please restart.");return}}},[d]),o.useEffect(()=>{if(c!==null&&d&&!y&&H&&!L){const N=c;if(d.url){console.log("[Identity] Loading provider URL for user verification:",d.url),g(null);try{if(new URL(d.url),N===re.SardinAI){console.log("[SardinAI] Initializing Risk SDK in background...");try{const x=he.parseProviderConfig(c,d,i);he.createProvider(c,x).initialize().then(()=>{console.log("[SardinAI] Risk SDK initialized successfully in background")}).catch(q=>{console.warn("[SardinAI] Risk SDK initialization failed (non-blocking):",q)})}catch(x){console.warn("[SardinAI] Risk SDK setup failed (non-blocking):",x)}}m({type:"url",url:d.url})}catch(x){console.error("[Identity] Invalid URL:",x),g("Invalid verification URL. Please restart."),I(!0)}return}if(N===re.SardinAI){console.log("[SardinAI] No URL provided - initializing Risk SDK only..."),g(null);try{const x=he.parseProviderConfig(c,d,i),M=he.createProvider(c,x);M.initialize().then(()=>{console.log("[SardinAI] Risk SDK initialized successfully"),m(M),setTimeout(()=>{t==null||t()},2e3)}).catch(q=>{var K;console.error("[SardinAI] Failed to initialize:",q);const Z=((K=q.message)==null?void 0:K.toLowerCase())||"";Z.includes("expired")||Z.includes("invalid")||Z.includes("401")||Z.includes("400")?(I(!0),g("Session expired or invalid. Please restart verification.")):g(`Failed to initialize: ${q.message}`)})}catch(x){console.error("[SardinAI] Error creating provider:",x),g(`Configuration error: ${x.message}`)}return}try{g(null);const x=he.parseProviderConfig(c,d,i),M=he.createProvider(c,x);N===re.Sumsub?(M.initialize("identity-container").catch(q=>{var Z;console.error("[Sumsub] Initialization error:",q),g(`Failed to initialize: ${q.message}`),(Z=q.message)!=null&&Z.toLowerCase().includes("expired")&&I(!0)}),M.onComplete&&M.onComplete(()=>{t==null||t()})):N===re.Onfido&&M.initialize("identity-container").catch(q=>{console.error("[Onfido] Initialization error:",q),g(`Failed to initialize: ${q.message}`)}),m(M)}catch(x){console.error("[Identity] Provider setup error:",x),g(`Setup error: ${x.message}`)}}return()=>{if(y&&y.destroy)try{y.destroy()}catch(N){console.error("[Identity] Error destroying provider:",N)}}},[c,d,y,H,t,L]);const E=async()=>{try{g(null),I(!1),await v(),R(!0)}catch(N){console.error("Error starting identity verification:",N)}},S=async()=>{try{g(null),I(!1),m(null),console.log("[Identity] Restarting verification..."),await p(),R(!0)}catch(N){console.error("Error restarting identity verification:",N),g(N.message||"Failed to restart verification")}};if(j||u)return r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading identity verification..."})]})});if(w)return r.jsx(F,{children:r.jsx(P,{children:r.jsxs("p",{className:"text-danger-500",children:["Error: ",w.message]})})});if(H&&(O||L))return r.jsxs(F,{children:[r.jsx(G,{children:r.jsx("h2",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:"Verification Session Issue"})}),r.jsxs(P,{children:[r.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg mb-6",children:r.jsxs("div",{className:"flex items-start",children:[r.jsx("svg",{className:"h-6 w-6 text-red-600 dark:text-red-400 mr-3 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"font-semibold text-red-900 dark:text-red-100 mb-1",children:L?"Session Expired":"Verification Error"}),r.jsx("p",{className:"text-red-800 dark:text-red-200 text-sm",children:O||"Your verification session has expired and needs to be restarted."})]})]})}),r.jsxs("div",{className:"bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4",children:[r.jsx("h3",{className:"font-semibold text-blue-900 dark:text-blue-100 mb-2",children:"What to do next:"}),r.jsxs("ul",{className:"text-blue-800 dark:text-blue-200 text-sm space-y-1 list-disc list-inside",children:[r.jsx("li",{children:'Click "Restart Verification" below to generate a new session'}),r.jsx("li",{children:"Complete the verification process without delays"}),r.jsx("li",{children:"If issues persist, contact support"})]})]})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"button",onClick:S,disabled:u,children:u?"Restarting...":"Restart Verification"})]})]});if(H&&l){const N=c;return d!=null&&d.url?r.jsxs(F,{children:[r.jsx(G,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Identity Verification"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please complete the identity verification process"})]}),r.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:u,children:"Restart"})]})}),r.jsxs(P,{children:[r.jsx("div",{className:"mb-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:r.jsxs("p",{className:"text-yellow-800 dark:text-yellow-200 text-sm",children:[r.jsx("strong",{children:"Important:"}),' If you see an "expired" or "invalid link" message below, click the "Restart" button above to generate a new verification session.']})}),r.jsx("div",{className:"w-full",style:{height:"600px"},children:r.jsx("iframe",{src:d.url,className:"w-full h-full border-0 rounded-lg",allow:"camera; microphone; geolocation",title:"Identity Verification",onLoad:x=>{var M,q,Z;console.log("[Identity] Iframe loaded");try{const K=x.target,we=K.contentDocument||((M=K.contentWindow)==null?void 0:M.document);if(we){const de=((Z=(q=we.body)==null?void 0:q.textContent)==null?void 0:Z.toLowerCase())||"";(de.includes("expired")||de.includes("invalid")||de.includes("error"))&&(console.warn("[Identity] Iframe shows expiration message"),I(!0),g("Your verification link has expired."))}}catch{console.log("[Identity] Cannot check iframe content (CORS)")}}})})]}),s&&r.jsx(ee,{children:r.jsx(z,{variant:"outline",onClick:s,children:"Back"})})]}):N===re.SardinAI?r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Device Risk Assessment"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Analyzing device security and behavioral patterns..."})]}),r.jsx(P,{children:r.jsxs("div",{className:"text-center py-12",children:[r.jsx(ae,{className:"mb-4"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Please wait while we verify your device security"}),r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-500 mt-2",children:"This process is automatic and will complete in a few seconds"})]})})]}):r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Identity Verification"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please complete the identity verification process"})]}),r.jsx(P,{children:r.jsx("div",{id:"identity-container",className:"min-h-[400px]"})}),s&&r.jsx(ee,{children:r.jsx(z,{variant:"outline",onClick:s,children:"Back"})})]})}return r.jsx("form",{onSubmit:_.handleSubmit(E),children:r.jsxs(F,{children:[r.jsxs(G,{children:[r.jsx("h2",{className:"text-2xl font-bold",children:"Review Your Information"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-1",children:"Please review and confirm your information before starting identity verification"})]}),r.jsxs(P,{className:"space-y-6",children:[r.jsxs("div",{className:"space-y-4 pb-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:"Name"}),r.jsxs("p",{className:"mt-1 text-base",children:[($=k==null?void 0:k.applicantRequestData)==null?void 0:$.firstName," ",(f=k==null?void 0:k.applicantRequestData)==null?void 0:f.lastName]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:"Email"}),r.jsx("p",{className:"mt-1 text-base",children:(D=k==null?void 0:k.applicantRequestData)==null?void 0:D.email})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-500 dark:text-gray-400",children:"Date of Birth"}),r.jsx("p",{className:"mt-1 text-base",children:((B=k==null?void 0:k.applicantRequestData)==null?void 0:B.dateOfBirth)||"Not provided"})]})]}),r.jsxs("div",{className:"space-y-4",children:[r.jsx("h3",{className:"text-lg font-semibold",children:"Address Information"}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsx(ue.Controller,{control:_.control,name:"country",render:({field:N})=>r.jsx(le,{...N,label:"Country",options:[{value:"",label:"Select country..."},...b.map(x=>({value:x.abbreviation3||x.abbreviation,label:x.name}))]})}),r.jsx(ue.Controller,{control:_.control,name:"nationality",render:({field:N})=>r.jsx(le,{...N,label:"Nationality",options:[{value:"",label:"Select nationality..."},...b.map(x=>({value:x.abbreviation3||x.abbreviation,label:x.name}))]})})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsx(ue.Controller,{control:_.control,name:"street",render:({field:N})=>r.jsx(X,{...N,label:"Street"})}),r.jsx(ue.Controller,{control:_.control,name:"streetNumber",render:({field:N})=>r.jsx(X,{...N,label:"Street Number"})})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsx(ue.Controller,{control:_.control,name:"city",render:({field:N})=>r.jsx(X,{...N,label:"City"})}),r.jsx(ue.Controller,{control:_.control,name:"zip",render:({field:N})=>r.jsx(X,{...N,label:"ZIP/Postal Code"})})]}),r.jsx(ue.Controller,{control:_.control,name:"phonenumber",render:({field:N})=>r.jsx(X,{...N,label:"Phone Number",type:"tel"})})]})]}),r.jsxs(ee,{className:"flex justify-between",children:[s&&r.jsx(z,{type:"button",variant:"outline",onClick:s,children:"Back"}),r.jsx(z,{type:"submit",isLoading:u,children:"Confirm and Start Verification"})]})]})})},Ne=({kycStatus:e,reviewStatus:t,workflowResult:s,customMessage:a,onContinue:n,onContactSupport:i})=>{const c=e===me.Approved?{type:"success",title:"Verification Approved",icon:"✓",iconBg:"bg-green-100 dark:bg-green-900/30",iconColor:"text-green-600 dark:text-green-400",message:"Your identity verification has been successfully approved."}:e===me.Rejected?{type:"error",title:"Verification Rejected",icon:"✕",iconBg:"bg-red-100 dark:bg-red-900/30",iconColor:"text-red-600 dark:text-red-400",message:"Unfortunately, your identity verification was not approved."}:e===me.Pending||e===me.InProgress?{type:"pending",title:"Verification Pending",icon:"⏱",iconBg:"bg-blue-100 dark:bg-blue-900/30",iconColor:"text-blue-600 dark:text-blue-400",message:"Your identity verification is currently being processed."}:t===pe.Approved?{type:"success",title:"Application Approved",icon:"✓",iconBg:"bg-green-100 dark:bg-green-900/30",iconColor:"text-green-600 dark:text-green-400",message:"Your application has been approved."}:t===pe.Reject?{type:"error",title:"Application Rejected",icon:"✕",iconBg:"bg-red-100 dark:bg-red-900/30",iconColor:"text-red-600 dark:text-red-400",message:"Your application has been rejected."}:t===pe.UnderReview||t===pe.AdminReview?{type:"pending",title:"Under Review",icon:"📋",iconBg:"bg-yellow-100 dark:bg-yellow-900/30",iconColor:"text-yellow-700 dark:text-yellow-400",message:"Your application is currently under manual review."}:s===ye.Success?{type:"success",title:"Process Complete",icon:"✓",iconBg:"bg-green-100 dark:bg-green-900/30",iconColor:"text-green-600 dark:text-green-400",message:"Your verification process has been completed successfully."}:s===ye.Failed?{type:"error",title:"Process Failed",icon:"✕",iconBg:"bg-red-100 dark:bg-red-900/30",iconColor:"text-red-600 dark:text-red-400",message:"The verification process could not be completed."}:s===ye.AdminReview?{type:"pending",title:"Admin Review Required",icon:"📋",iconBg:"bg-yellow-100 dark:bg-yellow-900/30",iconColor:"text-yellow-700 dark:text-yellow-400",message:"Your application requires administrator review."}:{type:"pending",title:"Processing",icon:"⏱",iconBg:"bg-blue-100 dark:bg-blue-900/30",iconColor:"text-blue-600 dark:text-blue-400",message:"Your application is being reviewed."};return r.jsxs(F,{children:[r.jsxs(P,{className:"py-12",children:[r.jsx("div",{className:"flex justify-center mb-6",children:r.jsx("div",{className:`w-24 h-24 rounded-full flex items-center justify-center ${c.iconBg}`,children:r.jsx("span",{className:`text-5xl ${c.iconColor}`,children:c.icon})})}),r.jsx("h2",{className:"text-3xl font-bold text-center text-gray-900 dark:text-white mb-4",children:c.title}),r.jsx("div",{className:"flex justify-center mb-6",children:r.jsx(ie,{variant:c.type==="success"?"success":c.type==="error"?"danger":c.type==="pending"?"warning":"info",children:e!=null?me[e]:pe[t]})}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mb-6 max-w-md mx-auto",children:a||c.message}),c.type==="success"&&r.jsxs("div",{className:"bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 mb-6",children:[r.jsx("h3",{className:"font-semibold text-green-900 dark:text-green-100 mb-2",children:"What's Next?"}),r.jsxs("ul",{className:"text-sm text-green-800 dark:text-green-200 space-y-1",children:[r.jsx("li",{children:"✓ Your identity has been verified"}),r.jsx("li",{children:"✓ You can now proceed with your application"}),r.jsx("li",{children:"✓ All features are now accessible"})]})]}),c.type==="error"&&r.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6",children:[r.jsx("h3",{className:"font-semibold text-red-900 dark:text-red-100 mb-2",children:"What Can You Do?"}),r.jsxs("ul",{className:"text-sm text-red-800 dark:text-red-200 space-y-2",children:[r.jsx("li",{children:"• Review the requirements and ensure all information is correct"}),r.jsx("li",{children:"• Contact our support team for assistance"}),r.jsx("li",{children:"• You may be able to resubmit your application"})]})]}),c.type==="pending"&&r.jsxs("div",{className:"bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6",children:[r.jsx("h3",{className:"font-semibold text-blue-900 dark:text-blue-100 mb-2",children:"What Happens Next?"}),r.jsxs("ul",{className:"text-sm text-blue-800 dark:text-blue-200 space-y-2",children:[r.jsx("li",{children:"• Our team is reviewing your information"}),r.jsx("li",{children:"• You will be notified via email once the review is complete"}),r.jsx("li",{children:"• This typically takes 24-48 hours"}),r.jsx("li",{children:"• No action is required from you at this time"})]})]}),r.jsx("div",{className:"mt-6 pt-6 border-t border-gray-200 dark:border-gray-700",children:r.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"KYC Status:"}),r.jsx("div",{className:"font-medium text-gray-900 dark:text-white mt-1",children:e!=null?me[e]:"Not Available"})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"Review Status:"}),r.jsx("div",{className:"font-medium text-gray-900 dark:text-white mt-1",children:pe[t]})]})]})})]}),r.jsxs(ee,{className:"flex justify-center gap-4",children:[c.type==="success"&&n&&r.jsx(z,{onClick:n,size:"lg",children:"Continue"}),c.type==="error"&&r.jsxs(r.Fragment,{children:[i&&r.jsx(z,{variant:"outline",onClick:i,children:"Contact Support"}),n&&r.jsx(z,{onClick:n,children:"Try Again"})]}),c.type==="pending"&&r.jsx("div",{className:"text-center",children:r.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Please check back later or wait for our email notification"})})]})]})},$t=({config:e,className:t=""})=>!(e!=null&&e.visible)||!(e!=null&&e.url)?null:r.jsx("div",{className:`metakyc-logo ${t}`,children:r.jsx("img",{src:e.url,alt:e.alt||"Company Logo",style:{width:e.width||"auto",height:e.height||"40px",maxWidth:"100%",objectFit:"contain"},onError:s=>{console.warn("[Logo] Failed to load logo:",e.url),s.target.style.display="none"}})}),Ee=({title:e,subtitle:t,className:s=""})=>{const{currentTheme:a}=te(),n=e||(a==null?void 0:a.title)||"",i=!!(a!=null&&a.logo&&a.logo.visible&&a.logo.url),l=!!n;return!i&&!l?null:r.jsxs("div",{className:`metakyc-header ${s}`,children:[r.jsxs("div",{className:"metakyc-header-title flex items-center text-xl font-bold text-gray-900 dark:text-white",children:[i&&r.jsx($t,{config:a.logo}),i&&l&&r.jsx("span",{className:"text-gray-400 dark:text-gray-500 mx-3",style:{fontSize:"1.5rem",fontWeight:300},children:"|"}),l&&r.jsx("span",{children:n})]}),t&&r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:t})]})},yr=({workflowKey:e,externalRefId:t,onSuccess:s,onCancel:a})=>{var E,S,$;const{config:n,baseInformationService:i,currentTheme:l}=te(),{createApplicant:c,isLoading:d}=Et(),[u,w]=o.useState([]),[v,p]=o.useState(!0),[y,m]=o.useState(!1),[k,h]=o.useState(null),b=o.useRef(!1),A=o.useRef(!1),j=e||((E=n.applicantForm)==null?void 0:E.workflowKey);if(!j)throw new Error("workflowKey is required. Provide it either as a prop to CreateApplicantForm or set it in config.applicantForm.workflowKey");const C=t||((S=n.applicantForm)==null?void 0:S.externalRefId)||"",H=["firstName","lastName","email","phonenumber","dateOfBirth"],R=o.useMemo(()=>{const f=new Set(H),D=l==null?void 0:l.applicantFormRequiredFields;if(D&&D.length>0)for(const B of D)f.add(B);return Array.from(f)},[l==null?void 0:l.applicantFormRequiredFields]),O=o.useMemo(()=>{var B;let f;(B=n.applicantForm)!=null&&B.visibleFields?f=n.applicantForm.visibleFields:l!=null&&l.applicantFormVisibleFields&&l.applicantFormVisibleFields.length>0?f=l.applicantFormVisibleFields:f=_e;const D=new Set(f);for(const N of H)D.add(N);return Array.from(D)},[($=n.applicantForm)==null?void 0:$.visibleFields,l==null?void 0:l.applicantFormVisibleFields]),[g,L]=o.useState({workflowKey:j,firstName:"",lastName:"",title:"",email:"",dateOfBirth:"",phonenumber:"",externalRefId:C,mobileCountryCode:"",street:"",streetNumber:"",zip:"",city:"",country:"",nationality:"",otherNationality:[],defaultLanguage:"EN",taxCountry:"",placeOfBirth:"",countryOfBirth:"",salutation:null,educationLevel:"",occupation:"",taxNumber:""});o.useEffect(()=>{(async()=>{if(b.current||A.current){console.log("[CreateApplicant] Countries already loading or loaded, skipping...");return}b.current=!0,p(!0);try{const D=await i.getCountries("",n.locale||"en"),B=new Set,N=D.map(x=>({value:x.abbreviation3||x.abbreviation,label:x.name})).filter(x=>!x.value||B.has(x.value)?!1:(B.add(x.value),!0));w(N),A.current=!0}catch(D){console.error("Failed to load countries:",D)}finally{p(!1),b.current=!1}})()},[]);const I=(f,D)=>{L(B=>({...B,[f]:D}))},Q=async f=>{var D;f.preventDefault(),m(!0),h(null);try{if(!g.externalRefId||g.externalRefId.trim()===""){h("External Reference ID is required. Please pass it via config.applicantForm.externalRefId."),m(!1);return}for(const x of R){const M=g[x];if(M==null||M===""||Array.isArray(M)&&M.length===0){const Z=((D=Se[x])==null?void 0:D.label)||x;h(`${Z} is required.`),m(!1);return}}const B={workflowKey:g.workflowKey,externalRefId:g.externalRefId.trim()};O.forEach(x=>{if(x==="externalRefId")return;const M=g[x];M!=null&&M!==""&&!(Array.isArray(M)&&M.length===0)&&(B[x]=M)}),console.log("Creating applicant with data:",B);const N=await c(B);console.log("Applicant created:",N),s(N.applicantId)}catch(B){console.error("Error creating applicant:",B),h(B.message||"Failed to create applicant")}finally{m(!1)}},_=f=>{var N;const D=Se[f],B=R.includes(f);switch(D.type){case"select":if(f==="country"||f==="nationality"||f==="taxCountry"||f==="countryOfBirth")return r.jsx(le,{label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),options:[{value:"",label:`Select ${D.label.toLowerCase()}...`},...u],disabled:v,required:B},f);if(f==="salutation")return r.jsx(le,{label:D.label,value:((N=g[f])==null?void 0:N.toString())||"",onChange:x=>I(f,x.target.value?Number(x.target.value):null),options:[{value:"",label:"Select salutation..."},{value:be.Male.toString(),label:"Male"},{value:be.Female.toString(),label:"Female"},{value:be.Other.toString(),label:"Other"}],required:B},f);if(f==="defaultLanguage"){const x=l!=null&&l.allowedLanguages&&l.allowedLanguages.length>0?je.filter(M=>l.allowedLanguages.includes(M.value)):je;return r.jsx(le,{label:D.label,value:g[f]||"",onChange:M=>I(f,M.target.value),options:[{value:"",label:"Select language..."},...x],required:B},f)}return null;case"multiselect":return f==="otherNationality"?r.jsx(Rt,{label:D.label,value:g[f]||[],onChange:x=>I(f,x),options:u,placeholder:"Select other nationalities...",disabled:v,required:B},f):null;case"date":return r.jsx(X,{type:"date",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f);case"email":return r.jsx(X,{type:"email",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f);case"tel":return r.jsx(X,{type:"tel",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f);case"text":default:return r.jsx(X,{type:"text",label:D.label,value:g[f]||"",onChange:x=>I(f,x.target.value),required:B},f)}};return v?r.jsx("div",{className:"metakyc-sdk",children:r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading form..."})]})})}):r.jsx("div",{className:"metakyc-sdk",children:r.jsx("form",{onSubmit:Q,children:r.jsxs(F,{children:[r.jsx(G,{children:r.jsx(Ee,{title:"Create Applicant",subtitle:"Please fill in the required information to begin the KYC verification process."})}),r.jsxs(P,{children:[k&&r.jsx("div",{className:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg",children:r.jsxs("p",{className:"text-red-600 dark:text-red-400 text-sm",children:[r.jsx("strong",{children:"Error:"})," ",k]})}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:O.map(f=>_(f))})]}),r.jsxs(ee,{className:"flex justify-between",children:[a&&r.jsx(z,{type:"button",variant:"outline",onClick:a,disabled:y||d,children:"Cancel"}),r.jsx(z,{type:"submit",isLoading:y||d,children:"Create Applicant"})]})]})})})},br=({applicantId:e,onComplete:t,onError:s,theme:a="light",className:n})=>{const{progress:i,currentStep:l,steps:c,workflowKey:d,nextWorkflowKey:u,hasWorkflowChanged:w,isLoading:v,error:p,moveBack:y,refreshProgress:m}=kt(e),[k,h]=o.useState(!1);if(o.useEffect(()=>{p&&s&&s(p)},[p,s]),o.useEffect(()=>{i!=null&&i.workflowResult&&t&&t(i.workflowResult)},[i==null?void 0:i.workflowResult,t]),o.useEffect(()=>{a==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},[a]),o.useEffect(()=>{w&&h(!1)},[w]),v||!i)return r.jsx("div",{className:n,children:r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:"Loading workflow..."})]})})});if(p)return r.jsx("div",{className:n,children:r.jsx(F,{children:r.jsx(P,{children:r.jsxs("div",{className:"text-center py-8",children:[r.jsx("p",{className:"text-danger-500 text-lg mb-4",children:"An error occurred"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:p.message})]})})})});if(w&&!k)return r.jsx("div",{className:`metakyc-sdk ${n||""}`,children:r.jsx(F,{children:r.jsx(P,{children:r.jsxs("div",{className:"text-center py-8",children:[r.jsx("div",{className:"mb-6",children:r.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900 mb-4",children:r.jsx("svg",{className:"w-8 h-8 text-blue-600 dark:text-blue-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})})}),r.jsx("h3",{className:"text-xl font-semibold text-gray-900 dark:text-white mb-2",children:"Workflow Transition"}),r.jsx("p",{className:"text-gray-600 dark:text-gray-400 mb-6",children:"Your application workflow has been updated based on your progress."}),r.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6 max-w-md mx-auto",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsxs("div",{className:"text-left",children:[r.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"Previous Workflow"}),r.jsx("p",{className:"font-medium text-gray-900 dark:text-white",children:d})]}),r.jsx("svg",{className:"w-6 h-6 text-gray-400 mx-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7l5 5m0 0l-5 5m5-5H6"})}),r.jsxs("div",{className:"text-right",children:[r.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-1",children:"New Workflow"}),r.jsx("p",{className:"font-medium text-blue-600 dark:text-blue-400",children:u})]})]}),i.nextWorkflowName&&r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-2 text-xs",children:i.nextWorkflowName})]}),r.jsx("button",{onClick:()=>h(!0),className:"px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors",children:"Continue with New Workflow"})]})})})});if(i.status===se.Finished||i.status===se.OnHold)return r.jsx("div",{className:`metakyc-sdk ${n||""}`,children:r.jsx(Ne,{kycStatus:i.kycStatus,reviewStatus:i.reviewStatus,workflowResult:i.workflowResult,customMessage:i.customMessage,onContinue:t&&i.workflowResult?()=>t(i.workflowResult):void 0,onContactSupport:()=>{typeof window<"u"&&(window.location.href="mailto:support@example.com")}})});if(!l)return r.jsx("div",{className:`metakyc-sdk ${n||""}`,children:r.jsx(F,{children:r.jsxs(P,{children:[r.jsx(ae,{className:"my-8"}),r.jsx("p",{className:"text-center text-gray-600 dark:text-gray-400 mt-4",children:i.status===se.IdentityPending?"Loading identity verification...":"Loading current step..."})]})})});const b=C=>{switch(C){case T.Overview:return"Overview";case T.Questionaries:return"Questionnaire";case T.UploadDocument:return"Documents";case T.IdentitySdk:return"Identity";case T.RiskScoring:return"Risk Assessment";case T.InvestorCategorization:return"Investor Categorization";case T.AppropriatenessTest:return"Appropriateness Test";case T.AdditionalData:return"Additional Data";case T.ManualReview:return"Review";default:return""}},A=()=>{const C=c.filter(g=>g.visibility!==!1),H=C.findIndex(g=>g.order===l.order),R=H>=0?H+1:1,O=C.length;return r.jsxs("div",{className:"mb-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsx(Ee,{}),r.jsxs(ie,{variant:i.status===1?"info":"success",children:["Step ",R," of ",O]})]}),r.jsx("div",{className:"flex items-center",children:C.map((g,L)=>{const I=L<H,Q=g.order===l.order;return r.jsxs(o.Fragment,{children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("div",{className:`
66
66
  w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium
67
67
  ${I||Q?"bg-primary-500 text-white":"bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-400"}
68
- `,children:L+1}),r.jsx("span",{className:`ml-2 text-sm ${Q?"font-semibold text-gray-900 dark:text-white":"text-gray-600 dark:text-gray-400"}`,children:g.displayName||g.name||b(g.action)||`Step ${L+1}`})]}),L<C.length-1&&r.jsx("div",{className:`flex-1 h-0.5 mx-4 ${I?"bg-primary-500":"bg-gray-200 dark:bg-gray-700"}`})]},g.order)})})]})},k=()=>{const C={applicantId:e,onComplete:async()=>{await m()},onBack:l.order>0?y:void 0};switch(l.action){case T.Questionaries:return r.jsx(Mt,{...C});case T.UploadDocument:return r.jsx(Ot,{...C});case T.Overview:return r.jsx(zt,{...C});case T.IdentitySdk:return r.jsx(_t,{...C});case T.RiskScoring:return r.jsx(Bt,{...C});case T.AdditionalData:case T.InvestorCategorization:return r.jsx(Kt,{...C});case T.AppropriatenessTest:return r.jsx(Ut,{...C});case T.ManualReview:return r.jsx(Ne,{kycStatus:i.kycStatus,reviewStatus:i.reviewStatus,workflowResult:i.workflowResult,customMessage:i.customMessage});default:return r.jsx(F,{children:r.jsxs(P,{className:"py-12 text-center",children:[r.jsx("div",{className:"mb-4",children:r.jsx(ae,{})}),r.jsxs("p",{className:"text-gray-600 dark:text-gray-400 mb-2",children:["Processing step: ",l.title||l.name]}),r.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:["Action type: ",T[l.action]]})]})})}};return r.jsxs("div",{className:`metakyc-sdk ${n||""}`,children:[A(),k()]})};function vr(e){return ce.z.object({questionResults:ce.z.any()}).passthrough()}function wr(e){let t=ce.z.array(ce.z.instanceof(File));if(e.isRequired?t=t.min(1,`${e.displayName} is required`):t=t.optional(),e.multipleFile||(t=t.refine(s=>!s||s.length<=1,{message:"Only one file is allowed"})),e.maxEachFileSizeByte>0&&(t=t.refine(s=>!s||s.every(a=>a.size<=e.maxEachFileSizeByte),{message:`File size must not exceed ${Math.round(e.maxEachFileSizeByte/1024/1024)}MB`})),e.allowedTypes){const s=e.allowedTypes.split(",").map(a=>a.trim());t=t.refine(a=>a?a.every(n=>s.some(i=>i.endsWith("/*")?n.type.startsWith(i.slice(0,-2)):n.type===i)):!0,{message:"Invalid file type"})}return t}function jr(e){const t={};return e.uploadDocumentFiles.forEach(s=>{const a=`file_${s.id}`;t[a]=wr(s)}),ce.z.object(t)}function kr(e){return ce.z.any()}function Sr(e){return ce.z.string().min(1,"This question is required")}function Nr(e){const t={};return e.appropriatenessQuestions.forEach(s=>{const a=`question_${s.id}`;t[a]=Sr()}),ce.z.object(t)}const Cr=ce.z.any();exports.ALLOWED_LANGUAGES=ke;exports.ALL_APPLICANT_FIELDS=Qt;exports.ApplicantProgressOnHoldReason=De;exports.ApplicantProgressStatus=se;exports.ApplicantService=We;exports.ApplicantStatus=Pe;exports.AppropriatenessQuestionType=ze;exports.AppropriatenessTestService=Ve;exports.AppropriatenessTestStep=Ut;exports.Badge=ie;exports.BaseInformationService=Xe;exports.Button=z;exports.Card=F;exports.CardContent=P;exports.CardFooter=ee;exports.CardHeader=G;exports.CreateApplicantForm=yr;exports.CriteriaBuiltInType=Ke;exports.DEFAULT_VISIBLE_FIELDS=_e;exports.DocumentReviewStatus=Oe;exports.EndpointBuilder=He;exports.ErrorHandler=ge;exports.EventEmitter=lt;exports.FIELD_METADATA=Se;exports.FileType=Me;exports.FileUpload=It;exports.GenderType=be;exports.Header=Ee;exports.HttpClient=qe;exports.IdentityProviderManager=he;exports.IdentityService=Je;exports.IdentityVerificationProvider=re;exports.IdentityVerificationStep=_t;exports.Input=X;exports.InvestorCategorizationService=et;exports.InvestorCategorizationStep=Kt;exports.InvestorCategorizationType=J;exports.InvestorCategoryType=Ue;exports.KycProcessStatus=Le;exports.KycStatus=me;exports.KycStatusDisplay=Ne;exports.KycWorkflow=br;exports.Logo=$t;exports.MetaKYCContext=Ae;exports.MetaKYCError=ne;exports.MetaKYCProvider=Zt;exports.MultiSelect=Rt;exports.OnfidoProvider=pt;exports.OverviewService=Ge;exports.OverviewStep=zt;exports.PhoneInput=Dt;exports.QuestionnaireService=Ye;exports.QuestionnaireStep=Mt;exports.ReviewStatus=pe;exports.RiskCriteriaType=Be;exports.RiskLevel=Fe;exports.RiskScoringService=Ze;exports.RiskScoringStep=Bt;exports.SardinAIProvider=ht;exports.Select=le;exports.Spinner=ae;exports.StepRouter=dt;exports.SumsubProvider=mt;exports.ThemeManager=gt;exports.ThemePreset=W;exports.ThemeService=ot;exports.UploadDocumentService=Qe;exports.UploadDocumentStep=Ot;exports.UserType=Te;exports.ValueDataType=oe;exports.WorkflowOrchestrator=ut;exports.WorkflowResultType=ye;exports.WorkflowState=ct;exports.WorkflowStepAction=T;exports.appropriatenessTestSchema=Cr;exports.clearAllStorage=rr;exports.clearApplicantId=bt;exports.clearWorkflowState=wt;exports.cn=Y;exports.corporateTheme=tt;exports.defaultConfig=$e;exports.defaultTheme=V;exports.fileToBase64=xt;exports.fintechTheme=rt;exports.formatFileSize=ve;exports.generateAppropriatenessSchema=Nr;exports.generateQuestionnaireSchema=vr;exports.generateRiskScoringSchema=kr;exports.generateUploadDocumentSchema=jr;exports.getAcceptString=er;exports.getApplicantId=yt;exports.getThemePreset=xe;exports.getWorkflowState=tr;exports.healthcareTheme=st;exports.isScriptLoaded=Vt;exports.loadScript=Ce;exports.minimalTheme=nt;exports.modernTheme=at;exports.removeScript=Gt;exports.saveApplicantId=ft;exports.saveWorkflowState=vt;exports.themePresets=it;exports.useApplicant=Et;exports.useAppropriatenessTest=sr;exports.useIdentityVerification=Ct;exports.useKycWorkflow=jt;exports.useMetaKYC=te;exports.useOverview=Nt;exports.useQuestionnaire=kt;exports.useRiskScoring=At;exports.useUploadDocument=St;exports.validateFileSize=Jt;exports.validateFileType=Xt;
68
+ `,children:L+1}),r.jsx("span",{className:`ml-2 text-sm ${Q?"font-semibold text-gray-900 dark:text-white":"text-gray-600 dark:text-gray-400"}`,children:g.displayName||g.name||b(g.action)||`Step ${L+1}`})]}),L<C.length-1&&r.jsx("div",{className:`flex-1 h-0.5 mx-4 ${I?"bg-primary-500":"bg-gray-200 dark:bg-gray-700"}`})]},g.order)})})]})},j=()=>{const C={applicantId:e,onComplete:async()=>{await m()},onBack:l.order>0?y:void 0};switch(l.action){case T.Questionaries:return r.jsx(Mt,{...C});case T.UploadDocument:return r.jsx(Ot,{...C});case T.Overview:return r.jsx(zt,{...C});case T.IdentitySdk:return r.jsx(_t,{...C});case T.RiskScoring:return r.jsx(Bt,{...C});case T.AdditionalData:case T.InvestorCategorization:return r.jsx(Kt,{...C});case T.AppropriatenessTest:return r.jsx(Ut,{...C});case T.ManualReview:return r.jsx(Ne,{kycStatus:i.kycStatus,reviewStatus:i.reviewStatus,workflowResult:i.workflowResult,customMessage:i.customMessage});default:return r.jsx(F,{children:r.jsxs(P,{className:"py-12 text-center",children:[r.jsx("div",{className:"mb-4",children:r.jsx(ae,{})}),r.jsxs("p",{className:"text-gray-600 dark:text-gray-400 mb-2",children:["Processing step: ",l.title||l.name]}),r.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:["Action type: ",T[l.action]]})]})})}};return r.jsxs("div",{className:`metakyc-sdk ${n||""}`,children:[A(),j()]})};function vr(e){return ce.z.object({questionResults:ce.z.any()}).passthrough()}function wr(e){let t=ce.z.array(ce.z.instanceof(File));if(e.isRequired?t=t.min(1,`${e.displayName} is required`):t=t.optional(),e.multipleFile||(t=t.refine(s=>!s||s.length<=1,{message:"Only one file is allowed"})),e.maxEachFileSizeByte>0&&(t=t.refine(s=>!s||s.every(a=>a.size<=e.maxEachFileSizeByte),{message:`File size must not exceed ${Math.round(e.maxEachFileSizeByte/1024/1024)}MB`})),e.allowedTypes){const s=e.allowedTypes.split(",").map(a=>a.trim());t=t.refine(a=>a?a.every(n=>s.some(i=>i.endsWith("/*")?n.type.startsWith(i.slice(0,-2)):n.type===i)):!0,{message:"Invalid file type"})}return t}function kr(e){const t={};return e.uploadDocumentFiles.forEach(s=>{const a=`file_${s.id}`;t[a]=wr(s)}),ce.z.object(t)}function jr(e){return ce.z.any()}function Sr(e){return ce.z.string().min(1,"This question is required")}function Nr(e){const t={};return e.appropriatenessQuestions.forEach(s=>{const a=`question_${s.id}`;t[a]=Sr()}),ce.z.object(t)}const Cr=ce.z.any();exports.ALLOWED_LANGUAGES=je;exports.ALL_APPLICANT_FIELDS=Qt;exports.ApplicantProgressOnHoldReason=De;exports.ApplicantProgressStatus=se;exports.ApplicantService=We;exports.ApplicantStatus=Pe;exports.AppropriatenessQuestionType=ze;exports.AppropriatenessTestService=Ve;exports.AppropriatenessTestStep=Ut;exports.Badge=ie;exports.BaseInformationService=Xe;exports.Button=z;exports.Card=F;exports.CardContent=P;exports.CardFooter=ee;exports.CardHeader=G;exports.CreateApplicantForm=yr;exports.CriteriaBuiltInType=Ke;exports.DEFAULT_VISIBLE_FIELDS=_e;exports.DocumentReviewStatus=Oe;exports.EndpointBuilder=He;exports.ErrorHandler=ge;exports.EventEmitter=lt;exports.FIELD_METADATA=Se;exports.FileType=Me;exports.FileUpload=It;exports.GenderType=be;exports.Header=Ee;exports.HttpClient=qe;exports.IdentityProviderManager=he;exports.IdentityService=Je;exports.IdentityVerificationProvider=re;exports.IdentityVerificationStep=_t;exports.Input=X;exports.InvestorCategorizationService=et;exports.InvestorCategorizationStep=Kt;exports.InvestorCategorizationType=J;exports.InvestorCategoryType=Ue;exports.KycProcessStatus=Le;exports.KycStatus=me;exports.KycStatusDisplay=Ne;exports.KycWorkflow=br;exports.Logo=$t;exports.MetaKYCContext=Ae;exports.MetaKYCError=ne;exports.MetaKYCProvider=Zt;exports.MultiSelect=Rt;exports.OnfidoProvider=pt;exports.OverviewService=Ge;exports.OverviewStep=zt;exports.PhoneInput=Dt;exports.QuestionnaireService=Ye;exports.QuestionnaireStep=Mt;exports.ReviewStatus=pe;exports.RiskCriteriaType=Be;exports.RiskLevel=Fe;exports.RiskScoringService=Ze;exports.RiskScoringStep=Bt;exports.SardinAIProvider=ht;exports.Select=le;exports.Spinner=ae;exports.StepRouter=dt;exports.SumsubProvider=mt;exports.ThemeManager=gt;exports.ThemePreset=W;exports.ThemeService=ot;exports.UploadDocumentService=Qe;exports.UploadDocumentStep=Ot;exports.UserType=Te;exports.ValueDataType=oe;exports.WorkflowOrchestrator=ut;exports.WorkflowResultType=ye;exports.WorkflowState=ct;exports.WorkflowStepAction=T;exports.appropriatenessTestSchema=Cr;exports.clearAllStorage=rr;exports.clearApplicantId=bt;exports.clearWorkflowState=wt;exports.cn=Y;exports.corporateTheme=tt;exports.defaultConfig=$e;exports.defaultTheme=V;exports.fileToBase64=xt;exports.fintechTheme=rt;exports.formatFileSize=ve;exports.generateAppropriatenessSchema=Nr;exports.generateQuestionnaireSchema=vr;exports.generateRiskScoringSchema=jr;exports.generateUploadDocumentSchema=kr;exports.getAcceptString=er;exports.getApplicantId=yt;exports.getThemePreset=xe;exports.getWorkflowState=tr;exports.healthcareTheme=st;exports.isScriptLoaded=Vt;exports.loadScript=Ce;exports.minimalTheme=nt;exports.modernTheme=at;exports.removeScript=Gt;exports.saveApplicantId=ft;exports.saveWorkflowState=vt;exports.themePresets=it;exports.useApplicant=Et;exports.useAppropriatenessTest=sr;exports.useIdentityVerification=Ct;exports.useKycWorkflow=kt;exports.useMetaKYC=te;exports.useOverview=Nt;exports.useQuestionnaire=jt;exports.useRiskScoring=At;exports.useUploadDocument=St;exports.validateFileSize=Jt;exports.validateFileType=Xt;
69
69
  //# sourceMappingURL=index.cjs.map