@swan-admin/swan-web-component 1.0.125 → 1.0.127

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.
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),s=require("./Modal-CraqOTeI.js"),n=require("clsx"),a=require("react-webcam"),r=require("lucide-react"),o=require("@mui/material"),c=require("video.js");const i="DESKTOP",l="TAB",u="MOBILE",d=t.createContext(void 0);function m({children:s}){const[n,a]=t.useState([window?.innerWidth,window?.innerHeight]),[r,o]=t.useState(!1),c=()=>{a([window?.innerWidth,window?.innerHeight])};t.useEffect(()=>{c()},[]),t.useLayoutEffect(()=>(window.addEventListener("resize",c),()=>window.removeEventListener("resize",c)),[c]);let m=i;n[0]>768&&n[0]<1024&&(m=l),n[0]<768&&(m=u);const p=t.useMemo(()=>({size:n,setSize:a,clearInputs:r,setClearInputs:o,media:m}),[n,r,m]);return e.jsx(d.Provider,{value:p,children:s})}var p=t.memo(function({size:t=16}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 25 25",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M22.6968 14.6968C22.6968 16.8185 21.8539 18.8533 20.3536 20.3536C18.8533 21.8539 16.8185 22.6968 14.6968 22.6968",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.6968 11.6968V10.6968C18.6968 10.1663 18.4861 9.65764 18.111 9.28256C17.7359 8.90749 17.2272 8.69678 16.6968 8.69678C16.1663 8.69678 15.6576 8.90749 15.2826 9.28256C14.9075 9.65764 14.6968 10.1663 14.6968 10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M14.6968 10.6968V9.69678C14.6968 9.16634 14.4861 8.65764 14.111 8.28256C13.7359 7.90749 13.2272 7.69678 12.6968 7.69678C12.1663 7.69678 11.6576 7.90749 11.2826 8.28256C10.9075 8.65764 10.6968 9.16634 10.6968 9.69678V10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M10.6968 10.1968V4.69678C10.6968 4.16634 10.4861 3.65764 10.111 3.28256C9.73592 2.90749 9.22721 2.69678 8.69678 2.69678C8.16634 2.69678 7.65764 2.90749 7.28256 3.28256C6.90749 3.65764 6.69678 4.16634 6.69678 4.69678V14.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.6969 11.6968C18.6969 11.1663 18.9076 10.6576 19.2827 10.2826C19.6577 9.90749 20.1664 9.69678 20.6969 9.69678C21.2273 9.69678 21.736 9.90749 22.1111 10.2826C22.4862 10.6576 22.6969 11.1663 22.6969 11.6968V14.6968C22.6969 16.8185 21.854 18.8533 20.3537 20.3536C18.8534 21.8539 16.8186 22.6968 14.6969 22.6968H12.6969C9.89688 22.6968 8.19688 21.8368 6.70688 20.3568L3.10688 16.7568C2.76282 16.3757 2.57847 15.8769 2.592 15.3637C2.60554 14.8505 2.81593 14.3621 3.1796 13.9997C3.54327 13.6373 4.03238 13.4287 4.54565 13.417C5.05892 13.4053 5.55704 13.5914 5.93688 13.9368L7.69688 15.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})});var f=t.memo(function({angle:a,countdown:r,isScanning:o,isInTargetRange:c,stabilityScore:i,children:l}){const{translate:u}=t.useContext(s.LanguageContext)||{},d=s.useConfig(),m=t.useCallback(()=>a<80?Math.max(0,Math.min(100,10*(a-60))):a>95?Math.max(0,Math.min(100,10*(105-a))):100,[a]),f=t.useMemo(()=>{if(o)return d?.style?.angleDetector?.successAngleBackground||"#4f46e5";const e=m();if(0===e)return d?.style?.angleDetector?.successAngleLowBackground||"#ffffff";if(100===e)return d?.style?.angleDetector?.successAngleBackground||"#4f46e5";return`rgb(${Math.round(255-e/100*116)}, ${Math.round(255-e/100*163)}, ${Math.round(255-e/100*9)})`},[o,m]),h=t.useCallback((e,t)=>t>70?e?`text-[${d?.style?.angleDetector?.successAngleTextLightColor}]/70`:`text-[${d?.style?.angleDetector?.successAngleTextLightColor}]`:e?`text-[${d?.style?.angleDetector?.successAngleTextLightColor}]/40`:`text-[${d?.style?.angleDetector?.successAngleTextDarkColor}]/70`,[]),g=t.useCallback((e=!1)=>{const t=m();return o?`text-[${d?.style?.angleDetector?.successAngleTextLightColor}]`:h(e,t)},[o,m]),x=t.useCallback((e,t)=>t>70||e?d?.style?.angleDetector?.successAngleTextLightColor:d?.style?.angleDetector?.successAngleTextDarkColor,[]),S=t.useCallback((e=!1)=>{const t=m();return o?d?.style?.angleDetector?.successAngleTextLightColor:x(e,t)},[o,m]),v=r;function y(){document.documentElement.style.setProperty("--real-vh",window.innerHeight+"px")}return y(),window.addEventListener("resize",y),e.jsxs("div",{className:"flex common-ui-main w-screen flex-col items-center h-[var(--real-vh)] overflow-hidden touch-none justify-center transition-all duration-300 max-w-[28rem] mx-auto",style:{backgroundColor:f},"data-testid":"level-screen","data-angle-state":o?"locked":c?"target":"adjusting",children:[e.jsx("div",{className:"flex justify-start fixed top-[.5rem] max-w-[28rem] mx-auto w-full px-[1rem]",children:e.jsx("div",{className:"flex justify-start ",children:e.jsx(s.Header,{noTitle:!0})})}),null!==v?e.jsx("div",{className:"relative flex h-[6rem] w-[6rem] items-center justify-center rounded-[9999px] bg-[#fff]/20 transition-all duration-300",style:{border:`2px solid ${S()}`},children:e.jsx("div",{className:`text-[3rem] font-bold text-[${S()}]`,style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:v})}):o?e.jsxs("div",{className:"relative flex flex-col items-center justify-center",children:[e.jsx("div",{className:"relative flex h-16 w-16 items-center justify-center rounded-[9999px] border-2 bg-[#fff]/30 border-[#fff]",children:e.jsx("div",{className:"h-4 w-4 rounded-[9999px] animate-pulse bg-[#fff]/80"})}),l]}):e.jsxs("div",{className:n("relative flex h-[4rem] w-[4rem] items-center justify-center rounded-[9999px] ",c?"bg-[#fff]/20 border-[#fff]":"bg-[#fff]/10 border-[#fff]"),style:{transform:`translateY(${3*(90-a)}px)`,transition:"transform 0.2s ease-out",border:`2px solid ${S()}`},children:[e.jsx("div",{className:`h-[1rem] w-[1rem] rounded-[9999px] bg-[${S()}]/80`,style:{backgroundColor:`${S()}B3`}}),e.jsxs("div",{className:n("mt-[.5rem] text-center w-[180px] flex-col flex items-center absolute top-[60px]",g()),style:{color:S()},children:[e.jsx(p,{size:30}),e.jsxs("p",{style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[" ",u?.(s.LanguageKeys.startLevelCheck),e.jsx("br",{})]})]})]}),null!==v&&e.jsx("div",{className:"absolute bottom-[8rem] text-center",children:e.jsx("div",{className:n("text-sm font-medium px-4 py-1.5 bg-black/20 rounded-[9999px] mt-8",g()),style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:u?.(s.LanguageKeys.leavePhone)})}),c&&null===v&&!o&&e.jsx("div",{className:"absolute bottom-[8rem] w-[12rem]",children:e.jsx("div",{className:`h-[.375rem] w-full bg-[${S()}]/20 rounded-[9999px] overflow-hidden`,style:{backgroundColor:`${S()}33`},children:e.jsx("div",{className:`h-full bg-[${S()}]/70 transition-all duration-300 rounded-[9999px]`,style:{width:`${a}%`,backgroundColor:`${S()}B3`}})})}),null===v&&!o&&e.jsx("div",{className:"absolute bottom-[5rem] text-center",children:e.jsxs("div",{className:n("text-[1.5rem] font-light",g()),style:{color:S(),fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[Math.round(a),"°"]})}),null===v&&!o&&e.jsx("div",{className:"absolute bottom-[2rem] text-center max-w-[20rem] mx-auto",children:e.jsx("div",{className:n("text-[.75rem] opacity-50",g()),style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:u?.(s.LanguageKeys.placePhoneUpright)})})]})});function h({resetScan:n,loadingCam:o,onUserMedia:c,onPause:i,pause:l,onReScan:m,recordingStarted:p,startSendingVideoFrames:f,showPause:h,webcamRef:g,onUserMediaError:x,resetDetector:S,videoConstraints:v,webcamKey:y,faceDone:b,isScanning:C}){const{media:w}=t.useContext(d)||{},{translate:j}=t.useContext(s.LanguageContext)||{};return e.jsxs("div",{className:"App w-screen h-[100vh] relative common-ui-main","data-testid":"camera-scan","data-scan-phase":b?"spinning":p?"pose-detecting":C?"starting":"ready",children:[e.jsx("span",{onClick:()=>{n(),S()},className:"fixed right-[20px] top-[20px] z-[999]",children:e.jsx(r.X,{className:"text-[#fff]"})}),e.jsx("div",{className:"w-full h-full overflow-hidden ",children:w===u&&e.jsx(a,{audio:!1,ref:g,screenshotQuality:1,videoConstraints:v,mirrored:!0,screenshotFormat:"image/jpeg",poster:s.transparentPoster,onUserMedia:c,onUserMediaError:x,style:{position:"fixed",top:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}},y)}),e.jsxs("div",{className:"fixed bottom-[30px] w-full z-[999] flex flex-col gap-4 items-center justify-center",children:[h&&e.jsx(s.SpecificButton,{className:"!w-[180px] !h-[40px] !py-[0] mx-auto ",prefix:s.pauseIcon,buttonText:j?.(s.LanguageKeys.pause),buttonFunc:i,btnSecondary:!0}),l?e.jsx("div",{children:e.jsx(s.SpecificButton,{className:"!w-[180px] !h-[40px] !py-[0] mx-auto",buttonText:j?.(s.LanguageKeys.restart),buttonFunc:m,btnSecondary:!0})}):p?null:e.jsx(s.SpecificButton,{"data-testid":"start-scan-btn",className:"!w-[180px] !h-[40px] !py-[0] mx-auto !bg-[#ffffff] !text-[#000000] "+(o?"!opacity-50":""),buttonText:j?.(s.LanguageKeys.startScan),buttonFunc:f,disabled:o})]}),e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:`${s.voiceOverAssetsPath}scanAudioInstructions/silence.mp3`})]})}let g=null,x=null,S=null;let v,y=null;var b=t.memo(function({setIsScanLocked:n,resetDetector:a,scanID:r,setIsVideoUploaded:o,setScanFailsError:c,setScanStartTime:i,setScanUniqueKey:l,userDetails:u}){const{email:d,shopDomain:m,gender:p,heightInCm:f}=u,b=t.useRef(null),C=t.useRef(null),w=t.useRef(null),[j,k]=t.useState([]),[E,N]=t.useState(!0),[T,D]=t.useState(!1),[I,_]=t.useState(!1),[L,M]=t.useState(!0),[F,P]=t.useState(!1),R=t.useRef(null),[$,A]=t.useState(""),[U,O]=t.useState([]),[B,z]=t.useState(""),[K,q]=t.useState(!1),[V,W]=t.useState(!1),[H,G]=t.useState(!1),[J,Q]=t.useState([]),[X,Y]=t.useState(!1),Z=t.useRef(!0),{poseDetector:ee}=function(){const[e,s]=t.useState(0),[n,a]=t.useState(0),[r,o]=t.useState(!1),c=t.useRef(0),i=t.useRef(0),l=t.useRef(!0);async function u(){if("undefined"==typeof window||"undefined"==typeof navigator)return!1;try{console.log("Starting TensorFlow preload...");const[e,t,s]=await Promise.all([Promise.resolve().then(function(){return require("./pose-detection.esm-Bk0xrbdx.js")}),import("@tensorflow/tfjs-core"),import("@tensorflow/tfjs-backend-webgl")]);S=e;const n=t.getBackend();if(n)await t.ready(),console.log(`TensorFlow backend already active (${n})`);else{let e=!1;try{e=await t.setBackend("webgl")}catch(e){console.warn("WebGL backend threw during init:",e)}e||(console.warn("WebGL unavailable, falling back to CPU backend"),await t.setBackend("cpu")),await t.ready(),console.log(`TensorFlow backend ready (${t.getBackend()})`)}const a={runtime:"mediapipe",modelType:"full",solutionPath:"https://cdn.jsdelivr.net/npm/@mediapipe/pose"};try{x=await S.createDetector(S.SupportedModels.BlazePose,a),console.log("MediaPipe detector created successfully")}catch(e){console.warn("MediaPipe failed, falling back to TFJS runtime:",e),x=await S.createDetector(S.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),console.log("TFJS detector created successfully")}return!0}catch(e){return console.error("Failed to load TensorFlow dependencies:",e),g=null,!1}}function d(e){return!(!e||0===e.length)&&22===e.filter(e=>e[2]>.7).length}return t.useEffect(()=>{if(l.current=!0,!x)return g||(g=u()),g.then(e=>{e&&l.current&&o(!0)}),()=>{l.current=!1};o(!0)},[]),t.useEffect(()=>{i.current=e,e>6&&c.current<2&&(a(e=>e+1),s(0))},[e]),t.useEffect(()=>{c.current=n},[n]),{poseDetector:async(e,t)=>{if(!x||!l.current||!t?.current?.video)return;const n=t.current.video;if(!(n.readyState<2))try{const t=await x.estimatePoses(n,{flipHorizontal:!1});if(!t||!t.length)return;const a=t[0].keypoints.slice(11).map(e=>[e.x>0&&e.x<720?e.x:-1,e.y>0&&e.y<1280?e.y:-1,e.score??0]);0!==c.current||d(a)||s(e=>e+1),1===c.current&&d(a)&&s(e=>e+1),2===c.current&&e()}catch(e){console.error("Pose detection error:",e)}},isLoaded:r,spinPhase:n,resetDetector:()=>{c.current=0,i.current=0,s(0),a(0)},retryLoading:async()=>{x||g||(g=u(),await g&&l.current&&o(!0))}}}(),te=t.useRef(!0),se=t.useRef(!1),ne=t.useRef(0),ae=t.useRef(0),re=t.useRef(0),oe=t.useRef(0),ce=t.useRef(!1),ie=t.useRef(!1),le=t.useRef(!1),ue=t.useRef(()=>{}),de=t.useRef(()=>{}),me=t.useRef(null),[pe,fe]=t.useState([]),[he,ge]=t.useState(0),[xe,Se]=t.useState(s.videoConstraintsExact),{setStartGyro:ve,uploadScanFile:ye,setUploadLoading:be,swan:Ce,onScanStart:we,onCaptureComplete:je}=t.useContext(s.ParamsContext),ke=t.useRef(r);t.useEffect(()=>{ke.current=r},[r]);const Ee=t.useRef(J);t.useEffect(()=>{Ee.current=J},[J]);const Ne=function({timeoutMs:e,onTimeout:s}){const n=t.useRef(null),a=t.useRef(s);t.useEffect(()=>{a.current=s},[s]);const r=t.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null)},[]),o=t.useCallback(()=>{n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{n.current=null,a.current()},e)},[e]);return t.useEffect(()=>r,[r]),{start:o,pet:o,stop:r}}({timeoutMs:12e3,onTimeout:t.useCallback(()=>{s.posthog.capture(`${m}/pose_feedback_timeout`,{scanID:ke.current,email:d,framesSent:re.current,id:me.current})},[m,d])}),Te=()=>{se.current=!1,Ne.stop(),clearTimeout(v),R.current&&clearTimeout(R.current),l(s.generateUuid()),c(""),be?.(!1),k([]),w.current=null,N(!0),D(!1),_(!1),M(!0),P(!1),R.current=null,A(""),O([]),z(""),q(!K),ve(!1),s.speechService.stopAudio(),W(!1),G(!1),ne.current=0,ae.current=0,re.current=0,oe.current=0,ce.current=!1,le.current=!1,null!==C.current&&C.current.stop(),J.forEach(e=>{C.current&&C.current.removeEventListener("dataavailable",e)}),Q([]),Z.current=!0,Y(!1),o(!1),b.current?.stream&&N(!1)},De=t.useCallback(()=>{setTimeout(()=>{N(!1)},1e3)},[]),Ie=t.useCallback(e=>{if(console.log("camera error",e),xe===s.videoConstraintsExact)return Se(s.videoConstraintsFallback),void ge(e=>e+1);N(!1)},[xe]),_e=t.useCallback(()=>{Z.current=!1,Ne.stop(),G(!0),Y(!1),R.current&&clearTimeout(R.current),C.current&&C.current.pause(),s.speechService.stopAudio(),Ce.poseDetection.disconnect(),s.posthog.capture(`${m}/pose_detection_disconnected`,{scanID:r,email:d,id:me.current,reason:"pause"}),ne.current=0,ae.current=0,ce.current=!1,le.current=!1,C.current&&C.current.stop(),J.forEach(e=>{C.current&&C.current.removeEventListener("dataavailable",e)}),Q([]),clearTimeout(v)},[C,J,s.speechService,Z]),Le=t.useMemo(()=>s.getPreferredMediaRecorderTypes(),[]),Me=s.getRecordingMimeType(pe),Fe=s.getRecordingExtension(Me),Pe=t.useCallback(async()=>{Z.current=!0,await s.speechService.playAudio(`${s.voiceOverAssetsPath}SpotOn.mp3`),G(!1),Y(!1),R.current&&clearTimeout(R.current),D(!1)},[R,s.speechService]),Re=t.useCallback(async()=>{if(!ie.current&&!me.current){ie.current=!0;try{me.current=await Ce.poseDetection.connect(),s.posthog.capture(`${m}/pose_detection_connected`,{scanID:ke.current,email:d,id:me.current})}catch(e){console.log(e,"while connecting websocket"),s.posthog.capture(`${m}/pose_detection_connect_failed`,{scanID:r,email:d,error:String(e)})}finally{ie.current=!1}}},[r,m,d]),$e=t.useCallback(({data:e})=>{e&&e.size>0&&Z.current&&(k(t=>t.concat(e)),!se.current&&b.current&&(se.current=!0,ee(()=>{Pe(),s.handleScanTimeCapture({eventName:`${m}/tensorFlow`,scanID:ke.current,email:d,message:"recording stopped by tensorflow "})},b)))},[Pe,s.handleScanTimeCapture,m,d,b]),Ae=t.useCallback(async()=>{const e=U[U.length-1];e&&Z.current&&(await s.speechService.playAudio(s.voiceOverAssetsPath+e),Z.current&&(v=setTimeout(Ae,2e3)))},[U,Z]),Ue=t.useCallback(()=>{C&&C.current&&C.current.stop(),D(!0);try{if(b&&b.current&&b.current.stream){const e=b.current.stream.getVideoTracks()[0];if(e){const t=e.getSettings();w.current=t.frameRate||null}const t={videoBitsPerSecond:15e5};pe[0]&&(t.mimeType=pe[0]),C.current=new MediaRecorder(b.current.stream,t),C.current.addEventListener("dataavailable",$e),C.current.addEventListener("stop",()=>{M(!0)}),Q([...J,$e]),C.current.start(1e3),M(!1)}}catch(e){console.log("error while using media recorder",e)}},[b,pe,$e,J]),Oe=t.useCallback(async()=>{R.current&&clearTimeout(R.current),Ue(),Z.current&&(R.current=setTimeout(async()=>{Z.current&&(await s.speechService.playAudio(`${s.voiceOverAssetsPath}SpotOn.mp3`),D(!1))},15e3)),_(!0),Z.current&&await s.speechService.playAudio(`${s.voiceOverAssetsPath}Spin.mp3`)},[Ue,Z,s.speechService]);t.useEffect(()=>{ue.current=Oe},[Oe]);const Be=t.useCallback(({data:e})=>{const t=Ce.poseDetection.connected();if(e.size>0&&t){ce.current||(ce.current=!0,Ce.poseDetection.poseStatus(async e=>{if(Ne.pet(),s.posthog.capture(`${m}/pose_instruction_received`,{scanID:ke.current,email:d,audio:e?.audio??"",audioEmpty:!(e?.audio&&e.audio.length>0),status:e?.status,sid:e?.sid,sidMatchesConnection:e?.sid===me.current,counter:ne.current,consecutiveFalse:ae.current,type:"body_scan_instruction"}),e&&e.audio&&e.audio.length>0){const t=document.querySelector("#audioElement");!0===e.status&&e.sid===me.current?(ae.current=0,ne.current<2?(ne.current+=1,1!==ne.current||le.current?2===ne.current&&t?.paused&&(clearTimeout(v),s.speechService.playAudio(s.voiceOverAssetsPath+e.audio)):(le.current=!0,clearTimeout(v),s.speechService.stopAudio(),await s.speechService.playAudio(s.voiceOverAssetsPath+e.audio))):(Ne.stop(),z(e.audio),clearTimeout(v),Ce.poseDetection.disconnect(),s.posthog.capture(`${m}/pose_detection_disconnected`,{scanID:r,email:d,id:me.current,reason:"pose_confirmed"}),ce.current=!1,setTimeout(()=>ue.current(),1e3))):(ae.current+=1,ae.current>=3&&(ne.current=0,le.current=!1),!t?.paused||y&&y?.audioName===e.audio?y?.audioName===e.audio&&t?.paused&&(y&&y.no_of_times_skipped>=y.skipCount?(y.no_of_times_skipped=0,s.speechService.playAudio(s.voiceOverAssetsPath+e.audio)):y&&(y.no_of_times_skipped+=1)):(y={skipCount:2,no_of_times_skipped:0,audioName:e.audio},s.speechService.playAudio(s.voiceOverAssetsPath+e.audio)))}}));const e=b?.current?b.current.getScreenshot():null;e?(re.current+=1,1===re.current&&Ne.start(),Ce.poseDetection.videoEmit({image:e,scanId:ke.current}),1!==re.current&&re.current%5!=0||s.posthog.capture(`${m}/pose_frame_sent`,{scanID:ke.current,email:d,sid:me.current,framesSent:re.current})):(oe.current+=1,1!==oe.current&&oe.current%5!=0||s.posthog.capture(`${m}/pose_frame_skipped_null`,{scanID:ke.current,email:d,framesSkipped:oe.current}))}},[b,r,Ce,s.speechService,m,d]),ze=t.useCallback(async()=>{P(!0),ve(!0),we?.(),te.current&&(te.current=!1,s.handleScanTimeCapture({eventName:"scan started",scanID:ke.current,status:"success",email:d})),i(s.getCurrentTimeInSeconds()),N(!0),Z.current&&await s.speechService.playAudio(`${s.voiceOverAssetsPath}StartScan.mp3`),Z.current&&await s.speechService.playAudio(`${s.voiceOverAssetsPath}LiftArmsAndHoldAtHip.mp3`),Z.current&&(P(!1),D(!0),W(!0),Y(!0),De());try{if(b&&b.current&&b.current.stream&&Z.current){const e=b.current.stream.getVideoTracks()[0];if(e){const t=e.getSettings();w.current=t.frameRate||null}const t={videoBitsPerSecond:15e5};pe[0]&&(t.mimeType=pe[0]),Z.current&&(C.current=new MediaRecorder(b.current.stream,t)),Z.current&&C.current&&C.current.addEventListener("dataavailable",Be),Q([...Ee.current,Be]),C.current&&C.current.start(1e3),M(!1),Z.current&&(v=setTimeout(Ae,2e3))}}catch(e){console.log("error ----------",e)}},[b,pe,Be,Ae,Z,we]);return t.useEffect(()=>{de.current=ze},[ze]),t.useEffect(()=>(m&&(n(!0),Re()),()=>{const e=me.current;me.current=null,e&&(Ce.poseDetection.disconnect(),s.posthog.capture(`${m}/pose_detection_disconnected`,{scanID:ke.current,email:d,id:e,reason:"unmount"})),J.forEach(e=>{C?.current?.removeEventListener("dataavailable",e)})}),[m]),t.useEffect(()=>{U.push($)},[$]),t.useEffect(()=>{O([])},[B]),t.useEffect(()=>{const e=j.length&&j.length>0;L||!e||T||!Z.current||H||C&&C.current&&(T||C.current.stop())},[L,T,j,H]),t.useEffect(()=>{const e=j.length&&j.length>0;if(L&&e&&!T&&C&&C.current&&Z.current&&!H&&!T){const e=new File(j,`${r}.${Fe}`,{type:Me});je?.(),be?.(!0),c(""),ye?.(e,w.current)}},[L,T,j,H,C,Z]),t.useEffect(()=>{de.current=ze},[ze]),t.useEffect(()=>{const e=s.getSupportedMediaRecorderTypes(Le,s.videoTypes);fe(e)},[Le]),t.useEffect(()=>{Te()},[]),e.jsx(h,{resetDetector:a,resetScan:Te,loadingCam:E,onPause:_e,showRestart:V,pause:H,onReScan:async()=>{s.rescanSupportCaptureEvent({eventName:`${m}/rescan`,email:d,scanID:ke.current,height:f,gender:p,status:!1}),Ce.poseDetection.disconnect(),Te(),await Re()},recordingStarted:T,isScanning:F,startSendingVideoFrames:ze,faceDone:I,stopRecording:Pe,showPause:X,webcamRef:b,onUserMedia:De,onUserMediaError:Ie,videoConstraints:xe,webcamKey:he})});function C({config:n}){const{scanUniqueKey:a,userDetails:r,setIsVideoUploaded:o,setScanFailsError:c,setScanStartTime:i,setScanUniqueKey:l}=t.useContext(s.ParamsContext),[u,d]=t.useState(90),[m,p]=t.useState(0),[h,g]=t.useState(null),[x,S]=t.useState(!1),[v,y]=t.useState(0),C=t.useRef([]),[w,j]=t.useState(!1),k=u-m,E=k>=80&&k<=95;t.useEffect(()=>{if("undefined"!=typeof window&&window.DeviceOrientationEvent){const e=e=>{if(null!==e.beta){let t=Math.abs(e.beta);null!==e.gamma&&(t*=Math.cos(e.gamma*Math.PI/180)),t=Math.max(0,Math.min(180,t)),d(t)}},t=async()=>{const t=DeviceOrientationEvent;if(t&&"function"==typeof t.requestPermission)try{"granted"===await t.requestPermission()&&window.addEventListener("deviceorientation",e)}catch(e){console.error("Permission error",e)}else window.addEventListener("deviceorientation",e);return()=>{e&&window.removeEventListener("deviceorientation",e)}};document.addEventListener("click",t,{once:!0})}},[]),t.useEffect(()=>{if(C.current=[...C.current.slice(-4),k],C.current.length>=5){const e=Math.max(...C.current)-Math.min(...C.current);y(E&&e<2?e=>Math.min(100,e+10):e=>Math.max(0,e-20))}E||null===h&&!x||T()},[k,E,h,x]),t.useEffect(()=>{v>=100&&null===h&&!x&&N(),v<50&&null!==h&&T()},[v,h,x]);const N=()=>{g(3);const e=setInterval(()=>{g(t=>null===t||t<=1?(clearInterval(e),S(!0),null):t-1)},1e3)},T=()=>{g(null),w||S(!1)};return e.jsx(f,{angle:k,countdown:h,isScanning:x,isInTargetRange:E,stabilityScore:v,children:x&&e.jsx(b,{setIsScanLocked:j,resetDetector:()=>{d(90),p(0),g(null),S(!1),y(0),j(!1),C.current=[]},scanID:a,userDetails:r,setIsVideoUploaded:o,setScanFailsError:c,setScanStartTime:i,setScanUniqueKey:l})})}function w({setShowDrawer:n,loader:r}){const[o,c]=t.useState({disabled:!1,message:""}),[i,l]=t.useState(!0),u=t.useRef(null),d=t.useCallback(async()=>{const e=await s.checkCameraPermission();c(e),l(!1)},[]);return t.useEffect(()=>{d()},[]),i?e.jsx(s.LoadingScreen,{url:r,loaderType:"black"}):o?.disabled?e.jsx(s.Modal,{reason:o?.reason}):e.jsx(a,{audio:!1,ref:u,screenshotQuality:1,videoConstraints:s.videoConstraints,mirrored:!0,poster:s.transparentPoster,onUserMedia:()=>n?.(!0),screenshotFormat:"image/jpeg",style:{position:"fixed",top:0,left:0,right:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}})}function j({link:n,onReady:a,wrapperClassName:r="[&_video]:rounded-t-[20px] w-full h-full"}){const o=t.useRef(null),i=t.useRef(null);let l={autoplay:!0,controls:!1,responsive:!0,fluid:!0,muted:!0,navigationUI:"hide",preload:"auto",poster:s.videoPoster};return t.useEffect(()=>{if(!i.current&&n&&o?.current){const e=c(o.current,{...l});e.ready(()=>{i.current=e;const t={...l,sources:[{src:n,type:"application/x-mpegURL"}]};e.autoplay(t.autoplay),e.src(t.sources),a?.(e)})}},[n,o]),t.useEffect(()=>{const e=i.current;return()=>{e&&!e.isDisposed()&&(e.dispose(),i.current=null)}},[i]),e.jsx("div",{className:r,children:e.jsx("video",{ref:o,muted:!0,className:"video-js",playsInline:!0,onDrag:e=>e.preventDefault()})})}function k({scanFailsError:n,onNext:a,gender:c,setScanUniqueKey:i,setIsVideoUploaded:l}){const{translate:u}=t.useContext(s.LanguageContext)||{},d=s.useConfig(),[m,p]=t.useState(!1),f=()=>{p(!m)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{"data-testid":"scan-error-message",className:"flex common-ui-main flex-col h-full max-w-[28rem] mx-auto w-full rounded-t-[20px] overflow-y-auto",style:{background:d?.style?.base?.backgroundColor},children:[e.jsx("div",{className:"w-full max-w-[28rem] mx-auto pt-[1rem] px-[1rem]",children:e.jsx(s.Header,{noTitle:!0})}),e.jsx("div",{className:"flex-1",children:n&&e.jsxs("div",{className:"px-[1rem]",children:[e.jsx("h2",{className:"text-center",style:{fontFamily:d?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:d?.style?.heading?.headingFontSize||"32px",color:d?.style?.heading?.headingColor||"#000",fontWeight:d?.style?.heading?.headingFontWeight||"normal"},children:u?.(s.LanguageKeys.issueWithScan)}),e.jsx("p",{style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:d?.style?.base?.baseFontSize||"16px",color:d?.style?.base?.baseTextColor||"#1E1E1E"},children:u?.(s.LanguageKeys.reason)}),e.jsx("p",{style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:d?.style?.base?.baseFontSize||"16px",color:d?.style?.base?.baseTextColor||"#1E1E1E"},children:s.handleErrorMessage(n)}),e.jsx("img",{className:"my-[0.5rem] aspect-[2/1.4] w-full object-cover",onClick:f,src:s.VIDEO_POSTER_GENDER_BASED[c],alt:"icon"})]})}),n&&e.jsx("div",{className:"p-[1rem] flex gap-[0.5rem]",children:e.jsx(s.SpecificButton,{"data-testid":"scan-again-btn",disabled:!1,buttonText:u?.(s.LanguageKeys.scanAgain),className:"!shadow-none",buttonFunc:()=>{a?a?.():i?.(s.generateUuid()),l?.(!1)}})})]}),m&&e.jsxs(o.Dialog,{className:"w-screen h-screen video-modal",onClose:f,open:m,children:[e.jsx("div",{className:"flex justifyEnd ",children:e.jsx("span",{className:"closeBtn",onClick:f,children:e.jsx(r.X,{className:"absolute right-[8px] top-[8px] text-white z-[9]"})})}),e.jsx("div",{className:"aspect-video object-cover rounded-[20px] ",children:e.jsx(j,{link:c?s.GENDER[c].PRE_LINK:s.GENDER.male.PRE_LINK,wrapperClassName:"w-screen h-screen fixed top-[0] left-[0]"})})]})]})}function E({scanId:n,userDetails:a,config:r,isVideoUploadedCorrect:c,isMeasurementAvailable:i,onComplete:l,isSuccess:u,onCustomScanSuccess:d,swan:m}){const{gender:p,shopDomain:f,heightInCm:h,deviceFocalLength:g,userName:x,email:S,scanType:v}=a||{},y=[s.CLOTHING_CUSTOM_SCAN,s.CLOTHING_BANNER_SCAN,s.CLOTHING_CUSTOM_FIT_SCAN].includes(v??""),[b,C]=t.useState(!0),j=t.useCallback(async()=>{try{(y||v===s.CLOTHING_TRYON_CONSUMER_SCAN)&&(await(m?.auth.addUser({scanId:n,email:S,name:x,gender:p,height:h})),d?.()),s.posthog.capture(f??"",{scanID:n,email:S,height:h,focalLength:g,clothesFit:"0",gender:p})}catch(e){console.log(e)}},[y]),{translate:k}=t.useContext(s.LanguageContext)||{};t.useEffect(()=>{(c||i)&&j()},[c,i]);const E=(u||c||i)&&!y;return e.jsx(o.Box,{className:"flex h-full w-full flex-col common-ui-main",children:e.jsxs("div",{className:"h-full w-full flex-col items-center justify-center flex",children:[e.jsx(w,{loader:r?.loader,setShowDrawer:C}),e.jsx(o.Drawer,{open:b,onClose:(e,t)=>{},className:"camera-drawer",anchor:"bottom",children:e.jsx("div",{className:"max-w-[28rem] mx-auto w-full h-full flex text-center flex-col justify-between items-center bg-primary rounded-t-[30px] p-[1rem]",style:{background:r?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full h-full flex flex-col",children:[e.jsx(s.Header,{title:k?.(s.LanguageKeys.measurementsBeingTaken)}),e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsx("video",{preload:"auto",className:"max-h-[calc(100vh-450px)] mx-auto w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:p===s.GenderType.Male?s.maleMeasurementProgress:s.measurementProgress,type:"video/mp4"})})}),E&&e.jsx(s.SpecificButton,{className:"!w-[180px] mx-auto",buttonText:k?.(s.LanguageKeys.next),buttonFunc:()=>{l?.()}})]})})})]})})}const N=()=>{const{userDetails:n,onRetry:a,isError:r,isSuccess:c,onScanSuccess:i,gender:l,scanUniqueKey:u,scanFailsError:d,setScanUniqueKey:m,setIsVideoUploaded:p,isMeasurementAvailable:f,isVideoUploadedCorrect:h,loading:g,showDeniedModal:x,uploadLoading:S,resetScan:v,onCustomScanSuccess:y,swan:b,onComplete:j}=t.useContext(s.ParamsContext),N=s.useConfig();return r?e.jsxs("div",{"data-scan-state":"error",children:[e.jsx(w,{}),e.jsx(o.Drawer,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e.jsx(k,{scanFailsError:d,onNext:()=>{a?.(),v()},setScanUniqueKey:m,gender:l,setIsVideoUploaded:p})})]}):c?e.jsx("div",{"data-scan-state":"success",children:e.jsx(E,{isSuccess:!0,onComplete:j})}):g?e.jsx("div",{"data-scan-state":"loading",className:"flex top-0 !mt-0 left-0 z-[999] absolute justify-center items-center w-full h-full",style:{background:N?.style?.base?.backgroundColor},children:e.jsx(s.LoadingScreen,{url:N?.loader,loaderType:"black"})}):x.disabled?e.jsx("div",{"data-scan-state":"camera-denied",children:e.jsx(s.Modal,{reason:x.reason})}):S||d||f||h?(S||f||h)&&!d?e.jsx("div",{"data-scan-state":"processing",children:e.jsx(E,{scanId:u,isMeasurementAvailable:f,userDetails:n,isVideoUploadedCorrect:h,onCustomScanSuccess:y,swan:b,onComplete:j,config:N})}):e.jsxs("div",{"data-scan-state":"error-retry",children:[e.jsx(w,{}),e.jsx(o.Drawer,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e.jsx(k,{scanFailsError:d,onNext:()=>{a?.(),v()},setScanUniqueKey:m,gender:l,setIsVideoUploaded:p})})]}):e.jsx("div",{"data-scan-state":"scanning",children:e.jsx(C,{config:N})})},T=n=>{const{config:a,onRetry:r,onScanStart:o,onCaptureComplete:c,onUploadStart:i,onUploadEnd:l,onMeasurementSocketStart:u,onMeasurementSocketClose:d,onIntermediateScanSuccess:p,onScanError:f,onScanSuccess:h,onCustomScanSuccess:g,onComplete:x,isError:S,isSuccess:v}=n,y={email:"",shopDomain:"",gender:"male",heightInCm:0,scanType:"",deviceFocalLength:0,deviceModelName:"",sourceTag:"",callbackUrl:null,...n.userDetails??{}},b=n.token??"",{gender:C,scanType:w,shopDomain:j,heightInCm:k,email:E,deviceFocalLength:T,deviceModelName:D,callbackUrl:I,sourceTag:_}=y,L=t.useMemo(()=>s.getSwanService(b),[b]),[M,F]=t.useState(!1),[P,R]=t.useState(!1),[$,A]=t.useState(!1),[U,O]=t.useState({disabled:!1,message:""}),[B,z]=t.useState(""),[K,q]=t.useState(!1),[V,W]=t.useState(!0),[H,G]=t.useState(!1),[J,Q]=t.useState(""),[X,Y]=t.useState(s.getCurrentTimeInSeconds()),{gyroData:Z}=function(e){const[s,n]=t.useState([]),[a,r]=t.useState(!1),o=t.useCallback(e=>{try{const{alpha:t,beta:s,gamma:a}=e;n(e=>[...e,{alpha:t?.toString()||void 0,beta:s?.toString()||void 0,gamma:a?.toString()||void 0,timestamp:(new Date).toISOString()}])}catch(e){console.log(e)}},[]),c=t.useCallback(async()=>{const e=DeviceOrientationEvent;if(void 0!==e&&"function"==typeof e.requestPermission)try{"granted"===await e.requestPermission()?r(!0):console.warn("Device orientation permission denied.")}catch(e){console.error("Error requesting device orientation permission:",e)}else r(!0)},[]);return t.useEffect(()=>(e&&a?window.addEventListener("deviceorientation",o):n([]),()=>{window.removeEventListener("deviceorientation",o)}),[e,a,o]),t.useEffect(()=>{e&&c()},[e,c]),{gyroData:s}}(H);s.usePosthogPageview();const ee=t.useCallback(()=>{Q(s.generateUuid()),z(""),F(!1),q(!1)},[]),te=()=>{Y(null),Q("")},se=t.useCallback(async e=>{if(e&&"success"===e?.scanStatus&&"intermediate"===e?.resultType&&200===e?.code)return s.handleScanTimeCapture({eventName:`${j}/measurement_success/intermediate`,scanID:J,status:"success",email:E}),R(!0),void p?.({...e,scanId:J,email:E});h?.({...e,scanId:J,email:E}),R(!0),te();const t=J;A(!0),F(!1),s.handleScanTimeCapture({eventName:`${j}/measurement_success/fit-view`,scanID:t,status:"success",email:E}),X&&s.handleScanTimeCapture({eventName:`${j}/scan_completion_time`,scanID:t,status:"success",completionTime:s.getCurrentTimeInSeconds()-X,email:E})},[w,j,J]),ne=e=>{F(!0),z(""),L.measurement.handleMeasurementSocket({scanId:J,onPreopen:()=>{s.handleWebSocketCapture({eventName:`${j}/webSocket`,scanID:J,connection:"pre_open",type:"measurement_recommendation",email:E})},onOpen:()=>{u?.(),s.handleWebSocketCapture({eventName:`${j}/webSocket`,scanID:J,connection:"open",type:"measurement_recommendation",email:E})},onClose:()=>{d?.(),s.handleWebSocketCapture({eventName:`${j}/webSocket`,scanID:J,connection:"close",type:"measurement_recommendation",email:E})},onError:e=>{var t;t=e,f?.({...t,message:s.handleErrorMessage(t),scanId:J,email:E}),te(),A(!1),z(t),R(!1),F(!1),s.handleScanTimeCapture({eventName:`${j}/measurement_failed/fit-view`,scanID:J,status:"failed",email:E,message:s.handleErrorMessage(t)}),X&&s.handleScanTimeCapture({eventName:`${j}/scan_completion_time`,scanID:J,status:"failed",completionTime:s.getCurrentTimeInSeconds()-X,email:E}),s.handleWebSocketCapture({eventName:`${j}/webSocket`,scanID:J,connection:"error",type:"measurement_recommendation",email:E})},onSuccess:e=>{s.handleWebSocketCapture({eventName:`${j}/webSocket`,scanID:J,connection:"success",type:"measurement_recommendation",email:E}),se(e)}})},ae=t.useCallback(async(e,t)=>{const n=Number((e.size/1048576).toFixed(2)),a=null!=t?t:await s.getVideoFPS(e),r=s.createObjectMetadataArray({gender:C,focal_length:`${T}`,height:`${k}`,customer_store_url:j,clothes_fit:"0",scan_type:s.getScanType(w),callback_url:I,source_tag:_});s.handleScanTimeCapture({eventName:`${j}/body_scan_meta_data`,scanID:J,email:E,data:JSON.stringify([...r,{fileSizeInMB:n,video_fps:a||0}])}),i?.();try{await L.fileUpload.uploadFileFrontend({file:e,arrayMetaData:r,scanId:J,email:E}),await L.fileUpload.setDeviceInfo({model:D,detection:"manual",gyro:Z,scanId:J}),console.log("video successfully uploaded"),q(!1),s.handleScanTimeCapture({eventName:`${j}/scan_success`,scanID:J,status:"success",email:E,data:JSON.stringify(r)}),s.handleScanTimeCapture({eventName:"scan finished",scanID:J,status:"success",email:E}),Y(s.getCurrentTimeInSeconds()),setTimeout(()=>{q(!0)},3e3)}catch(e){s.handleScanTimeCapture({eventName:"scan finished",scanID:J,status:"failed",email:E,message:s.handleErrorMessage(e)}),s.handleScanTimeCapture({eventName:`${j}/scan_failed`,scanID:J,status:"failed",email:E,message:s.handleErrorMessage(e),data:JSON.stringify(r)}),z(s.handleErrorMessage(e)),q(!1),f?.({...e,message:s.handleErrorMessage(e),scanId:J,email:E}),te()}finally{G(!1),l?.()}},[J,Z,i,l]),re=t.useCallback(async()=>{if(+k<152.4||+k>213.36)return void f?.({message:"Height must be between 152.4cm (5ft) and 213.36cm (7ft)",scanId:J,email:E});const e=await s.checkCameraPermission();e.disabled?(s.handleScanTimeCapture({eventName:`${j}/camera_activation`,scanID:J,status:"failed",email:E}),W(!1)):(W(!1),s.handleScanTimeCapture({eventName:`${j}/camera_activation`,scanID:J,status:"success",email:E})),O(e),z(""),q(!1)},[E,J,Q,j]);return t.useEffect(()=>{S||v||j&&re()},[j,k,S,v]),t.useEffect(()=>{S||v||K&&j&&J&&ne()},[K,j,J,S,v]),e.jsx("div",{"data-testid":"body-scan-root",children:e.jsx(s.LanguageContextProvider,{children:e.jsx(s.ConfigProvider,{config:a,children:e.jsx(m,{children:e.jsx(s.ParamsContext.Provider,{value:{userDetails:y,onRetry:r,onScanError:f,isError:S,isSuccess:v,onScanSuccess:h,gender:C,scanUniqueKey:J,scanFailsError:B,setScanUniqueKey:Q,setIsVideoUploaded:q,isMeasurementAvailable:$,isVideoUploadedCorrect:P,loading:V,showDeniedModal:U,uploadLoading:M,setStartGyro:G,uploadScanFile:ae,setUploadLoading:F,resetScan:ee,setScanFailsError:z,setScanStartTime:Y,onScanStart:o,onCaptureComplete:c,onCustomScanSuccess:g,onComplete:x,swan:L},children:e.jsx(N,{})})})})})})};exports.BodyScanClientGate=s=>{const[n,a]=t.useState(!1);return t.useEffect(()=>{a(!0)},[]),n?e.jsx(T,{...s}):e.jsx("div",{"data-testid":"body-scan-root"})};
3
+ //# sourceMappingURL=BodyScan-07mCUq2m.js.map
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r,{useState as a,useCallback as s,useEffect as o,createContext as c,useLayoutEffect as i,useMemo as l,useContext as u,useRef as d}from"react";import{L as m,u as p,H as f,b as h,t as g,S as y,A as v,a as w,i as b,P as x,p as S,o as C,s as D,j as N,k as I,l as k,y as T,B as F,q as _,r as E,f as $,D as L,E as M,c as U,M as j,v as A,I as P,J as z,V,K as B,N as R,O as q,Q as K,G as O,R as W,T as H,U as J,h as G,n as Q,x as X,W as Y,w as Z,C as ee,X as te,z as ne}from"./Modal-DHcCPbXc.mjs";import re from"clsx";import ae from"react-webcam";import{X as se}from"lucide-react";import{Dialog as oe,Box as ce,Drawer as ie}from"@mui/material";import le from"video.js";const ue="DESKTOP",de="TAB",me="MOBILE",pe=c(void 0);function fe({children:t}){const[n,r]=a([window?.innerWidth,window?.innerHeight]),[s,c]=a(!1),u=()=>{r([window?.innerWidth,window?.innerHeight])};o(()=>{u()},[]),i(()=>(window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)),[u]);let d=ue;n[0]>768&&n[0]<1024&&(d=de),n[0]<768&&(d=me);const m=l(()=>({size:n,setSize:r,clearInputs:s,setClearInputs:c,media:d}),[n,s,d]);return e(pe.Provider,{value:m,children:t})}var he=r.memo(function({size:n=16}){return t("svg",{width:n,height:n,viewBox:"0 0 25 25",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M22.6968 14.6968C22.6968 16.8185 21.8539 18.8533 20.3536 20.3536C18.8533 21.8539 16.8185 22.6968 14.6968 22.6968",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M18.6968 11.6968V10.6968C18.6968 10.1663 18.4861 9.65764 18.111 9.28256C17.7359 8.90749 17.2272 8.69678 16.6968 8.69678C16.1663 8.69678 15.6576 8.90749 15.2826 9.28256C14.9075 9.65764 14.6968 10.1663 14.6968 10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M14.6968 10.6968V9.69678C14.6968 9.16634 14.4861 8.65764 14.111 8.28256C13.7359 7.90749 13.2272 7.69678 12.6968 7.69678C12.1663 7.69678 11.6576 7.90749 11.2826 8.28256C10.9075 8.65764 10.6968 9.16634 10.6968 9.69678V10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M10.6968 10.1968V4.69678C10.6968 4.16634 10.4861 3.65764 10.111 3.28256C9.73592 2.90749 9.22721 2.69678 8.69678 2.69678C8.16634 2.69678 7.65764 2.90749 7.28256 3.28256C6.90749 3.65764 6.69678 4.16634 6.69678 4.69678V14.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M18.6969 11.6968C18.6969 11.1663 18.9076 10.6576 19.2827 10.2826C19.6577 9.90749 20.1664 9.69678 20.6969 9.69678C21.2273 9.69678 21.736 9.90749 22.1111 10.2826C22.4862 10.6576 22.6969 11.1663 22.6969 11.6968V14.6968C22.6969 16.8185 21.854 18.8533 20.3537 20.3536C18.8534 21.8539 16.8186 22.6968 14.6969 22.6968H12.6969C9.89688 22.6968 8.19688 21.8368 6.70688 20.3568L3.10688 16.7568C2.76282 16.3757 2.57847 15.8769 2.592 15.3637C2.60554 14.8505 2.81593 14.3621 3.1796 13.9997C3.54327 13.6373 4.03238 13.4287 4.54565 13.417C5.05892 13.4053 5.55704 13.5914 5.93688 13.9368L7.69688 15.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})});var ge=r.memo(function({angle:n,countdown:r,isScanning:a,isInTargetRange:o,stabilityScore:c,children:i}){const{translate:d}=u(m)||{},g=p(),y=s(()=>n<80?Math.max(0,Math.min(100,10*(n-60))):n>95?Math.max(0,Math.min(100,10*(105-n))):100,[n]),v=l(()=>{if(a)return g?.style?.angleDetector?.successAngleBackground||"#4f46e5";const e=y();if(0===e)return g?.style?.angleDetector?.successAngleLowBackground||"#ffffff";if(100===e)return g?.style?.angleDetector?.successAngleBackground||"#4f46e5";return`rgb(${Math.round(255-e/100*116)}, ${Math.round(255-e/100*163)}, ${Math.round(255-e/100*9)})`},[a,y]),w=s((e,t)=>t>70?e?`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]/70`:`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]`:e?`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]/40`:`text-[${g?.style?.angleDetector?.successAngleTextDarkColor}]/70`,[]),b=s((e=!1)=>{const t=y();return a?`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]`:w(e,t)},[a,y]),x=s((e,t)=>t>70||e?g?.style?.angleDetector?.successAngleTextLightColor:g?.style?.angleDetector?.successAngleTextDarkColor,[]),S=s((e=!1)=>{const t=y();return a?g?.style?.angleDetector?.successAngleTextLightColor:x(e,t)},[a,y]),C=r;function D(){document.documentElement.style.setProperty("--real-vh",window.innerHeight+"px")}return D(),window.addEventListener("resize",D),t("div",{className:"flex common-ui-main w-screen flex-col items-center h-[var(--real-vh)] overflow-hidden touch-none justify-center transition-all duration-300 max-w-[28rem] mx-auto",style:{backgroundColor:v},"data-testid":"level-screen","data-angle-state":a?"locked":o?"target":"adjusting",children:[e("div",{className:"flex justify-start fixed top-[.5rem] max-w-[28rem] mx-auto w-full px-[1rem]",children:e("div",{className:"flex justify-start ",children:e(f,{noTitle:!0})})}),null!==C?e("div",{className:"relative flex h-[6rem] w-[6rem] items-center justify-center rounded-[9999px] bg-[#fff]/20 transition-all duration-300",style:{border:`2px solid ${S()}`},children:e("div",{className:`text-[3rem] font-bold text-[${S()}]`,style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:C})}):t("div",a?{className:"relative flex flex-col items-center justify-center",children:[e("div",{className:"relative flex h-16 w-16 items-center justify-center rounded-[9999px] border-2 bg-[#fff]/30 border-[#fff]",children:e("div",{className:"h-4 w-4 rounded-[9999px] animate-pulse bg-[#fff]/80"})}),i]}:{className:re("relative flex h-[4rem] w-[4rem] items-center justify-center rounded-[9999px] ",o?"bg-[#fff]/20 border-[#fff]":"bg-[#fff]/10 border-[#fff]"),style:{transform:`translateY(${3*(90-n)}px)`,transition:"transform 0.2s ease-out",border:`2px solid ${S()}`},children:[e("div",{className:`h-[1rem] w-[1rem] rounded-[9999px] bg-[${S()}]/80`,style:{backgroundColor:`${S()}B3`}}),t("div",{className:re("mt-[.5rem] text-center w-[180px] flex-col flex items-center absolute top-[60px]",b()),style:{color:S()},children:[e(he,{size:30}),t("p",{style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[" ",d?.(h.startLevelCheck),e("br",{})]})]})]}),null!==C&&e("div",{className:"absolute bottom-[8rem] text-center",children:e("div",{className:re("text-sm font-medium px-4 py-1.5 bg-black/20 rounded-[9999px] mt-8",b()),style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:d?.(h.leavePhone)})}),o&&null===C&&!a&&e("div",{className:"absolute bottom-[8rem] w-[12rem]",children:e("div",{className:`h-[.375rem] w-full bg-[${S()}]/20 rounded-[9999px] overflow-hidden`,style:{backgroundColor:`${S()}33`},children:e("div",{className:`h-full bg-[${S()}]/70 transition-all duration-300 rounded-[9999px]`,style:{width:`${n}%`,backgroundColor:`${S()}B3`}})})}),null===C&&!a&&e("div",{className:"absolute bottom-[5rem] text-center",children:t("div",{className:re("text-[1.5rem] font-light",b()),style:{color:S(),fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[Math.round(n),"°"]})}),null===C&&!a&&e("div",{className:"absolute bottom-[2rem] text-center max-w-[20rem] mx-auto",children:e("div",{className:re("text-[.75rem] opacity-50",b()),style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:d?.(h.placePhoneUpright)})})]})});function ye({resetScan:n,loadingCam:r,onUserMedia:a,onPause:s,pause:o,onReScan:c,recordingStarted:i,startSendingVideoFrames:l,showPause:d,webcamRef:p,onUserMediaError:f,resetDetector:b,videoConstraints:x,webcamKey:S,faceDone:C,isScanning:D}){const{media:N}=u(pe)||{},{translate:I}=u(m)||{};return t("div",{className:"App w-screen h-[100vh] relative common-ui-main","data-testid":"camera-scan","data-scan-phase":C?"spinning":i?"pose-detecting":D?"starting":"ready",children:[e("span",{onClick:()=>{n(),b()},className:"fixed right-[20px] top-[20px] z-[999]",children:e(se,{className:"text-[#fff]"})}),e("div",{className:"w-full h-full overflow-hidden ",children:N===me&&e(ae,{audio:!1,ref:p,screenshotQuality:1,videoConstraints:x,mirrored:!0,screenshotFormat:"image/jpeg",poster:g,onUserMedia:a,onUserMediaError:f,style:{position:"fixed",top:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}},S)}),t("div",{className:"fixed bottom-[30px] w-full z-[999] flex flex-col gap-4 items-center justify-center",children:[d&&e(y,{className:"!w-[180px] !h-[40px] !py-[0] mx-auto ",prefix:v,buttonText:I?.(h.pause),buttonFunc:s,btnSecondary:!0}),o?e("div",{children:e(y,{className:"!w-[180px] !h-[40px] !py-[0] mx-auto",buttonText:I?.(h.restart),buttonFunc:c,btnSecondary:!0})}):i?null:e(y,{"data-testid":"start-scan-btn",className:"!w-[180px] !h-[40px] !py-[0] mx-auto !bg-[#ffffff] !text-[#000000] "+(r?"!opacity-50":""),buttonText:I?.(h.startScan),buttonFunc:l,disabled:r})]}),e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:`${w}scanAudioInstructions/silence.mp3`})]})}let ve=null,we=null,be=null;let xe,Se=null;var Ce=r.memo(function({setIsScanLocked:t,resetDetector:n,scanID:r,setIsVideoUploaded:c,setScanFailsError:i,setScanStartTime:m,setScanUniqueKey:p,userDetails:f}){const{email:h,shopDomain:g,gender:y,heightInCm:v}=f,M=d(null),U=d(null),j=d(null),[A,P]=a([]),[z,V]=a(!0),[B,R]=a(!1),[q,K]=a(!1),[O,W]=a(!0),[H,J]=a(!1),G=d(null),[Q,X]=a(""),[Y,Z]=a([]),[ee,te]=a(""),[ne,re]=a(!1),[ae,se]=a(!1),[oe,ce]=a(!1),[ie,le]=a([]),[ue,de]=a(!1),me=d(!0),{poseDetector:pe}=function(){const[e,t]=a(0),[n,r]=a(0),[s,c]=a(!1),i=d(0),l=d(0),u=d(!0);async function m(){if("undefined"==typeof window||"undefined"==typeof navigator)return!1;try{console.log("Starting TensorFlow preload...");const[e,t,n]=await Promise.all([import("./pose-detection.esm-CahFpbbr.mjs"),import("@tensorflow/tfjs-core"),import("@tensorflow/tfjs-backend-webgl")]);be=e;const r=t.getBackend();if(r)await t.ready(),console.log(`TensorFlow backend already active (${r})`);else{let e=!1;try{e=await t.setBackend("webgl")}catch(e){console.warn("WebGL backend threw during init:",e)}e||(console.warn("WebGL unavailable, falling back to CPU backend"),await t.setBackend("cpu")),await t.ready(),console.log(`TensorFlow backend ready (${t.getBackend()})`)}const a={runtime:"mediapipe",modelType:"full",solutionPath:"https://cdn.jsdelivr.net/npm/@mediapipe/pose"};try{we=await be.createDetector(be.SupportedModels.BlazePose,a),console.log("MediaPipe detector created successfully")}catch(e){console.warn("MediaPipe failed, falling back to TFJS runtime:",e),we=await be.createDetector(be.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),console.log("TFJS detector created successfully")}return!0}catch(e){return console.error("Failed to load TensorFlow dependencies:",e),ve=null,!1}}function p(e){return!(!e||0===e.length)&&22===e.filter(e=>e[2]>.7).length}return o(()=>{if(u.current=!0,!we)return ve||(ve=m()),ve.then(e=>{e&&u.current&&c(!0)}),()=>{u.current=!1};c(!0)},[]),o(()=>{l.current=e,e>6&&i.current<2&&(r(e=>e+1),t(0))},[e]),o(()=>{i.current=n},[n]),{poseDetector:async(e,n)=>{if(!we||!u.current||!n?.current?.video)return;const r=n.current.video;if(!(r.readyState<2))try{const n=await we.estimatePoses(r,{flipHorizontal:!1});if(!n||!n.length)return;const a=n[0].keypoints.slice(11).map(e=>[e.x>0&&e.x<720?e.x:-1,e.y>0&&e.y<1280?e.y:-1,e.score??0]);0!==i.current||p(a)||t(e=>e+1),1===i.current&&p(a)&&t(e=>e+1),2===i.current&&e()}catch(e){console.error("Pose detection error:",e)}},isLoaded:s,spinPhase:n,resetDetector:()=>{i.current=0,l.current=0,t(0),r(0)},retryLoading:async()=>{we||ve||(ve=m(),await ve&&u.current&&c(!0))}}}(),fe=d(!0),he=d(!1),ge=d(0),Ce=d(0),De=d(0),Ne=d(0),Ie=d(!1),ke=d(!1),Te=d(!1),Fe=d(()=>{}),_e=d(()=>{}),Ee=d(null),[$e,Le]=a([]),[Me,Ue]=a(0),[je,Ae]=a(b),{setStartGyro:Pe,uploadScanFile:ze,setUploadLoading:Ve,swan:Be,onScanStart:Re,onCaptureComplete:qe}=u(x),Ke=d(r);o(()=>{Ke.current=r},[r]);const Oe=d(ie);o(()=>{Oe.current=ie},[ie]);const We=function({timeoutMs:e,onTimeout:t}){const n=d(null),r=d(t);o(()=>{r.current=t},[t]);const a=s(()=>{n.current&&(clearTimeout(n.current),n.current=null)},[]),c=s(()=>{n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{n.current=null,r.current()},e)},[e]);return o(()=>a,[a]),{start:c,pet:c,stop:a}}({timeoutMs:12e3,onTimeout:s(()=>{S.capture(`${g}/pose_feedback_timeout`,{scanID:Ke.current,email:h,framesSent:De.current,id:Ee.current})},[g,h])}),He=()=>{he.current=!1,We.stop(),clearTimeout(xe),G.current&&clearTimeout(G.current),p($()),i(""),Ve?.(!1),P([]),j.current=null,V(!0),R(!1),K(!1),W(!0),J(!1),G.current=null,X(""),Z([]),te(""),re(!ne),Pe(!1),D.stopAudio(),se(!1),ce(!1),ge.current=0,Ce.current=0,De.current=0,Ne.current=0,Ie.current=!1,Te.current=!1,null!==U.current&&U.current.stop(),ie.forEach(e=>{U.current&&U.current.removeEventListener("dataavailable",e)}),le([]),me.current=!0,de(!1),c(!1),M.current?.stream&&V(!1)},Je=s(()=>{setTimeout(()=>{V(!1)},1e3)},[]),Ge=s(e=>{if(console.log("camera error",e),je===b)return Ae(C),void Ue(e=>e+1);V(!1)},[je]),Qe=s(()=>{me.current=!1,We.stop(),ce(!0),de(!1),G.current&&clearTimeout(G.current),U.current&&U.current.pause(),D.stopAudio(),Be.poseDetection.disconnect(),S.capture(`${g}/pose_detection_disconnected`,{scanID:r,email:h,id:Ee.current,reason:"pause"}),ge.current=0,Ce.current=0,Ie.current=!1,Te.current=!1,U.current&&U.current.stop(),ie.forEach(e=>{U.current&&U.current.removeEventListener("dataavailable",e)}),le([]),clearTimeout(xe)},[U,ie,D,me]),Xe=l(()=>N(),[]),Ye=I($e),Ze=k(Ye),et=s(async()=>{me.current=!0,await D.playAudio(`${w}SpotOn.mp3`),ce(!1),de(!1),G.current&&clearTimeout(G.current),R(!1)},[G,D]),tt=s(async()=>{if(!ke.current&&!Ee.current){ke.current=!0;try{Ee.current=await Be.poseDetection.connect(),S.capture(`${g}/pose_detection_connected`,{scanID:Ke.current,email:h,id:Ee.current})}catch(e){console.log(e,"while connecting websocket"),S.capture(`${g}/pose_detection_connect_failed`,{scanID:r,email:h,error:String(e)})}finally{ke.current=!1}}},[r,g,h]),nt=s(({data:e})=>{e&&e.size>0&&me.current&&(P(t=>t.concat(e)),!he.current&&M.current&&(he.current=!0,pe(()=>{et(),T({eventName:`${g}/tensorFlow`,scanID:Ke.current,email:h,message:"recording stopped by tensorflow "})},M)))},[et,T,g,h,M]),rt=s(async()=>{const e=Y[Y.length-1];e&&me.current&&(await D.playAudio(w+e),me.current&&(xe=setTimeout(rt,2e3)))},[Y,me]),at=s(()=>{U&&U.current&&U.current.stop(),R(!0);try{if(M&&M.current&&M.current.stream){const e=M.current.stream.getVideoTracks()[0];if(e){const t=e.getSettings();j.current=t.frameRate||null}const t={videoBitsPerSecond:15e5};$e[0]&&(t.mimeType=$e[0]),U.current=new MediaRecorder(M.current.stream,t),U.current.addEventListener("dataavailable",nt),U.current.addEventListener("stop",()=>{W(!0)}),le([...ie,nt]),U.current.start(1e3),W(!1)}}catch(e){console.log("error while using media recorder",e)}},[M,$e,nt,ie]),st=s(async()=>{G.current&&clearTimeout(G.current),at(),me.current&&(G.current=setTimeout(async()=>{me.current&&(await D.playAudio(`${w}SpotOn.mp3`),R(!1))},15e3)),K(!0),me.current&&await D.playAudio(`${w}Spin.mp3`)},[at,me,D]);o(()=>{Fe.current=st},[st]);const ot=s(({data:e})=>{const t=Be.poseDetection.connected();if(e.size>0&&t){Ie.current||(Ie.current=!0,Be.poseDetection.poseStatus(async e=>{if(We.pet(),S.capture(`${g}/pose_instruction_received`,{scanID:Ke.current,email:h,audio:e?.audio??"",audioEmpty:!(e?.audio&&e.audio.length>0),status:e?.status,sid:e?.sid,sidMatchesConnection:e?.sid===Ee.current,counter:ge.current,consecutiveFalse:Ce.current,type:"body_scan_instruction"}),e&&e.audio&&e.audio.length>0){const t=document.querySelector("#audioElement");!0===e.status&&e.sid===Ee.current?(Ce.current=0,ge.current<2?(ge.current+=1,1!==ge.current||Te.current?2===ge.current&&t?.paused&&(clearTimeout(xe),D.playAudio(w+e.audio)):(Te.current=!0,clearTimeout(xe),D.stopAudio(),await D.playAudio(w+e.audio))):(We.stop(),te(e.audio),clearTimeout(xe),Be.poseDetection.disconnect(),S.capture(`${g}/pose_detection_disconnected`,{scanID:r,email:h,id:Ee.current,reason:"pose_confirmed"}),Ie.current=!1,setTimeout(()=>Fe.current(),1e3))):(Ce.current+=1,Ce.current>=3&&(ge.current=0,Te.current=!1),!t?.paused||Se&&Se?.audioName===e.audio?Se?.audioName===e.audio&&t?.paused&&(Se&&Se.no_of_times_skipped>=Se.skipCount?(Se.no_of_times_skipped=0,D.playAudio(w+e.audio)):Se&&(Se.no_of_times_skipped+=1)):(Se={skipCount:2,no_of_times_skipped:0,audioName:e.audio},D.playAudio(w+e.audio)))}}));const e=M?.current?M.current.getScreenshot():null;e?(De.current+=1,1===De.current&&We.start(),Be.poseDetection.videoEmit({image:e,scanId:Ke.current}),1!==De.current&&De.current%5!=0||S.capture(`${g}/pose_frame_sent`,{scanID:Ke.current,email:h,sid:Ee.current,framesSent:De.current})):(Ne.current+=1,1!==Ne.current&&Ne.current%5!=0||S.capture(`${g}/pose_frame_skipped_null`,{scanID:Ke.current,email:h,framesSkipped:Ne.current}))}},[M,r,Be,D,g,h]),ct=s(async()=>{J(!0),Pe(!0),Re?.(),fe.current&&(fe.current=!1,T({eventName:"scan started",scanID:Ke.current,status:"success",email:h})),m(F()),V(!0),me.current&&await D.playAudio(`${w}StartScan.mp3`),me.current&&await D.playAudio(`${w}LiftArmsAndHoldAtHip.mp3`),me.current&&(J(!1),R(!0),se(!0),de(!0),Je());try{if(M&&M.current&&M.current.stream&&me.current){const e=M.current.stream.getVideoTracks()[0];if(e){const t=e.getSettings();j.current=t.frameRate||null}const t={videoBitsPerSecond:15e5};$e[0]&&(t.mimeType=$e[0]),me.current&&(U.current=new MediaRecorder(M.current.stream,t)),me.current&&U.current&&U.current.addEventListener("dataavailable",ot),le([...Oe.current,ot]),U.current&&U.current.start(1e3),W(!1),me.current&&(xe=setTimeout(rt,2e3))}}catch(e){console.log("error ----------",e)}},[M,$e,ot,rt,me,Re]);return o(()=>{_e.current=ct},[ct]),o(()=>(g&&(t(!0),tt()),()=>{const e=Ee.current;Ee.current=null,e&&(Be.poseDetection.disconnect(),S.capture(`${g}/pose_detection_disconnected`,{scanID:Ke.current,email:h,id:e,reason:"unmount"})),ie.forEach(e=>{U?.current?.removeEventListener("dataavailable",e)})}),[g]),o(()=>{Y.push(Q)},[Q]),o(()=>{Z([])},[ee]),o(()=>{const e=A.length&&A.length>0;O||!e||B||!me.current||oe||U&&U.current&&(B||U.current.stop())},[O,B,A,oe]),o(()=>{const e=A.length&&A.length>0;if(O&&e&&!B&&U&&U.current&&me.current&&!oe&&!B){const e=new File(A,`${r}.${Ze}`,{type:Ye});qe?.(),Ve?.(!0),i(""),ze?.(e,j.current)}},[O,B,A,oe,U,me]),o(()=>{_e.current=ct},[ct]),o(()=>{const e=_(Xe,E);Le(e)},[Xe]),o(()=>{He()},[]),e(ye,{resetDetector:n,resetScan:He,loadingCam:z,onPause:Qe,showRestart:ae,pause:oe,onReScan:async()=>{L({eventName:`${g}/rescan`,email:h,scanID:Ke.current,height:v,gender:y,status:!1}),Be.poseDetection.disconnect(),He(),await tt()},recordingStarted:B,isScanning:H,startSendingVideoFrames:ct,faceDone:q,stopRecording:et,showPause:ue,webcamRef:M,onUserMedia:Je,onUserMediaError:Ge,videoConstraints:je,webcamKey:Me})});function De({config:t}){const{scanUniqueKey:n,userDetails:r,setIsVideoUploaded:s,setScanFailsError:c,setScanStartTime:i,setScanUniqueKey:l}=u(x),[m,p]=a(90),[f,h]=a(0),[g,y]=a(null),[v,w]=a(!1),[b,S]=a(0),C=d([]),[D,N]=a(!1),I=m-f,k=I>=80&&I<=95;o(()=>{if("undefined"!=typeof window&&window.DeviceOrientationEvent){const e=e=>{if(null!==e.beta){let t=Math.abs(e.beta);null!==e.gamma&&(t*=Math.cos(e.gamma*Math.PI/180)),t=Math.max(0,Math.min(180,t)),p(t)}},t=async()=>{const t=DeviceOrientationEvent;if(t&&"function"==typeof t.requestPermission)try{"granted"===await t.requestPermission()&&window.addEventListener("deviceorientation",e)}catch(e){console.error("Permission error",e)}else window.addEventListener("deviceorientation",e);return()=>{e&&window.removeEventListener("deviceorientation",e)}};document.addEventListener("click",t,{once:!0})}},[]),o(()=>{if(C.current=[...C.current.slice(-4),I],C.current.length>=5){const e=Math.max(...C.current)-Math.min(...C.current);S(k&&e<2?e=>Math.min(100,e+10):e=>Math.max(0,e-20))}k||null===g&&!v||F()},[I,k,g,v]),o(()=>{b>=100&&null===g&&!v&&T(),b<50&&null!==g&&F()},[b,g,v]);const T=()=>{y(3);const e=setInterval(()=>{y(t=>null===t||t<=1?(clearInterval(e),w(!0),null):t-1)},1e3)},F=()=>{y(null),D||w(!1)};return e(ge,{angle:I,countdown:g,isScanning:v,isInTargetRange:k,stabilityScore:b,children:v&&e(Ce,{setIsScanLocked:N,resetDetector:()=>{p(90),h(0),y(null),w(!1),S(0),N(!1),C.current=[]},scanID:n,userDetails:r,setIsVideoUploaded:s,setScanFailsError:c,setScanStartTime:i,setScanUniqueKey:l})})}function Ne({setShowDrawer:t,loader:n}){const[r,c]=a({disabled:!1,message:""}),[i,l]=a(!0),u=d(null),m=s(async()=>{const e=await M();c(e),l(!1)},[]);return o(()=>{m()},[]),i?e(U,{url:n,loaderType:"black"}):r?.disabled?e(j,{reason:r?.reason}):e(ae,{audio:!1,ref:u,screenshotQuality:1,videoConstraints:A,mirrored:!0,poster:g,onUserMedia:()=>t?.(!0),screenshotFormat:"image/jpeg",style:{position:"fixed",top:0,left:0,right:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}})}function Ie({link:t,onReady:n,wrapperClassName:r="[&_video]:rounded-t-[20px] w-full h-full"}){const a=d(null),s=d(null);let c={autoplay:!0,controls:!1,responsive:!0,fluid:!0,muted:!0,navigationUI:"hide",preload:"auto",poster:P};return o(()=>{if(!s.current&&t&&a?.current){const e=le(a.current,{...c});e.ready(()=>{s.current=e;const r={...c,sources:[{src:t,type:"application/x-mpegURL"}]};e.autoplay(r.autoplay),e.src(r.sources),n?.(e)})}},[t,a]),o(()=>{const e=s.current;return()=>{e&&!e.isDisposed()&&(e.dispose(),s.current=null)}},[s]),e("div",{className:r,children:e("video",{ref:a,muted:!0,className:"video-js",playsInline:!0,onDrag:e=>e.preventDefault()})})}function ke({scanFailsError:r,onNext:s,gender:o,setScanUniqueKey:c,setIsVideoUploaded:i}){const{translate:l}=u(m)||{},d=p(),[g,v]=a(!1),w=()=>{v(!g)};return t(n,{children:[t("div",{"data-testid":"scan-error-message",className:"flex common-ui-main flex-col h-full max-w-[28rem] mx-auto w-full rounded-t-[20px] overflow-y-auto",style:{background:d?.style?.base?.backgroundColor},children:[e("div",{className:"w-full max-w-[28rem] mx-auto pt-[1rem] px-[1rem]",children:e(f,{noTitle:!0})}),e("div",{className:"flex-1",children:r&&t("div",{className:"px-[1rem]",children:[e("h2",{className:"text-center",style:{fontFamily:d?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:d?.style?.heading?.headingFontSize||"32px",color:d?.style?.heading?.headingColor||"#000",fontWeight:d?.style?.heading?.headingFontWeight||"normal"},children:l?.(h.issueWithScan)}),e("p",{style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:d?.style?.base?.baseFontSize||"16px",color:d?.style?.base?.baseTextColor||"#1E1E1E"},children:l?.(h.reason)}),e("p",{style:{fontFamily:d?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:d?.style?.base?.baseFontSize||"16px",color:d?.style?.base?.baseTextColor||"#1E1E1E"},children:z(r)}),e("img",{className:"my-[0.5rem] aspect-[2/1.4] w-full object-cover",onClick:w,src:V[o],alt:"icon"})]})}),r&&e("div",{className:"p-[1rem] flex gap-[0.5rem]",children:e(y,{"data-testid":"scan-again-btn",disabled:!1,buttonText:l?.(h.scanAgain),className:"!shadow-none",buttonFunc:()=>{s?s?.():c?.($()),i?.(!1)}})})]}),g&&t(oe,{className:"w-screen h-screen video-modal",onClose:w,open:g,children:[e("div",{className:"flex justifyEnd ",children:e("span",{className:"closeBtn",onClick:w,children:e(se,{className:"absolute right-[8px] top-[8px] text-white z-[9]"})})}),e("div",{className:"aspect-video object-cover rounded-[20px] ",children:e(Ie,{link:o?B[o].PRE_LINK:B.male.PRE_LINK,wrapperClassName:"w-screen h-screen fixed top-[0] left-[0]"})})]})]})}function Te({scanId:n,userDetails:r,config:c,isVideoUploadedCorrect:i,isMeasurementAvailable:l,onComplete:d,isSuccess:p,onCustomScanSuccess:g,swan:v}){const{gender:w,shopDomain:b,heightInCm:x,deviceFocalLength:C,userName:D,email:N,scanType:I}=r||{},k=[W,H,J].includes(I??""),[T,F]=a(!0),_=s(async()=>{try{(k||I===R)&&(await(v?.auth.addUser({scanId:n,email:N,name:D,gender:w,height:x})),g?.()),S.capture(b??"",{scanID:n,email:N,height:x,focalLength:C,clothesFit:"0",gender:w})}catch(e){console.log(e)}},[k]),{translate:E}=u(m)||{};o(()=>{(i||l)&&_()},[i,l]);const $=(p||i||l)&&!k;return e(ce,{className:"flex h-full w-full flex-col common-ui-main",children:t("div",{className:"h-full w-full flex-col items-center justify-center flex",children:[e(Ne,{loader:c?.loader,setShowDrawer:F}),e(ie,{open:T,onClose:(e,t)=>{},className:"camera-drawer",anchor:"bottom",children:e("div",{className:"max-w-[28rem] mx-auto w-full h-full flex text-center flex-col justify-between items-center bg-primary rounded-t-[30px] p-[1rem]",style:{background:c?.style?.base?.backgroundColor},children:t("div",{className:"w-full h-full flex flex-col",children:[e(f,{title:E?.(h.measurementsBeingTaken)}),e("div",{className:"flex items-center justify-center flex-1",children:e("video",{preload:"auto",className:"max-h-[calc(100vh-450px)] mx-auto w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:w===O.Male?q:K,type:"video/mp4"})})}),$&&e(y,{className:"!w-[180px] mx-auto",buttonText:E?.(h.next),buttonFunc:()=>{d?.()}})]})})})]})})}const Fe=()=>{const{userDetails:n,onRetry:r,isError:a,isSuccess:s,onScanSuccess:o,gender:c,scanUniqueKey:i,scanFailsError:l,setScanUniqueKey:d,setIsVideoUploaded:m,isMeasurementAvailable:f,isVideoUploadedCorrect:h,loading:g,showDeniedModal:y,uploadLoading:v,resetScan:w,onCustomScanSuccess:b,swan:S,onComplete:C}=u(x),D=p();return a?t("div",{"data-scan-state":"error",children:[e(Ne,{}),e(ie,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e(ke,{scanFailsError:l,onNext:()=>{r?.(),w()},setScanUniqueKey:d,gender:c,setIsVideoUploaded:m})})]}):s?e("div",{"data-scan-state":"success",children:e(Te,{isSuccess:!0,onComplete:C})}):g?e("div",{"data-scan-state":"loading",className:"flex top-0 !mt-0 left-0 z-[999] absolute justify-center items-center w-full h-full",style:{background:D?.style?.base?.backgroundColor},children:e(U,{url:D?.loader,loaderType:"black"})}):y.disabled?e("div",{"data-scan-state":"camera-denied",children:e(j,{reason:y.reason})}):v||l||f||h?(v||f||h)&&!l?e("div",{"data-scan-state":"processing",children:e(Te,{scanId:i,isMeasurementAvailable:f,userDetails:n,isVideoUploadedCorrect:h,onCustomScanSuccess:b,swan:S,onComplete:C,config:D})}):t("div",{"data-scan-state":"error-retry",children:[e(Ne,{}),e(ie,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e(ke,{scanFailsError:l,onNext:()=>{r?.(),w()},setScanUniqueKey:d,gender:c,setIsVideoUploaded:m})})]}):e("div",{"data-scan-state":"scanning",children:e(De,{config:D})})},_e=t=>{const{config:n,onRetry:r,onScanStart:c,onCaptureComplete:i,onUploadStart:u,onUploadEnd:d,onMeasurementSocketStart:m,onMeasurementSocketClose:p,onIntermediateScanSuccess:f,onScanError:h,onScanSuccess:g,onCustomScanSuccess:y,onComplete:v,isError:w,isSuccess:b}=t,S={email:"",shopDomain:"",gender:"male",heightInCm:0,scanType:"",deviceFocalLength:0,deviceModelName:"",sourceTag:"",callbackUrl:null,...t.userDetails??{}},C=t.token??"",{gender:D,scanType:N,shopDomain:I,heightInCm:k,email:_,deviceFocalLength:E,deviceModelName:L,callbackUrl:U,sourceTag:j}=S,A=l(()=>G(C),[C]),[P,V]=a(!1),[B,R]=a(!1),[q,K]=a(!1),[O,W]=a({disabled:!1,message:""}),[H,J]=a(""),[re,ae]=a(!1),[se,oe]=a(!0),[ce,ie]=a(!1),[le,ue]=a(""),[de,me]=a(F()),{gyroData:pe}=function(e){const[t,n]=a([]),[r,c]=a(!1),i=s(e=>{try{const{alpha:t,beta:r,gamma:a}=e;n(e=>[...e,{alpha:t?.toString()||void 0,beta:r?.toString()||void 0,gamma:a?.toString()||void 0,timestamp:(new Date).toISOString()}])}catch(e){console.log(e)}},[]),l=s(async()=>{const e=DeviceOrientationEvent;if(void 0!==e&&"function"==typeof e.requestPermission)try{"granted"===await e.requestPermission()?c(!0):console.warn("Device orientation permission denied.")}catch(e){console.error("Error requesting device orientation permission:",e)}else c(!0)},[]);return o(()=>(e&&r?window.addEventListener("deviceorientation",i):n([]),()=>{window.removeEventListener("deviceorientation",i)}),[e,r,i]),o(()=>{e&&l()},[e,l]),{gyroData:t}}(ce);Q();const he=s(()=>{ue($()),J(""),V(!1),ae(!1)},[]),ge=()=>{me(null),ue("")},ye=s(async e=>{if(e&&"success"===e?.scanStatus&&"intermediate"===e?.resultType&&200===e?.code)return T({eventName:`${I}/measurement_success/intermediate`,scanID:le,status:"success",email:_}),R(!0),void f?.({...e,scanId:le,email:_});g?.({...e,scanId:le,email:_}),R(!0),ge();const t=le;K(!0),V(!1),T({eventName:`${I}/measurement_success/fit-view`,scanID:t,status:"success",email:_}),de&&T({eventName:`${I}/scan_completion_time`,scanID:t,status:"success",completionTime:F()-de,email:_})},[N,I,le]),ve=e=>{V(!0),J(""),A.measurement.handleMeasurementSocket({scanId:le,onPreopen:()=>{ne({eventName:`${I}/webSocket`,scanID:le,connection:"pre_open",type:"measurement_recommendation",email:_})},onOpen:()=>{m?.(),ne({eventName:`${I}/webSocket`,scanID:le,connection:"open",type:"measurement_recommendation",email:_})},onClose:()=>{p?.(),ne({eventName:`${I}/webSocket`,scanID:le,connection:"close",type:"measurement_recommendation",email:_})},onError:e=>{var t;t=e,h?.({...t,message:z(t),scanId:le,email:_}),ge(),K(!1),J(t),R(!1),V(!1),T({eventName:`${I}/measurement_failed/fit-view`,scanID:le,status:"failed",email:_,message:z(t)}),de&&T({eventName:`${I}/scan_completion_time`,scanID:le,status:"failed",completionTime:F()-de,email:_}),ne({eventName:`${I}/webSocket`,scanID:le,connection:"error",type:"measurement_recommendation",email:_})},onSuccess:e=>{ne({eventName:`${I}/webSocket`,scanID:le,connection:"success",type:"measurement_recommendation",email:_}),ye(e)}})},we=s(async(e,t)=>{const n=Number((e.size/1048576).toFixed(2)),r=null!=t?t:await X(e),a=Y({gender:D,focal_length:`${E}`,height:`${k}`,customer_store_url:I,clothes_fit:"0",scan_type:te(N),callback_url:U,source_tag:j});T({eventName:`${I}/body_scan_meta_data`,scanID:le,email:_,data:JSON.stringify([...a,{fileSizeInMB:n,video_fps:r||0}])}),u?.();try{await A.fileUpload.uploadFileFrontend({file:e,arrayMetaData:a,scanId:le,email:_}),await A.fileUpload.setDeviceInfo({model:L,detection:"manual",gyro:pe,scanId:le}),console.log("video successfully uploaded"),ae(!1),T({eventName:`${I}/scan_success`,scanID:le,status:"success",email:_,data:JSON.stringify(a)}),T({eventName:"scan finished",scanID:le,status:"success",email:_}),me(F()),setTimeout(()=>{ae(!0)},3e3)}catch(e){T({eventName:"scan finished",scanID:le,status:"failed",email:_,message:z(e)}),T({eventName:`${I}/scan_failed`,scanID:le,status:"failed",email:_,message:z(e),data:JSON.stringify(a)}),J(z(e)),ae(!1),h?.({...e,message:z(e),scanId:le,email:_}),ge()}finally{ie(!1),d?.()}},[le,pe,u,d]),be=s(async()=>{if(+k<152.4||+k>213.36)return void h?.({message:"Height must be between 152.4cm (5ft) and 213.36cm (7ft)",scanId:le,email:_});const e=await M();e.disabled?(T({eventName:`${I}/camera_activation`,scanID:le,status:"failed",email:_}),oe(!1)):(oe(!1),T({eventName:`${I}/camera_activation`,scanID:le,status:"success",email:_})),W(e),J(""),ae(!1)},[_,le,ue,I]);return o(()=>{w||b||I&&be()},[I,k,w,b]),o(()=>{w||b||re&&I&&le&&ve()},[re,I,le,w,b]),e("div",{"data-testid":"body-scan-root",children:e(Z,{children:e(ee,{config:n,children:e(fe,{children:e(x.Provider,{value:{userDetails:S,onRetry:r,onScanError:h,isError:w,isSuccess:b,onScanSuccess:g,gender:D,scanUniqueKey:le,scanFailsError:H,setScanUniqueKey:ue,setIsVideoUploaded:ae,isMeasurementAvailable:q,isVideoUploadedCorrect:B,loading:se,showDeniedModal:O,uploadLoading:P,setStartGyro:ie,uploadScanFile:we,setUploadLoading:V,resetScan:he,setScanFailsError:J,setScanStartTime:me,onScanStart:c,onCaptureComplete:i,onCustomScanSuccess:y,onComplete:v,swan:A},children:e(Fe,{})})})})})})},Ee=t=>{const[n,r]=a(!1);return o(()=>{r(!0)},[]),n?e(_e,{...t}):e("div",{"data-testid":"body-scan-root"})};export{Ee as B};
3
+ //# sourceMappingURL=BodyScan-BvA15WCG.mjs.map
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import{useRef as n,useState as r,useMemo as o,useCallback as c,useEffect as i,useContext as s}from"react";import{v as l,p as d,s as u,a as m,L as h,u as f,H as g,b as p,S as y,m as S,g as b,G as w,d as v,F as x,P as F,c as N,t as I,e as _,M as k,f as E,h as C,i as M,j as D,k as T,l as P,n as R,o as z,q as $,r as j,w as L,C as V,x as W,y as O,z as U}from"./Modal-DHcCPbXc.mjs";import{ArrowRight as A}from"lucide-react";import{Drawer as B}from"@mui/material";let q=null,G=!1;const J=async()=>{if("undefined"==typeof window)return null;if(q)return q;if(G)for(;G;)if(await new Promise(e=>setTimeout(e,100)),q)return q;G=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("./pose-detection.esm-CahFpbbr.mjs")]);try{await e.setBackend("webgl"),await e.ready()}catch{console.warn("WebGL backend unavailable, falling back to CPU"),await e.setBackend("cpu"),await e.ready()}const a=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),n=document.createElement("canvas");n.width="number"==typeof l.width?l.width:l.width.ideal??l.width.max??1280,n.height="number"==typeof l.height?l.height:l.height.ideal??l.height.max??720;const r=n.getContext("2d");if(r){r.fillStyle="black",r.fillRect(0,0,n.width,n.height);try{await a.estimatePoses(n)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return q=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{G=!1}};function H({faceScanId:e,onValidPose:t,onScanComplete:a,onModelReady:s,onStartRecording:l,shopDomain:h,isError:f,isSuccess:g}){const p=n(null),[y,S]=r(0),[b,w]=r(0),[v,x]=r(!1),[F,N]=r(!1),I=n(!1),_=n(null),k=n(null),E=n(y),C=n(b),M=n([]),D=n(""),T=n(0),P=n(!1),R=n(0),z="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),$=o(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),j=o(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{d.capture(`${h}/face_scan_pose_detection`,e)},4e3),[h]),L=c((t,a,n,r,o,c)=>{const i=Date.now();if(!(i-R.current<4e3)){R.current=i;try{const i=t[0]||[0,0,0],s=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],m=t.map(e=>e[2]).filter(e=>e>0),h=m.length>0?m.reduce((e,t)=>e+t,0)/m.length:0,f=a.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,p=Math.abs(s[0]-l[0]),y=i[0]-l[0],S=s[0]-i[0];let b="frontal";1===n?b="left":2===n?b="right":3===n&&(b="frontal_smile");const w={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:r,bodyInvalid:o,consecutiveValid:c,avgFaceScore:parseFloat(h.toFixed(3)),avgBodyScore:parseFloat(g.toFixed(3)),faceKeypointsDetected:m.length,bodyKeypointsDetected:f.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(i[2].toFixed(3)),leftEyeScore:parseFloat(s[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:b})};j(w)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,j]),V=()=>{d.capture(`${h}/face_scan_detection_started`,{faceScanId:e,stage:E.current,timestamp:(new Date).toISOString(),stageName:$[E.current]}),setTimeout(()=>{N(!0)},1500)};return i(()=>{if(!f&&!g)return(async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await J();e&&(p.current=e,console.log("Face scan model loaded successfully"),x(!0),s?.())}catch(e){console.error("Error initializing face scan:",e)}})(),()=>{(async()=>{try{x(!1)}catch(e){console.error("Error disposing resources:",e)}finally{S(0),w(0),E.current=0,C.current=0,M.current=[]}})()}},[f,g]),i(()=>{E.current=y},[y]),i(()=>{C.current=b},[b]),{faceScanDetector:async(n,r)=>{if(p.current&&n.current&&v&&F&&!(n.current.readyState<2||I.current)){I.current=!0;try{const o=n.current.videoWidth||720,c=n.current.videoHeight||1280;_.current||(_.current=document.createElement("canvas"),_.current.width=o,_.current.height=c);const i=_.current.getContext("2d");i&&i.drawImage(n.current,0,0,o,c);const s=await p.current.estimatePoses(i?_.current:n.current);if(s.length>0){const n=[],o=[];if(s[0].keypoints.forEach((e,t)=>{const a=e.score??0,r=[e.x??-1,e.y??-1,a];t<=10?n.push(r):o.push(r)}),r?.current){const e=r.current.getContext("2d"),{width:t,height:a}=r.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),r=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,r+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const c=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,r=n>.7||n<.3,o=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,c=t[2][0]-t[5][0],i=t[0][0]-t[5][0],s=i>.4*c&&i<.6*c,l=i>.85*c,d=t[2][0]-t[0][0]>.85*c;switch(e){case 0:case 3:return!r&&o&&s;case 1:return!r&&o&&l;case 2:return!r&&o&&d;default:return!1}})(E.current,n),i=o.slice(2).filter(e=>e[2]>.7).length<=2;M.current.push(c&&i),M.current.length>10&&M.current.shift();if(M.current.filter(Boolean).length>=2){const e=C.current+1;w(e)}else w(Math.max(0,C.current-1));if(C.current>=2){t?.();const n=E.current+1;w(0),M.current=[],S(n),N(!1),(async()=>{if(await u.playAudio(`${m}face-scan-vos/Sound-effect.mp3`),d.capture(`${h}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:E.current,nextStage:n,timestamp:(new Date).toISOString(),totalStages:4,stageName:$[E.current]}),1===n&&l&&l(),n>=4)a?.();else{let e=null;switch(n){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await u.playAudio(`${m}face-scan-vos/${e}`),V()}})()}L(n,o,E.current,c,i,C.current)}}catch(e){console.error("Pose detection error:",e)}finally{I.current=!1}}},scanStage:y,setScanStage:S,consecutiveValid:b,isModelLoaded:v,resetScan:()=>{d.capture(`${h}/face_scan_reset`,{faceScanId:e,stage:E.current,timestamp:(new Date).toISOString(),stageName:$[E.current],consecutiveValid:C.current}),S(0),w(0),N(!1),E.current=0,C.current=0,M.current=[],D.current="",T.current=0,P.current=!1,k.current&&("undefined"!=typeof speechSynthesis&&speechSynthesis.cancel(),k.current=null)},enableVoiceCommands:()=>{if(P.current=!0,"undefined"!=typeof window&&z&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:V,isScanningActive:F}}function K({onRetry:a,loading:n}){const{translate:r}=s(h)||{},o=f();return e("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:o?.style?.base?.backgroundColor},children:t("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e(g,{noTitle:!0}),t("div",{className:"flex flex-col items-center w-full",children:[e("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:o?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:o?.style?.heading?.headingFontSize||"32px",color:o?.style?.heading?.headingColor||"#000",fontWeight:o?.style?.heading?.headingFontWeight||"normal"},children:r?.(p.scanFailed)}),e("p",{className:"mb-[1.5rem]",style:{fontFamily:o?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:o?.style?.subheading?.subheadingFontSize||"14px",color:o?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:o?.style?.subheading?.subheadingFontWeight||"normal"},children:r?.(p.clickToResetScan)}),e(y,{"data-testid":"face-scan-retry-btn",disabled:n,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:r?.(p.resetScan),postfixIcon:e(A,{}),buttonFunc:()=>a?.()})]})]})})}function X({stage:a,videoLoading:n,setVideoLoading:r,videoError:o,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=s(h)||{},u=f();return-1===a?t("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(p.faceVisible)}),n&&e("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.loadingVideo)}),o&&e("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.videoLoadFailed)}),!o&&e("div",{className:" w-[100px] mx-auto",children:e("video",{src:i===w.Male?S:b,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>r(!1),onLoadStart:()=>r(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e("div",{className:"flex justify-center w-full p-[1rem]",children:e(y,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(v[a])}),t("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e("div",{className:` w-[120px] overflow-hidden ${0===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.forward:x.female.forward,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${1===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.left:x.female.left,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${2===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.right:x.female.right,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${3===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.smile:x.female.smile,type:"video/mp4"})})})]})]})})}const Q=({webcamRef:n,canvasRef:r})=>{const{isError:o,isSuccess:c,showLoader:i,hasError:d,errorType:u,resetScanState:m,showGuideCard:h,scanStage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,getButtonText:v,isScanning:x,startScan:E,isModelLoaded:C,onRetry:M}=s(F),D=f();return o?e(K,{onRetry:M}):c?e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:D?.style?.base?.backgroundColor},children:e(N,{url:D?.loader,loaderType:"black"})}):t(a,{children:[e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),i&&!d&&e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:D?.style?.base?.backgroundColor},children:e(N,{url:D?.loader,loaderType:"black"})}),e("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:D?.style?.base?.backgroundColor},children:e("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:t("div",{className:"w-full h-full",children:[e("video",{ref:n,autoPlay:!0,playsInline:!0,muted:!0,poster:I,width:l.width.ideal,height:l.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e("canvas",{ref:r,width:l.width.ideal,height:l.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!i&&d&&u===_.Camera&&e(k,{testId:"face-scan-camera-error-screen"}),!i&&d&&u!==_.Camera&&e(K,{loading:i,onRetry:m}),h&&!d&&!i&&e(B,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e(X,{stage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,btnConfig:{label:v(),onClick:x?m:E,isDisabled:i||!C,icon:e(x?A:a,{})}})})]})},Y=t=>{const{onScanSuccess:a,onScanError:s,onRetry:l,onScanStart:d,onCaptureComplete:h,onUploadStart:f,onUploadEnd:g,onMeasurementSocketStart:y,onMeasurementSocketClose:S,config:b,isError:w,isSuccess:v}=t,x=t.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:"",callbackUrl:null},N=t.token??"",I=n(null),k=n(null),A=n(null),B=n([]),q=n(null),G=n(null),J=n(0),K=n(null),[X,Y]=r(!1),[Z,ee]=r(!1),[te,ae]=r(!1),[ne,re]=r(!0),[oe,ce]=r(!1),[ie,se]=r(!1),[le,de]=r(!1),[ue,me]=r(null),[he,fe]=r(E()),ge=o(()=>C(N),[N]),{email:pe,gender:ye,deviceFocalLength:Se,shopDomain:be,callbackUrl:we,bodyScanId:ve}=x,[xe,Fe]=r([]),[Ne,Ie]=r(M),_e=o(()=>D(),[]),ke=T(xe),Ee=P(ke);R();const Ce=c(()=>{console.log("Stopping recording..."),cancelAnimationFrame(J.current),K.current&&(K.current.pause(),K.current.srcObject=null,K.current=null),A.current&&"recording"===A.current.state&&A.current.stop(),A.current=null},[]),Me=async()=>{if(h?.(),B.current){if(0===B.current.length)return console.error("No video data recorded"),me(_.Scan),de(!0),void Y(!1);f?.(),Y(!0);const e=new File(B.current,`${he}.${Ee}`,{type:ke}),t=G.current??await W(e),a=e.size,n=(a/1048576).toFixed(2),r=Math.round(a/1e4),o={video_size_mb:parseFloat(n),video_size_bytes:a,video_fps:t||0,blob_count:B.current.length,estimated_duration_seconds:r},c=[{gender:ye},{face_scan_id:he},{focal_length:`${Se}`},{customer_store_url:be},{scan_type:"face_scan"},{body_scan_id:ve}];we&&c.push({callback_url:we}),O({eventName:`${be}/face_scan_meta_data`,faceScanId:he,email:pe,data:JSON.stringify({metaData:c,videoData:o})});const i=Date.now();O({eventName:`${be}/face_scan_upload_start`,faceScanId:he,email:pe,startTime:i});try{const t=await ge.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:he,email:pe,contentType:e.type}),a=Date.now();O({eventName:`${be}/face_scan_upload_complete`,faceScanId:he,email:pe,completionTime:a,uploadDuration:a-i}),g?.(),console.log("✅ Upload successful",t),ge.measurement.handlFaceScaneSocket({onPreopen:()=>{y?.(),U({eventName:`${be}/webSocket`,faceScanID:he,connection:"pre_open",type:"faceScan_recommendation",email:pe})},faceScanId:he,onOpen:()=>{U({eventName:`${be}/webSocket`,faceScanID:he,connection:"open",type:"faceScan_recommendation",email:pe}),console.log("websocket connect open")},onError:e=>{U({eventName:`${be}/webSocket`,faceScanID:he,connection:"error",type:"faceScan_recommendation",email:pe}),We(e)},onSuccess:e=>{U({eventName:`${be}/webSocket`,faceScanID:he,connection:"success",type:"faceScan_recommendation",email:pe}),Oe(e)},onClose:()=>{S?.(),console.log("websocket connect close"),U({eventName:`${be}/webSocket`,faceScanID:he,connection:"close",type:"faceScan_recommendation",email:pe})}})}catch(e){g?.(),We(e)}}},De=c(()=>{const e=I.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=1280,height:n=720}=t,r=document.createElement("canvas"),o=r.getContext("2d");a>n?(r.width=n,r.height=a):(r.width=a,r.height=n);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play(),K.current=c;const i=()=>{a>n?(o?.save(),o?.translate(r.width,0),o?.rotate(Math.PI/2),o?.drawImage(c,0,0,n,a),o?.restore()):o?.drawImage(c,0,0,a,n),J.current=requestAnimationFrame(i)};J.current=requestAnimationFrame(i);const s=t.frameRate??10;G.current=s;const l=r.captureStream(s),d={videoBitsPerSecond:15e5};let u;xe.length>0&&(d.mimeType=xe[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),me(_.Scan),de(!0),void Y(!1)}B.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&B.current&&B.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",B?.current?.length),Me()},u.start(100),A.current=u,console.log("Recording started successfully (portrait normalized)")},[xe,Me]),{faceScanDetector:Te,scanStage:Pe,setScanStage:Re,resetScan:ze,isModelLoaded:$e,startScanSequence:je}=H({faceScanId:he,shopDomain:be,isError:w,isSuccess:v,onScanComplete:()=>{Ce()},onModelReady:()=>{ee(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),De()}}),Le=c(()=>{$e&&(d?.(),Re(0),u.playAudio(`${m}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{ae(!0),setTimeout(()=>{je()},200)},200))},[Re,ae,je,$e,d]),Ve=c(()=>{ae(!1),re(!0),Ce(),ze(),l?.(),B.current=[],G.current=null,A.current&&(A.current=null),de(!1),me(null),Re(-1),fe(E()),I.current&&q.current&&(I.current.srcObject=q.current,console.log("Camera stream restored after reset"))},[Re,ae,re,Ce,ze,fe]),We=e=>{console.log(e,"ws error"),s?.(e),me(_.Scan),de(!0),Y(!1),re(!1),O({eventName:`${be}/faceScan`,faceScanId:he,status:"failed",email:pe,data:JSON.stringify(e)})},Oe=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&O({eventName:`${be}/faceScan_success/intermediate`,faceScanId:he,status:"success",email:pe,data:JSON.stringify(e)}),a?.(e)};i(()=>{if(!w&&!v)return navigator.mediaDevices?.getUserMedia&&navigator.mediaDevices.getUserMedia({video:Ne}).then(e=>{q.current=e,I.current&&(I.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),Ne===M)return void Ie(z);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);me(t?_.Camera:_.Scan),de(!0)}),()=>{q.current&&q.current.getTracks().forEach(e=>e.stop())}},[w,v,Ne]),i(()=>{if(!Z||!te)return;const e=setInterval(()=>{Te(I,k)},500);return()=>clearInterval(e)},[Te,Z,te]);return console.log("Model ready:",Z,"Has error:",le,"Is scanning:",te,"showLoader",X),i(()=>{const e=$(_e,j);Fe(e)},[_e]),i(()=>{Re(-1)},[]),e("div",{"data-face-scan-stage":Pe,children:e(L,{children:e(V,{config:b,children:e(F.Provider,{value:{isError:w,isSuccess:v,showLoader:X,hasError:le,errorType:ue,resetScanState:Ve,showGuideCard:ne,scanStage:Pe,videoLoading:oe,setVideoLoading:ce,videoError:ie,setVideoError:se,gender:ye,getButtonText:()=>te?p.reset:$e?p.start:p.loading,isScanning:te,startScan:Le,isModelLoaded:$e,onRetry:l},children:e(Q,{webcamRef:I,canvasRef:k})})})})})};export{Y as F,J as p};
3
+ //# sourceMappingURL=FaceScan-BuWM0ckX.mjs.map
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./Modal-CraqOTeI.js"),n=require("lucide-react"),r=require("@mui/material");let o=null,s=!1;const c=async()=>{if("undefined"==typeof window)return null;if(o)return o;if(s)for(;s;)if(await new Promise(e=>setTimeout(e,100)),o)return o;s=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-Bk0xrbdx.js")})]);try{await e.setBackend("webgl"),await e.ready()}catch{console.warn("WebGL backend unavailable, falling back to CPU"),await e.setBackend("cpu"),await e.ready()}const n=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),r=document.createElement("canvas");r.width="number"==typeof a.videoConstraints.width?a.videoConstraints.width:a.videoConstraints.width.ideal??a.videoConstraints.width.max??1280,r.height="number"==typeof a.videoConstraints.height?a.videoConstraints.height:a.videoConstraints.height.ideal??a.videoConstraints.height.max??720;const s=r.getContext("2d");if(s){s.fillStyle="black",s.fillRect(0,0,r.width,r.height);try{await n.estimatePoses(r)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return o=n,n}catch(e){return console.error("Failed to preload detector:",e),null}finally{s=!1}};function i({faceScanId:e,onValidPose:n,onScanComplete:r,onModelReady:o,onStartRecording:s,shopDomain:i,isError:l,isSuccess:d}){const u=t.useRef(null),[f,g]=t.useState(0),[h,m]=t.useState(0),[p,y]=t.useState(!1),[S,x]=t.useState(!1),v=t.useRef(!1),b=t.useRef(null),w=t.useRef(null),F=t.useRef(f),C=t.useRef(h),j=t.useRef([]),E=t.useRef(""),_=t.useRef(0),N=t.useRef(!1),T=t.useRef(0),k="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),R=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),I=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${i}/face_scan_pose_detection`,e)},4e3),[i]),D=t.useCallback((t,a,n,r,o,s)=>{const c=Date.now();if(!(c-T.current<4e3)){T.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:r,bodyInvalid:o,consecutiveValid:s,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};I(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,I]),M=()=>{a.posthog.capture(`${i}/face_scan_detection_started`,{faceScanId:e,stage:F.current,timestamp:(new Date).toISOString(),stageName:R[F.current]}),setTimeout(()=>{x(!0)},1500)};return t.useEffect(()=>{if(!l&&!d)return(async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await c();e&&(u.current=e,console.log("Face scan model loaded successfully"),y(!0),o?.())}catch(e){console.error("Error initializing face scan:",e)}})(),()=>{(async()=>{try{y(!1)}catch(e){console.error("Error disposing resources:",e)}finally{g(0),m(0),F.current=0,C.current=0,j.current=[]}})()}},[l,d]),t.useEffect(()=>{F.current=f},[f]),t.useEffect(()=>{C.current=h},[h]),{faceScanDetector:async(t,o)=>{if(u.current&&t.current&&p&&S&&!(t.current.readyState<2||v.current)){v.current=!0;try{const c=t.current.videoWidth||720,l=t.current.videoHeight||1280;b.current||(b.current=document.createElement("canvas"),b.current.width=c,b.current.height=l);const d=b.current.getContext("2d");d&&d.drawImage(t.current,0,0,c,l);const f=await u.current.estimatePoses(d?b.current:t.current);if(f.length>0){const t=[],c=[];if(f[0].keypoints.forEach((e,a)=>{const n=e.score??0,r=[e.x??-1,e.y??-1,n];a<=10?t.push(r):c.push(r)}),o?.current){const e=o.current.getContext("2d"),{width:t,height:a}=o.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),r=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,r+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const l=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,r=n>.7||n<.3,o=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,s=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*s&&c<.6*s,l=c>.85*s,d=t[2][0]-t[0][0]>.85*s;switch(e){case 0:case 3:return!r&&o&&i;case 1:return!r&&o&&l;case 2:return!r&&o&&d;default:return!1}})(F.current,t),d=c.slice(2).filter(e=>e[2]>.7).length<=2;j.current.push(l&&d),j.current.length>10&&j.current.shift();if(j.current.filter(Boolean).length>=2){const e=C.current+1;m(e)}else m(Math.max(0,C.current-1));if(C.current>=2){n?.();const t=F.current+1;m(0),j.current=[],g(t),x(!1),(async()=>{if(await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${i}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:F.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:R[F.current]}),1===t&&s&&s(),t>=4)r?.();else{let e=null;switch(t){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/${e}`),M()}})()}D(t,c,F.current,l,d,C.current)}}catch(e){console.error("Pose detection error:",e)}finally{v.current=!1}}},scanStage:f,setScanStage:g,consecutiveValid:h,isModelLoaded:p,resetScan:()=>{a.posthog.capture(`${i}/face_scan_reset`,{faceScanId:e,stage:F.current,timestamp:(new Date).toISOString(),stageName:R[F.current],consecutiveValid:C.current}),g(0),m(0),x(!1),F.current=0,C.current=0,j.current=[],E.current="",_.current=0,N.current=!1,w.current&&("undefined"!=typeof speechSynthesis&&speechSynthesis.cancel(),w.current=null)},enableVoiceCommands:()=>{if(N.current=!0,"undefined"!=typeof window&&k&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:M,isScanningActive:S}}function l({onRetry:r,loading:o}){const{translate:s}=t.useContext(a.LanguageContext)||{},c=a.useConfig();return e.jsx("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:c?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(a.Header,{noTitle:!0}),e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:s?.(a.LanguageKeys.scanFailed)}),e.jsx("p",{className:"mb-[1.5rem]",style:{fontFamily:c?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:c?.style?.subheading?.subheadingFontSize||"14px",color:c?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:c?.style?.subheading?.subheadingFontWeight||"normal"},children:s?.(a.LanguageKeys.clickToResetScan)}),e.jsx(a.SpecificButton,{"data-testid":"face-scan-retry-btn",disabled:o,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:s?.(a.LanguageKeys.resetScan),postfixIcon:e.jsx(n.ArrowRight,{}),buttonFunc:()=>r?.()})]})]})})}function d({stage:n,videoLoading:r,setVideoLoading:o,videoError:s,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=t.useContext(a.LanguageContext)||{},u=a.useConfig();return-1===n?e.jsxs("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.LanguageKeys.faceVisible)}),r&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.loadingVideo)}),s&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.videoLoadFailed)}),!s&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===a.GenderType.Male?a.maleGlassesOffVideo:a.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>o(!1),onLoadStart:()=>o(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(a.SpecificButton,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e.jsx("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.directionMessages[n])}),e.jsxs("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e.jsx("div",{className:` w-[120px] overflow-hidden ${0===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.forward:a.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.left:a.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.right:a.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.smile:a.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const u=({webcamRef:o,canvasRef:s})=>{const{isError:c,isSuccess:i,showLoader:u,hasError:f,errorType:g,resetScanState:h,showGuideCard:m,scanStage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,getButtonText:w,isScanning:F,startScan:C,isModelLoaded:j,onRetry:E}=t.useContext(a.ParamsContext),_=a.useConfig();return c?e.jsx(l,{onRetry:E}):i?e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}):e.jsxs(e.Fragment,{children:[e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:_?.style?.base?.backgroundColor},children:e.jsx("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:e.jsxs("div",{className:"w-full h-full",children:[e.jsx("video",{ref:o,autoPlay:!0,playsInline:!0,muted:!0,poster:a.transparentPoster,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:s,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&g===a.FaceScanErrorType.Camera&&e.jsx(a.Modal,{testId:"face-scan-camera-error-screen"}),!u&&f&&g!==a.FaceScanErrorType.Camera&&e.jsx(l,{loading:u,onRetry:h}),m&&!f&&!u&&e.jsx(r.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(d,{stage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,btnConfig:{label:w(),onClick:F?h:C,isDisabled:u||!j,icon:F?e.jsx(n.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=n=>{const{onScanSuccess:r,onScanError:o,onRetry:s,onScanStart:c,onCaptureComplete:l,onUploadStart:d,onUploadEnd:f,onMeasurementSocketStart:g,onMeasurementSocketClose:h,config:m,isError:p,isSuccess:y}=n,S=n.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:"",callbackUrl:null},x=n.token??"",v=t.useRef(null),b=t.useRef(null),w=t.useRef(null),F=t.useRef([]),C=t.useRef(null),j=t.useRef(null),E=t.useRef(0),_=t.useRef(null),[N,T]=t.useState(!1),[k,R]=t.useState(!1),[I,D]=t.useState(!1),[M,P]=t.useState(!0),[A,L]=t.useState(!1),[O,z]=t.useState(!1),[$,H]=t.useState(!1),[W,V]=t.useState(null),[U,K]=t.useState(a.generateUuid()),B=t.useMemo(()=>a.getSwanService(x),[x]),{email:q,gender:G,deviceFocalLength:J,shopDomain:X,callbackUrl:Q,bodyScanId:Y}=S,[Z,ee]=t.useState([]),[te,ae]=t.useState(a.videoConstraintsExact),ne=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),re=a.getRecordingMimeType(Z),oe=a.getRecordingExtension(re);a.usePosthogPageview();const se=t.useCallback(()=>{console.log("Stopping recording..."),cancelAnimationFrame(E.current),_.current&&(_.current.pause(),_.current.srcObject=null,_.current=null),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),ce=async()=>{if(l?.(),F.current){if(0===F.current.length)return console.error("No video data recorded"),V(a.FaceScanErrorType.Scan),H(!0),void T(!1);d?.(),T(!0);const e=new File(F.current,`${U}.${oe}`,{type:re}),t=j.current??await a.getVideoFPS(e),n=e.size,r=(n/1048576).toFixed(2),o=Math.round(n/1e4),s={video_size_mb:parseFloat(r),video_size_bytes:n,video_fps:t||0,blob_count:F.current.length,estimated_duration_seconds:o},c=[{gender:G},{face_scan_id:U},{focal_length:`${J}`},{customer_store_url:X},{scan_type:"face_scan"},{body_scan_id:Y}];Q&&c.push({callback_url:Q}),a.handleScanTimeCapture({eventName:`${X}/face_scan_meta_data`,faceScanId:U,email:q,data:JSON.stringify({metaData:c,videoData:s})});const i=Date.now();a.handleScanTimeCapture({eventName:`${X}/face_scan_upload_start`,faceScanId:U,email:q,startTime:i});try{const t=await B.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:U,email:q,contentType:e.type}),n=Date.now(),r=n-i;a.handleScanTimeCapture({eventName:`${X}/face_scan_upload_complete`,faceScanId:U,email:q,completionTime:n,uploadDuration:r}),f?.(),console.log("✅ Upload successful",t),B.measurement.handlFaceScaneSocket({onPreopen:()=>{g?.(),a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:U,connection:"pre_open",type:"faceScan_recommendation",email:q})},faceScanId:U,onOpen:()=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:U,connection:"open",type:"faceScan_recommendation",email:q}),console.log("websocket connect open")},onError:e=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:U,connection:"error",type:"faceScan_recommendation",email:q}),ye(e)},onSuccess:e=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:U,connection:"success",type:"faceScan_recommendation",email:q}),Se(e)},onClose:()=>{h?.(),console.log("websocket connect close"),a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:U,connection:"close",type:"faceScan_recommendation",email:q})}})}catch(e){f?.(),ye(e)}}},ie=t.useCallback(()=>{const e=v.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:n=1280,height:r=720}=t,o=document.createElement("canvas"),s=o.getContext("2d");n>r?(o.width=r,o.height=n):(o.width=n,o.height=r);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play(),_.current=c;const i=()=>{n>r?(s?.save(),s?.translate(o.width,0),s?.rotate(Math.PI/2),s?.drawImage(c,0,0,r,n),s?.restore()):s?.drawImage(c,0,0,n,r),E.current=requestAnimationFrame(i)};E.current=requestAnimationFrame(i);const l=t.frameRate??10;j.current=l;const d=o.captureStream(l),u={videoBitsPerSecond:15e5};let f;Z.length>0&&(u.mimeType=Z[0]);try{f=new MediaRecorder(d,u)}catch(e){return console.error("MediaRecorder init failed:",e),V(a.FaceScanErrorType.Scan),H(!0),void T(!1)}F.current=[],f.ondataavailable=e=>{e?.data&&e.data.size>0&&F.current&&F.current.push(e.data)},f.onstop=()=>{console.log("Recording stopped, total blobs:",F?.current?.length),ce()},f.start(100),w.current=f,console.log("Recording started successfully (portrait normalized)")},[Z,ce]),{faceScanDetector:le,scanStage:de,setScanStage:ue,resetScan:fe,isModelLoaded:ge,startScanSequence:he}=i({faceScanId:U,shopDomain:X,isError:p,isSuccess:y,onScanComplete:()=>{se()},onModelReady:()=>{R(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),ie()}}),me=t.useCallback(()=>{ge&&(c?.(),ue(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{D(!0),setTimeout(()=>{he()},200)},200))},[ue,D,he,ge,c]),pe=t.useCallback(()=>{D(!1),P(!0),se(),fe(),s?.(),F.current=[],j.current=null,w.current&&(w.current=null),H(!1),V(null),ue(-1),K(a.generateUuid()),v.current&&C.current&&(v.current.srcObject=C.current,console.log("Camera stream restored after reset"))},[ue,D,P,se,fe,K]),ye=e=>{console.log(e,"ws error"),o?.(e),V(a.FaceScanErrorType.Scan),H(!0),T(!1),P(!1),a.handleScanTimeCapture({eventName:`${X}/faceScan`,faceScanId:U,status:"failed",email:q,data:JSON.stringify(e)})},Se=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${X}/faceScan_success/intermediate`,faceScanId:U,status:"success",email:q,data:JSON.stringify(e)}),r?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices?.getUserMedia&&navigator.mediaDevices.getUserMedia({video:te}).then(e=>{C.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),te===a.videoConstraintsExact)return void ae(a.videoConstraintsFallback);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);V(t?a.FaceScanErrorType.Camera:a.FaceScanErrorType.Scan),H(!0)}),()=>{C.current&&C.current.getTracks().forEach(e=>e.stop())}},[p,y,te]),t.useEffect(()=>{if(!k||!I)return;const e=setInterval(()=>{le(v,b)},500);return()=>clearInterval(e)},[le,k,I]);return console.log("Model ready:",k,"Has error:",$,"Is scanning:",I,"showLoader",N),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(ne,a.videoTypes);ee(e)},[ne]),t.useEffect(()=>{ue(-1)},[]),e.jsx("div",{"data-face-scan-stage":de,children:e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:m,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:N,hasError:$,errorType:W,resetScanState:pe,showGuideCard:M,scanStage:de,videoLoading:A,setVideoLoading:L,videoError:O,setVideoError:z,gender:G,getButtonText:()=>I?a.LanguageKeys.reset:ge?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:I,startScan:me,isModelLoaded:ge,onRetry:s},children:e.jsx(u,{webcamRef:v,canvasRef:b})})})})})},exports.preloadDetector=c;
3
+ //# sourceMappingURL=FaceScan-lR9pZZDf.js.map