1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index.CdjOtu-m.js","assets/vendor-ui-core.DP8knyZn.js","assets/vendor-react.BBoGJFYM.js","assets/vendor-supabase.DS-aP8MZ.js","assets/vendor-ui-forms.CjLBxE3d.js","assets/vendor-utils.BlEnRQrd.js","assets/vendor-icons.BjAWwE8z.js","assets/vendor-ui-display.BT2Z6Vpo.js","assets/vendor-query.CfjDb5WU.js","assets/vendor-media.DY6E_qVO.js","assets/vendor-charts.RWeJ_I16.js","assets/vendor-motion.DCvbjL6b.js","assets/index.5-rfuBO2.css"])))=>i.map(i=>d[i]); 2var e=Object.defineProperty,t=(t,n,s)=>((t,n,s)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[n]=s)(t,"symbol"!=typeof n?n+"":n,s);import{_ as n}from"./vendor-supabase.DS-aP8MZ.js";import{j as s}from"./vendor-ui-core.DP8knyZn.js";import{r,f as i,j as a}from"./vendor-react.BBoGJFYM.js";import{A as o,a as l,b as c,c as d,d as u,e as h,f as p,g as f}from"./alert-dialog.DmbxRrbo.js";import{i as m,s as g,j as v,p as x,u as b,e as w,a as y}from"./index.CdjOtu-m.js";import{ad as k,ae as S,i as T,h as N,R as C,a1 as _,af as j,L as E,r as I,ag as R,k as A,N as P,O as M,ah as F,Q as B,ai as q}from"./vendor-icons.BjAWwE8z.js";import"./vendor-ui-forms.CjLBxE3d.js";import"./vendor-utils.BlEnRQrd.js";import"./vendor-ui-display.BT2Z6Vpo.js";import"./vendor-query.CfjDb5WU.js";import"./vendor-media.DY6E_qVO.js";import"./vendor-charts.RWeJ_I16.js";import"./vendor-motion.DCvbjL6b.js";const O={enableHighPass:!0,enableBandpass:!1,enableNoiseGate:!1,enableRNNoise:!1,highPassFrequency:80,bandpassLowFreq:80,bandpassHighFreq:4500,noiseGateThreshold:-50};class ${constructor(e={}){t(this,"audioContext",null),t(this,"sourceNode",null),t(this,"destinationNode",null),t(this,"inputStream",null),t(this,"highPassFilter",null),t(this,"lowPassFilter",null),t(this,"noiseGateNode",null),t(this,"rnnoiseModule",null),t(this,"rnnoiseProcessor",null),t(this,"rnnoiseState",null),t(this,"config"),t(this,"isInitialized",!1),this.config={...O,...e}}async initialize(e){this.inputStream=e;try{const n=e.getAudioTracks()[0],s=n.getSettings().sampleRate||24e3;this.audioContext=new AudioContext({sampleRate:s}),this.sourceNode=this.audioContext.createMediaStreamSource(e),this.destinationNode=this.audioContext.createMediaStreamDestination();let r=this.sourceNode;if(this.config.enableHighPass&&(this.highPassFilter=this.createHighPassFilter(),r.connect(this.highPassFilter),r=this.highPassFilter),this.config.enableBandpass&&(this.lowPassFilter=this.createLowPassFilter(),r.connect(this.lowPassFilter),r=this.lowPassFilter),this.config.enableNoiseGate)try{await this.audioContext.audioWorklet.addModule("/worklets/noise-gate-processor.js"),this.noiseGateNode=new AudioWorkletNode(this.audioContext,"noise-gate-processor"),this.noiseGateNode.port.postMessage({threshold:this.config.noiseGateThreshold,attackTime:.005,releaseTime:.05}),r.connect(this.noiseGateNode),r=this.noiseGateNode}catch(t){r=this.createFallbackNoiseGate(r)}if(this.config.enableRNNoise)try{await this.initializeRNNoise(),this.rnnoiseProcessor&&(r.connect(this.rnnoiseProcessor),r=this.rnnoiseProcessor)}catch(t){}return r.connect(this.destinationNode),this.isInitialized=!0,this.destinationNode.stream}catch(t){throw t}}createHighPassFilter(){const e=this.audioContext.createBiquadFilter();return e.type="highpass",e.frequency.value=this.config.highPassFrequency,e.Q.value=.7071,e}createLowPassFilter(){const e=this.audioContext.createBiquadFilter();return e.type="lowpass",e.frequency.value=this.config.bandpassHighFreq,e.Q.value=.7071,e}createFallbackNoiseGate(e){const t=this.audioContext.createAnalyser();t.fftSize=256;const n=this.audioContext.createGain();e.connect(t);const s=this.audioContext.createScriptProcessor(2048,1,1),r=new Float32Array(t.fftSize);return s.onaudioprocess=e=>{t.getFloatTimeDomainData(r);let s=0;for(let t=0;t<r.length;t++)s+=r[t]*r[t];const i=Math.sqrt(s/r.length),a=20*Math.log10(Math.max(i,1e-10))>this.config.noiseGateThreshold?1:0;n.gain.setTargetAtTime(a,this.audioContext.currentTime,.01);const o=e.inputBuffer.getChannelData(0);e.outputBuffer.getChannelData(0).set(o)},t.connect(s),s.connect(n),n}async initializeRNNoise(){this.config.enableRNNoise=!1}setNoiseGateThreshold(e){this.config.noiseGateThreshold=e,this.noiseGateNode&&this.noiseGateNode.port.postMessage({threshold:e})}setFilterEnabled(e,t){}getAudioLevel(){return{input:0,output:0}}async cleanup(){this.inputStream&&(this.inputStream.getTracks().forEac
2h(e=>{e.stop(),e.enabled=!1}),this.inputStream=null);try{if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.highPassFilter&&(this.highPassFilter.disconnect(),this.highPassFilter=null),this.lowPassFilter&&(this.lowPassFilter.disconnect(),this.lowPassFilter=null),this.noiseGateNode&&(this.noiseGateNode.disconnect(),this.noiseGateNode=null),this.rnnoiseProcessor&&(this.rnnoiseProcessor.disconnect(),this.rnnoiseProcessor=null),this.rnnoiseState&&this.rnnoiseModule&&(this.rnnoiseModule._rnnoise_destroy(this.rnnoiseState),this.rnnoiseState=null),this.destinationNode&&(this.destinationNode.disconnect(),this.destinationNode=null),this.audioContext)try{"suspended"===this.audioContext.state&&await this.audioContext.resume(),await this.audioContext.close()}catch(e){}finally{this.audioContext=null}this.isInitialized=!1}catch(t){}}get initialized(){return this.isInitialized}}const L="https://qzsjapqjvrpoctacudud.supabase.co".replace(/\/$/,"");class D extends Error{constructor(e,n,s,r){super(`${e} failed (${n}): ${"object"==typeof s&&s&&"error"in s?String(s.error):"object"==typeof s&&s&&"message"in s?String(s.message):r}`),t(this,"status"),t(this,"payload"),this.name="EdgeFunctionError",this.status=n,this.payload=s}}async function G(e,t){const n=await fetch(`${L}/functions/v1/${e}`,{method:"POST",headers:{"Content-Type":"application/json",apikey:m,...t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{}},body:JSON.stringify(t.body??{}),signal:t.signal,keepalive:t.keepalive}),s=await n.text();let r=s;try{r=s?JSON.parse(s):null}catch{r=s}if(!n.ok)throw new D(e,n.status,r,s||n.statusText);return r}const Q=e=>{var t;return e.response_id||(null==(t=e.response)?void 0:t.id)||e.item_id||""},H=e=>{var t,n,s,r,i;return(e.transcript||e.delta||(null==(i=null==(r=null==(s=null==(n=null==(t=e.response)?void 0:t.output)?void 0:n[0])?void 0:s.content)?void 0:r[0])?void 0:i.transcript)||"").trim()};class U{constructor(e,n,s,r,i){t(this,"pc",null),t(this,"dc",null),t(this,"audioElement",null),t(this,"mediaStream",null),t(this,"audioProcessor",null),t(this,"lastResponseCreateTime",0),t(this,"fullSystemPrompt",""),t(this,"isConnected",!1),t(this,"sessionStarted",!1),t(this,"isInterviewEnded",!1),t(this,"questionCount",1),t(this,"currentAiTranscript",""),t(this,"lastSavedQuestion",""),t(this,"currentResponseId",""),t(this,"userId",null),t(this,"finalTimingReached",!1),t(this,"savedQuestionOrders",new Set),t(this,"savingInProgress",new Map),t(this,"lastProcessedResponseId",""),t(this,"interview",null),t(this,"askedQuestions",[]),t(this,"initialGreetingSent",!1),t(this,"connectionStateChangeHandler",null),t(this,"iceConnectionStateChangeHandler",null),t(this,"dcMessageHandler",null),t(this,"onMessage",null),t(this,"onError",null),t(this,"onConnectionLost",null),t(this,"onConnectionQuality",null),t(this,"onTokenRefreshFailed",null),t(this,"onTokenRefreshed",null),t(this,"statsInterval",null),t(this,"ambientNoiseLevel",null),t(this,"interviewId",""),t(this,"pendingUserResponses",new Map),t(this,"questionSavePromises",new Map),t(this,"currentAnsweringQuestionOrder",0),t(this,"accessToken",""),t(this,"tokenRefreshInterval",null),t(this,"tokenExpiresAt",0),t(this,"tokenRefreshInFlight",null),t(this,"TOKEN_REFRESH_BUFFER_SEC",300),t(this,"TOKEN_REFRESH_CHECK_MS",6e4),t(this,"interviewContext",null),this.interviewId=e,this.accessToken=n,this.onMessage=r,this.onError=i,this.userId=s}canSendResponseCreate(){if(this.finalTimingReached)return!1;const e=Date.now();return!(e-this.lastResponseCreateTime<1500)&&(this.lastResponseCreateTime=e,!0)}async handleDataChannelMessage(e){var t,n,s,r,i,a,o,l,c,d,u,h,p,f,m,g,v,x,b,w,y,k,S;if(e.type&&"string"==typeof e.type&&(this.sessionStarted||"session.created"===e.type)&&!this.isInterviewEnded)switch(e.type){case"session.created":if(!this.fullSystemPrompt||this.fullSystemPrompt.length<500)return void(null==(t=this.onError)||t.call(this,"Interview context missing. Please restart the interview."));this.sessionStarted=!0,this.updateInstructions(this.fullSystemPrompt);break;case"response.created":if(this.finalTimingReached)return;this.currentAiTranscript="",this.currentResponseId=Q(e);break;case"response.audio_transcript.delta":case"response.output_audio_transcript.delta":{const t=(null==(n=e.delta)?void 0:n.trim())||"";if(t){Q(e)!==this.currentResponseId&&this.currentResponseId||(this.currentAiTranscript+=t,null==(s=this.onMessage)||s.call(this,{type:"ai_transcript",text:t}))}break}case"response.audio_transcript.done":case"response.output_audio_transcript.done":{let t=H(e)||this.currentAiTranscript.trim();if(!t||t.length<10)return void(this.currentAiTranscript="");if(this.lastProcessedResponseId===this.currentResponseId&&this.currentResponseId)return void(this.currentAiTranscript="");if(this.lastSavedQuestion===t)return void(this.currentAiTranscript="");const n=t.toLowerCase();if((n.includes("i'm interviewing you")||n.includes("im interviewing you")||n.includes("interviewing you from")||n.includes("let's start with a brief warm-up")||n.includes("let me start by introducing"))&&this.askedQuestions.some(e=>{const t=e.toLowerCase();return t.includes("i'm interviewing you")||t.includes("interviewing you from")||t.includes("let's start with a brief warm-up")})){if(this.currentAiTranscript="",!this.canSendResponseCreate())return;return void this.safeSend({type:"response.create",response:{output_modalities:["audio"],instructions:"You already introduced yourself and greeted the candidate. Continue with the next interview question without repeating the introduction or greeting."}})}try{await this.saveAIQuestion(t);const e=this.questionCount-1,n=this.pendingUserResponses.get(e);n&&(null==(r=this.onMessage)||r.call(this,{type:"user_transcript",text:n,questionOrder:e}),this.pendingUserResponses.delete(e)),await new Promise(e=>setTimeout(e,200)),this.lastSavedQuestion=t,this.lastProcessedResponseId=this.currentResponseId,this.askedQuestions.push(t),this.askedQuestions.length>60&&this.askedQuestions.shift(),null==(i=this.onMessage)||i.call(this,{type:"ai_speech_completed",questionOrder:this.questionCount}),this.questionCount++}catch(T){}this.currentAiTranscript="",this.currentResponseId="";break}case"conversation.item.input_audio_transcription.completed":{const t=(null==(a=e.transcript)?void 0:a.trim())||"";if(this.finalTimingReached&&!t)return;if(!t)break;const n=this.currentAnsweringQuestionOrder>0?this.currentAnsweringQuestionOrder:this.questionCount-1,s=this.questionSavePromises.get(n);if(s)try{await s}catch(T){this.pendingUserResponses.set(n,t)}this.pendingUserResponses.has(n)||null==(o=this.onMessage)||o.call(this,{type:"user_transcript",text:t,questionOrder:n});break}case"input_audio_buffer.speech_started":this.currentAnsweringQuestionOrder=this.questionCount-1,null==(l=this.onMessage)||l.call(this,{type:"user_speaking_started"});break;case"input_audio_buffer.speech_stopped":if(this.finalTimingReached)return;null==(c=this.onMessage)||c.call(this,{type:"user_speaking_stopped"});break;case"input_audio_buffer.committed":case"response.text.delta":case"response.output_text.delta":case"response.text.done":case"response.output_text.done":case"conversation.item.created":case"rate_limits.updated":case"response.output_item.added":case"response.output_item.done":case"response.content_part.added":case"response.content_part.done":break;case"session.updated":if(null==(d=e.session)?void 0:d.instructions){const t=e.session.instructions.length,n=e.session.instructions.toLowerCase(),s=n.includes("resume")&&n.includes("experience"),r=n.includes("job description")||n.includes("role:");if(t<1e3||!s||!r)return void(this.fullSystemPrompt&&this.fullSystemPrompt.length>1e3?setTimeout(()=>{this.updateInstructions(this.fullSystemPrompt)},1e3):null==(u=this.onError)||u.call(this,"â ï¸ Interview context incomplete. Please restart."));const i=(null==(p=null==(h=this.interview)?void 0:h.profile)?void 0:p.full_name)||(null==(m=null==(f=this.interviewContext)?void 0:f.resumeContent)?void 0:m.substring(0,50))||"Candidate",a=(null==(g=this.interview)?void 0:g.role_title)||"position",o=(null==(v=this.interview)?void 0:v.company_name)||"the company";if(this.initialGreetingSent){if(this.askedQuestions.length>0){const e=this.askedQuestions.map((e,t)=>`Q${t+1}: ${e.substring(0,150)}...`).join("\n");if(!this.canSendResponseCreate())return;this.safeSend({type:"response.create",response:{output_modalities:["audio"],instructions:`IMPORTANT: You have already asked ${this.askedQuestions.length} questions in this interview. \nDO NOT repeat any of these questions or ask the opening greeting again.\n\nPrevious questions asked:\n${e}\n\nContinue the interview with a NEW question that follows naturally from the conversation. Do NOT introduce yourself again.`}})}}else{if(this.initialGreetingSent=!0,!this.canSendResponseCreate())return;this.safeSend({type:"response.create",response:{output_modalities:["audio"],instructions:`Begin interview with a warm greeting: Hi ${i}, I'm interviewing you from ${o} for the ${a} position. Then immediately proceed to ask your first warm-up question about their background. Do NOT wait for a greeting response from the candidate - just start the conversation naturally.`}})}null==(x=this.onMessage)||x.call(this,{type:"session_ready"})}break;case"response.audio.done":null==(b=this.onMessage)||b.call(this,{type:"ai_audio_done"});break;case"response.done":{const t=H(e);t&&!this.currentAiTranscript&&(this.currentAiTranscript=t,await this.handleDataChannelMessage({type:"response.output_audio_transcript.done",transcript:t,response_id:Q(e)}));break}case"error":null==(y=this.onError)||y.call(this,(null==(w=e.error)?void 0:w.message)||"Unknown OpenAI error");break;default:!(null==(k=e.type)?void 0:k.startsWith("response."))&&(null==(S=e.type)||S.startsWith("conversation."))}}parseJwtExp(e){try{const t=e.split(".")[1];if(!t)return 0;const n=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")));return"number"==typeof n.exp?n.exp:0}catch{return 0}}getAccessToken(){return this.accessToken}async refreshAccessTokenNow(){var e,t,n,s,r;for(let a=1;a<=3;a++)try{let{data:r,error:i}=await g.auth.getSession(),a=(null==(e=null==r?void 0:r.session)?void 0:e.access_token)??null,o=a?this.parseJwtExp(a):0;const l=Math.floor(Date.now()/1e3);if(!a||o-l<this.TOKEN_REFRESH_BUFFER_SEC){const e=await g.auth.refreshSession();if(e.error)throw e.error;a=(null==(n=null==(t=e.data)?void 0:t.session)?void 0:n.access_token)??null,o=a?this.parseJwtExp(a):0}if(!a)throw new Error("No access token returned from Supabase");const c=a!==this.accessToken;return this.accessToken=a,this.tokenExpiresAt=o,c&&(null==(s=this.onTokenRefreshed)||s.call(this,a)),!0}catch(i){a<3&&await new Promise(e=>setTimeout(e,1e3*a))}return null==(r=this.onTokenRefreshFailed)||r.call(this,3),!1}async maybeRefreshAccessToken(){if(this.isInterviewEnded)return;if(this.tokenRefreshInFlight)return this.tokenRefreshInFlight;const e=Math.floor(Date.now()/1e3),t=this.tokenExpiresAt||this.parseJwtExp(this.accessToken);return this.tokenExpiresAt=t,t&&t-e>this.TOKEN_REFRESH_BUFFER_SEC?void 0:(this.tokenRefreshInFlight=(async()=>{try{await this.refreshAccessTokenNow()}finally{this.tokenRefreshInFlight=null}})(),this.tokenRefreshInFlight)}startTokenRefreshMonitor(){this.stopTokenRefreshMonitor(),this.tokenExpiresAt=this.parseJwtExp(this.accessToken),this.tokenRefreshInterval=setInterval(()=>{this.maybeRefreshAccessToken()},this.TOKEN_REFRESH_CHECK_MS)}stopTokenRefreshMonitor(){this.tokenRefreshInterval&&(clearInterval(this.tokenRefreshInterval),this.tokenRefreshInterval=null)}async connect(){var e,t,n;try{await this.maybeRefreshAccessToken(),this.startTokenRefreshMonitor();const a=await G("realtime-interview",{accessToken:this.accessToken,body:{interviewId:this.interviewId,interview_id:this.interviewId,accessToken:this.accessToken,ambient_noise_level:this.ambientNoiseLevel}});if(!a){throw new Error("Failed to get ephemeral token: Empty server response")}
2const o=a.ephemeralToken,l=a.instructions;if(this.interview=a.interview,!o||!o.startsWith("ek_"))throw new Error("Invalid ephemeral token received from server");if(!l)throw new Error("â ï¸ No instructions received; interview context missing");if(l.length<500)throw new Error("Interview context is incomplete. Please try again or contact support.");this.fullSystemPrompt=l;try{const{data:n}=await g.from("interview_sessions").select("question_order, question, user_response").eq("interview_id",this.interviewId).order("question_order",{ascending:!0});if(n&&n.length>0){if(this.questionCount=n.length+1,"in_progress"===(null==(e=this.interview)?void 0:e.status)&&(null==(t=this.interview)?void 0:t.started_at)){const e=new Date(this.interview.started_at).getTime(),t=Date.now(),n=Math.floor((t-e)/1e3);60*(this.interview.duration_minutes||30)-n<=15&&(this.finalTimingReached=!0)}this.askedQuestions=n.map(e=>e.question).filter(e=>Boolean(e)),this.askedQuestions.length>0&&(this.initialGreetingSent=!0),this.lastProcessedResponseId="",this.currentResponseId=""}}catch(s){}if(l.length,this.pc=new RTCPeerConnection,this.connectionStateChangeHandler=()=>{var e,t,n;const s=null==(e=this.pc)?void 0:e.connectionState;"connected"===s&&this.startQualityMonitor(),"failed"===s?(this.stopQualityMonitor(),this.handleConnectionError(new Error("Connection failed")),this.isInterviewEnded||null==(t=this.onConnectionLost)||t.call(this)):"closed"!==s||this.isInterviewEnded||(this.stopQualityMonitor(),null==(n=this.onConnectionLost)||n.call(this))},this.iceConnectionStateChangeHandler=()=>{},this.pc.addEventListener("connectionstatechange",this.connectionStateChangeHandler),this.pc.addEventListener("iceconnectionstatechange",this.iceConnectionStateChangeHandler),this.pc.ontrack=e=>{this.audioElement||(this.audioElement=document.createElement("audio"),this.audioElement.autoplay=!0,this.audioElement.volume=.8,"setSinkId"in this.audioElement&&"function"==typeof this.audioElement.setSinkId&&this.audioElement.setSinkId("default").catch(e=>{})),this.audioElement.srcObject=e.streams[0]},this.dc=this.pc.createDataChannel("oai-events"),this.dcMessageHandler=async e=>{try{const t=JSON.parse(e.data);await this.handleDataChannelMessage(t)}catch(s){}},this.dc.addEventListener("message",this.dcMessageHandler),this.dc.addEventListener("open",()=>{var e;const t=(null==(e=this.fullSystemPrompt)?void 0:e.toLowerCase())||"";t.includes("resume")&&t.includes("experience"),t.includes("job description")||t.includes("role:");!this.fullSystemPrompt||this.fullSystemPrompt.length}),this.dc.addEventListener("close",()=>{}),this.dc.addEventListener("error",e=>{this.handleConnectionError(e)}),!this.mediaStream){const e=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:24e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});try{this.audioProcessor=new $({enableHighPass:!0,enableBandpass:!0,enableNoiseGate:!0,enableRNNoise:!1,highPassFrequency:80,bandpassLowFreq:80,bandpassHighFreq:4500,noiseGateThreshold:-40}),this.mediaStream=await this.audioProcessor.initialize(e)}catch(r){this.mediaStream=e}}const c=this.mediaStream.getAudioTracks();if(0===c.length)throw new Error("No audio track available after processing");this.pc.addTrack(c[0],this.mediaStream);const d=await this.pc.createOffer();await this.pc.setLocalDescription(d);const u=new AbortController,h=setTimeout(()=>u.abort(),3e4);try{const e=await fetch("https://api.openai.com/v1/realtime/calls",{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/sdp"},body:d.sdp,signal:u.signal});if(clearTimeout(h),!e.ok){const t=await e.text();if(401===e.status)throw new Error("Authentication failed. Please restart the interview.");if(429===e.status)throw new Error("OpenAI API rate limit exceeded. Please try again in a few moments.");if(e.status>=500)throw new Error("OpenAI service temporarily unavailable. Please try again.");throw new Error(`OpenAI API error: ${e.status} - ${t}`)}const t=await e.text();if(!t||t.length<100)throw new Error("Invalid response from OpenAI. Please try again.");const n={type:"answer",sdp:t};await this.pc.setRemoteDescription(n)}catch(i){if(clearTimeout(h),"AbortError"===i.name)throw new Error("Connection to OpenAI timed out. Please check your internet and try again.");throw i}null==(n=this.onMessage)||n.call(this,{type:"connected"}),this.isConnected=!0}catch(i){throw this.handleConnectionError(i),i}}safeSend(e){this.dc&&"open"===this.dc.readyState&&this.dc.send(JSON.stringify(e))}updateInstructions(e){this.safeSend({type:"session.update",session:{type:"realtime",model:"gpt-realtime",output_modalities:["audio"],instructions:e,audio:{input:{format:{type:"audio/pcm",rate:24e3},transcription:{model:"gpt-4o-mini-transcribe"},turn_detection:{type:"server_vad",threshold:.55,prefix_padding_ms:700,silence_duration_ms:2600}},output:{format:{type:"audio/pcm",rate:24e3},voice:"alloy"}}}})}sendMessage(e){this.safeSend({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:e}]}})}startQualityMonitor(){if(this.statsInterval||!this.pc)return;let e=0,t=0;this.statsInterval=setInterval(async()=>{var n;if(this.pc&&"connected"===this.pc.connectionState)try{const s=await this.pc.getStats();let r=0,i=0,a=0,o=0;
2s.forEach(e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&(r+=e.packetsLost||0,i+=e.packetsReceived||0,a=Math.max(a,e.jitter||0)),"candidate-pair"===e.type&&"succeeded"===e.state&&e.currentRoundTripTime&&(o=e.currentRoundTripTime)});const l=r-e,c=i-t;e=r,t=i;const d=c>0?l/(c+l):0;let u="good";d>.05||a>.05||o>.4?u="poor":(d>.02||a>.03||o>.25)&&(u="fair"),null==(n=this.onConnectionQuality)||n.call(this,u)}catch{}},5e3)}stopQualityMonitor(){this.statsInterval&&(clearInterval(this.statsInterval),this.statsInterval=null)}handleConnectionError(e){var t;null==(t=this.onError)||t.call(this,`Connection error: ${e.message||"Unknown error"}`),this.cleanup()}injectTimerContext(e){e.includes("TIMING_SIGNAL_FINAL_15S")&&(this.finalTimingReached=!0),this.safeSend({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:e}]}})}async saveAIQuestion(e){const t=this.questionCount;if(this.savedQuestionOrders.has(t))return;const n=this.savingInProgress.get(t);if(n)return void(await n);const s=this.performQuestionSave(e,t);this.savingInProgress.set(t,s),this.questionSavePromises.set(t,s);try{await s,this.savedQuestionOrders.add(t)}finally{this.savingInProgress.delete(t),this.questionSavePromises.delete(t)}}async performQuestionSave(e,t){var n;if(t<=0)throw new Error("Question count must be positive");for(let r=1;r<=3;r++)try{const{data:n,error:s}=await g.from("interview_sessions").upsert({interview_id:this.interviewId,question_order:t,question:e,message_type:"ai_question",user_response:null,transcription:null},{onConflict:"interview_id,question_order",ignoreDuplicates:!1}).select().single();if(s){if("23505"===String(s.code))return;if(r<3){await new Promise(e=>setTimeout(e,300*r));continue}throw s}if(n&&(n.id||n.question_order===t))return;const{data:i}=await g.from("interview_sessions").select("id, question_order").eq("interview_id",this.interviewId).eq("question_order",t).maybeSingle();if(null==i?void 0:i.id)return;throw new Error(`No id returned and verification failed for question #${t}`)}catch(s){if("23505"===String(null==s?void 0:s.code)||(null==(n=null==s?void 0:s.message)?void 0:n.includes("duplicate key")))return;if(r>=3)throw s;await new Promise(e=>setTimeout(e,300*r))}}cleanup(){this.stopTokenRefreshMonitor(),this.savedQuestionOrders.clear(),this.savingInProgress.clear(),this.pendingUserResponses.clear(),this.questionSavePromises.clear(),this.currentAnsweringQuestionOrder=0,this.lastProcessedResponseId="",this.lastSavedQuestion="",this.initialGreetingSent=!1;try{if(this.audioProcessor&&(this.audioProcessor.cleanup(),this.audioProcessor=null),this.mediaStream){try{const e=this.mediaStream.getTracks();for(const n of e)n.stop(),n.enabled=!1,this.mediaStream.removeTrack(n);const t=this.mediaStream.getTracks();t.length>0&&t.forEach(e=>{var t;e.stop(),e.enabled=!1,null==(t=this.mediaStream)||t.removeTrack(e)})}catch(e){}this.mediaStream=null}if(this.dc){try{"open"!==this.dc.readyState&&"connecting"!==this.dc.readyState||this.dc.close()}catch(e){}this.dc=null}if(this.stopQualityMonitor(),this.pc){try{"closed"!==this.pc.connectionState&&this.pc.close()}catch(e){}this.pc=null}if(this.audioElement){try{this.audioElement.pause(),this.audioElement.srcObject=null,this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)}catch(e){}this.audioElement=null}this.isConnected=!1}catch(t){this.mediaStream=null,this.dc=null,this.pc=null,this.audioElement=null,this.isConnected=!1}}async disconnect(){this.isInterviewEnded||(this.isInterviewEnded=!0,await new Promise(e=>setTimeout(e,1500)),this.finalTimingReached,this.cleanup(),await new Promise(e=>setTimeout(e,100)))}}const z={dark:{barActive:["#a78bfa","#7c3aed","#c4b5fd","#8b5cf6","#ddd6fe"],barIdle:"rgba(255,255,255,0.12)",glowColor:"rgba(139,92,246,0.55)",outerRingActive:"rgba(139,92,246,0.18)",outerRingIdle:"rgba(255,255,255,0.05)",pulseRing:"rgba(139,92,246,0.12)",iconColor:"#a78bfa",labelActive:"#c4b5fd",labelIdle:"rgba(255,255,255,0.38)",bgOverlay:"rgba(139,92,246,0.06)"},light:{barActive:["#c4b5fd","#8b5cf6","#a78bfa","#7c3aed","#ddd6fe"],barIdle:"rgba(255,255,255,0.20)",glowColor:"rgba(167,139,250,0.65)",outerRingActive:"rgba(167,139,250,0.22)",outerRingIdle:"rgba(255,255,255,0.08)",pulseRing:"rgba(167,139,250,0.14)",iconColor:"#c4b5fd",labelActive:"#e9d5ff",labelIdle:"rgba(255,255,255,0.50)",bgOverlay:"rgba(167,139,250,0.08)"}},W=28,J=80,K=154,Y=({isActive:e,label:t,size:n="md"})=>{const{resolvedTheme:i}=v(),a="light"===i?z.light:z.dark,o=r.useRef(null),l=r.useRef(0),c=r.useRef(Array.from({length:W},(e,t)=>
2t/W*Math.PI*2)),d=r.useRef(Array(W).fill(.15)),u=r.useRef(Array(W).fill(.15)),h="sm"===n?.6:"lg"===n?1.35:1,p=Math.round(240*h),f=Math.round(192*h),m=Math.round(144*h);return r.useEffect(()=>{u.current=e?Array.from({length:W},(e,t)=>.35+.55*Math.abs(Math.sin(t/W*Math.PI))):Array(W).fill(.12)},[e]),r.useEffect(()=>{const t=o.current;if(!t)return;const n=t.getContext("2d");if(!n)return;const s=window.devicePixelRatio||1;t.width=K*s,t.height=J*s,t.style.width="154px",t.style.height="80px",n.scale(s,s);let r=0;const i=()=>{n.clearRect(0,0,K,J);for(let t=0;t<W;t++){d.current[t]+=.08*(u.current[t]-d.current[t]);const s=e?.048+.002*t:.012;c.current[t]+=s;const i=d.current[t]*J*(.6+.4*Math.sin(c.current[t])),o=Math.max(3,i),l=5.5*t,h=(J-o)/2,p=Math.floor((t/W*a.barActive.length+.01*r)%a.barActive.length);if(e){const e=n.createLinearGradient(l,h,l,h+o);e.addColorStop(0,a.barActive[p%a.barActive.length]),e.addColorStop(1,a.barActive[(p+1)%a.barActive.length]),n.fillStyle=e,n.shadowColor=a.glowColor,n.shadowBlur=6}else n.fillStyle=a.barIdle,n.shadowColor="transparent",n.shadowBlur=0;const f=Math.min(1.5,o/2);n.beginPath(),n.roundRect(l,h,3,o,f),n.fill(),n.shadowBlur=0}r++,l.current=requestAnimationFrame(i)};return i(),()=>{cancelAnimationFrame(l.current)}},[e,a]),s.jsxs("div",{className:"flex flex-col items-center justify-center select-none",style:{gap:"1.25rem"},"aria-label":e?"Audio active":"Audio idle",role:"img",children:[s.jsxs("div",{className:"relative flex items-center justify-center rounded-full transition-all duration-700",style:{width:p,height:p,background:e?a.outerRingActive:a.outerRingIdle,boxShadow:e?`0 0 0 0 ${a.pulseRing}, 0 0 40px ${a.glowColor}`:"none",animation:e?"sw-pulse-outer 2.4s ease-in-out infinite":"none"},children:[s.jsx("div",{className:"absolute rounded-full transition-all duration-500",style:{width:f,height:f,background:e?`radial-gradient(circle, ${a.bgOverlay}, transparent 70%)`:"transparent",border:`1px solid ${e?a.outerRingActive:"transparent"}`,animation:e?"sw-spin-slow 8s linear infinite":"none"}}),s.jsx("div",{className:"relative flex flex-col items-center justify-center rounded-full overflow-hidden transition-all duration-500",style:{width:m,height:m,background:e?`radial-gradient(circle at 50% 60%, ${a.bgOverlay} 0%, transparent 70%)`:"transparent",border:`1.5px solid ${e?a.outerRingActive:a.barIdle}`},children:s.jsx("canvas",{ref:o,"aria-hidden":!0,style:{display:"block",width:K,height:J}})}),e&&[0,1,2,3].map(e=>s.jsx("div",{className:"absolute rounded-full",style:{width:5,height:5,background:a.barActive[e%a.barActive.length],top:50+46*Math.sin(e/4*Math.PI*2)+"%",left:50+46*Math.cos(e/4*Math.PI*2)+"%",transform:"translate(-50%, -50%)",opacity:.7,animation:`sw-dot-pulse 1.8s ease-in-out ${.45*e}s infinite`,boxShadow:`0 0 6px ${a.glowColor}`}},e))]}),t&&s.jsx("p",{className:"text-xs font-semibold tracking-widest uppercase transition-colors duration-300",style:{color:e?a.labelActive:a.labelIdle,fontFamily:"'Roboto Slab', serif",letterSpacing:"0.14em",textShadow:e?`0 0 12px ${a.glowColor}`:"none"},children:t}),s.jsx("style",{children:`\n @keyframes sw-pulse-outer {\n 0%, 100% { box-shadow: 0 0 0 0 ${a.pulseRing}, 0 0 28px ${a.glowColor}; }\n 50% { box-shadow: 0 0 0 14px transparent, 0 0 48px ${a.glowColor}; }\n }\n @keyframes sw-spin-slow {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sw-dot-pulse {\n 0%, 100% { transform: translate(-50%, -50%) scale(1); opacity: 0.7; }\n 50% { transform: translate(-50%, -50%) scale(1.6); opacity: 1; }\n }\n `})]})};
2function V({error:e,errorInfo:t,fallbackTitle:n,showDetails:r,retryCount:i,onRetry:a,onGoHome:o,onToggleDetails:l,p:c}){return s.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 transition-colors duration-300",style:{background:c.sectionBg},children:[s.jsx("div",{"aria-hidden":!0,className:"fixed inset-0 pointer-events-none",style:{backgroundImage:[`linear-gradient(${c.gridLine} 1px, transparent 1px)`,`linear-gradient(90deg, ${c.gridLine} 1px, transparent 1px)`].join(", "),backgroundSize:"40px 40px",zIndex:0}}),s.jsxs("div",{className:"relative z-10 w-full max-w-lg rounded-3xl overflow-hidden",style:{background:c.cardBg,border:`1px solid ${c.cardBorder}`,backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",boxShadow:"0 32px 64px rgba(0,0,0,0.4)"},role:"alert","aria-live":"assertive",children:[s.jsx("div",{style:{background:"linear-gradient(135deg, rgba(220,38,38,0.25), rgba(185,28,28,0.30))",borderBottom:"1px solid rgba(248,113,113,0.20)",padding:"28px 28px 24px"},children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("div",{className:"flex-shrink-0 rounded-2xl flex items-center justify-center",style:{width:52,height:52,background:"rgba(248,113,113,0.15)",border:"1px solid rgba(248,113,113,0.30)"},children:s.jsx(k,{className:"h-6 w-6",style:{color:c.redAccent},"aria-hidden":!0})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] font-bold uppercase tracking-[0.18em] mb-0.5",style:{color:"rgba(248,113,113,0.80)"},children:"Session Error"}),s.jsx("h1",{className:"text-xl font-bold",style:{fontFamily:"'Roboto Slab', serif",color:c.headlineColor},children:n})]})]})}),s.jsxs("div",{className:"p-7 space-y-5",children:[s.jsxs("p",{className:"text-sm leading-relaxed",style:{color:c.bodyText},children:["Something went wrong during your interview session. Your progress has been saved where possible.",i>0&&s.jsxs("span",{style:{color:c.mutedText},children:[" (Retry attempt ",i,")"]})]}),e&&s.jsxs("div",{className:"rounded-xl p-4",style:{background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.18)"},children:[s.jsxs("div",{className:"flex items-start gap-2.5",children:[s.jsx(S,{className:"h-4 w-4 mt-0.5 flex-shrink-0",style:{color:"rgba(248,113,113,0.70)"}}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-xs font-semibold mb-1",style:{color:"rgba(248,113,113,0.80)"},children:"Error message"}),s.jsx("p",{className:"text-sm break-words font-mono",style:{color:c.bodyText},children:e.message||"An unexpected error occurred"})]})]}),(e.stack||(null==t?void 0:t.componentStack))&&s.jsxs("div",{className:"mt-3",children:[s.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1.5 text-xs transition-opacity hover:opacity-80",style:{color:c.mutedText},"aria-expanded":r,children:[r?s.jsx(T,{className:"h-3 w-3","aria-hidden":!0}):s.jsx(N,{className:"h-3 w-3","aria-hidden":!0}),r?"Hide":"Show"," technical details"]}),r&&s.jsxs("div",{className:"mt-3 rounded-lg p-3 overflow-auto max-h-40 text-xs font-mono",style:{background:"rgba(0,0,0,0.30)",color:"rgba(255,255,255,0.45)",lineHeight:1.6},children:[e.stack&&s.jsx("pre",{className:"whitespace-pre-wrap break-words",children:e.stack}),(null==t?void 0:t.componentStack)&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"mt-2 font-bold",style:{color:"rgba(255,255,255,0.60)"},children:"Component Stack:"}),s.jsx("pre",{className:"whitespace-pre-wrap break-words",children:t.componentStack})]})]})]})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 pt-1",children:[s.jsxs("button",{type:"button",onClick:a,className:"flex-1 flex items-center justify-center gap-2 rounded-xl font-semibold text-sm transition-all duration-200 hover:opacity-90 active:scale-[0.98]",style:{height:44,background:c.btnPrimaryBg,color:"#fff",border:"none",boxShadow:"0 4px 20px rgba(124,58,237,0.35)",cursor:"pointer",fontFamily:"inherit"},children:[s.jsx(C,{className:"h-4 w-4","aria-hidden":!0}),"Try Again"]}),s.jsxs("button",{type:"button",onClick:o,className:"flex-1 flex items-center justify-center gap-2 rounded-xl font-semibold text-sm transition-all duration-200 hover:opacity-80 active:scale-[0.98]",style:{height:44,background:c.stepLockedBg,border:`1.5px solid ${c.stepLockedBorder}`,color:c.bodyText,cursor:"pointer",fontFamily:"inherit"},children:[s.jsx(_,{className:"h-4 w-4","aria-hidden":!0}),"Go to Dashboard"]})]}),s.jsxs("p",{className:"text-xs text-center",style:{color:c.mutedText},children:["If this problem persists, please"," ",s.jsx("a",{href:"mailto:[email protected]",className:"underline underline-offset-2 transition-opacity hover:opacity-80",style:{color:c.accentText},children:"contact support"}),"."]})]})]})]})}class X extends r.Component{constructor(e){super(e),t(this,"MAX_RETRIES",3),t(this,"handleRetry",()=>{var e,t;this.state.retryCount>=this.MAX_RETRIES?this.handleGoHome():(this.setState(e=>
2({hasError:!1,error:null,errorInfo:null,showDetails:!1,retryCount:e.retryCount+1})),null==(t=(e=this.props).onRetry)||t.call(e))}),t(this,"handleGoHome",()=>{window.location.href="/dashboard"}),t(this,"handleToggleDetails",()=>{this.setState(e=>({showDetails:!e.showDetails}))}),this.state={hasError:!1,error:null,errorInfo:null,showDetails:!1,retryCount:0}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){this.setState({errorInfo:t})}render(){if(this.state.hasError){const e="light"===(this.props.resolvedTheme??"dark")?x.light:x.dark;return s.jsx(V,{error:this.state.error,errorInfo:this.state.errorInfo,fallbackTitle:this.props.fallbackTitle??"Interview Session Error",showDetails:this.state.showDetails,retryCount:this.state.retryCount,onRetry:this.handleRetry,onGoHome:this.handleGoHome,onToggleDetails:this.handleToggleDetails,p:e})}return this.props.children}}const Z=({interviewId:e,connectionState:t,reconnectAttempt:n,maxReconnectAttempts:a=3,onRetry:o,onAbandon:l})=>{const c=i(),[d,u]=r.useState(!1),[h,p]=r.useState(!1),[f,m]=r.useState(0);r.useEffect(()=>{if("reconnecting"!==t)return;m(5);const e=setInterval(()=>{m(t=>t<=1?(clearInterval(e),0):t-1)},1e3);return()=>clearInterval(e)},[t,n]);return"connected"===t?null:s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.72)",backdropFilter:"blur(10px)"},role:"alertdialog","aria-modal":"true","aria-label":"Connection issue",children:s.jsxs("div",{className:"w-full max-w-sm rounded-2xl overflow-hidden",style:{background:"rgba(21,0,43,0.98)",border:"reconnecting"===t?"1px solid rgba(245,158,11,0.45)":"1px solid rgba(239,68,68,0.45)"},children:[s.jsx("div",{style:{height:3,background:"reconnecting"===t?"linear-gradient(90deg,#f59e0b,#f97316)":"linear-gradient(90deg,#ef4444,#dc2626)"}}),s.jsxs("div",{className:"p-6 flex flex-col items-center gap-4 text-center",children:["reconnecting"===t?s.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"rgba(245,158,11,0.15)",border:"1px solid rgba(245,158,11,0.35)"},children:s.jsx(C,{className:"w-7 h-7 animate-spin",style:{color:"#f59e0b"}})}):s.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"rgba(239,68,68,0.15)",border:"1px solid rgba(239,68,68,0.35)"},children:s.jsx(j,{className:"w-7 h-7",style:{color:"#f87171"}})}),s.jsx("h2",{className:"text-lg font-bold",style:{fontFamily:"'Roboto Slab', serif",color:"#ffffff"},children:"reconnecting"===t?"Connection lost â reconnectingâ¦":"Connection failed"}),s.jsx("p",{className:"text-sm leading-relaxed",style:{color:"rgba(255,255,255,0.65)"},children:"reconnecting"===t?s.jsxs(s.Fragment,{children:["Attempt ",n+1," of ",a,"."," ",f>0?`Retrying in ${f}sâ¦`:"Trying nowâ¦"]}):h?"Credits refunded. Redirecting to dashboardâ¦":"We couldn't restore your interview connection. You can try again manually or exit and get your credits back."}),"reconnecting"===t&&s.jsx("div",{className:"flex gap-2",children:Array.from({length:a}).map((e,t)=>s.jsx("span",{className:"w-2 h-2 rounded-full transition-all duration-300",style:{background:t<n?"#6ee7b7":t===n?"#f59e0b":"rgba(255,255,255,0.20)"}},t))}),"failed"===t&&!h&&s.jsxs("div",{className:"flex flex-col gap-2 w-full",children:[s.jsxs("button",{onClick:o,className:"w-full flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-semibold transition-all hover:opacity-90",style:{background:"linear-gradient(135deg,#7c3aed,#a78bfa)",color:"#ffffff"},children:[s.jsx(C,{className:"w-4 h-4"}),"Try connecting again"]}),s.jsxs("button",{onClick:async()=>{var t;u(!0);try{let s=null;for(let r=0;r<3;r++){const{data:i}=await g.auth.getSession(),o=null==(t=i.session)?void 0:t.access_token;try{await G("revert-interview-session",{accessToken:o,body:{interview_id:e,scenario:"connection_failed",reason:`WebRTC connection failed after ${a} reconnect attempts`}}),s=null;break}catch(n){s=n}r<2&&await new Promise(e=>setTimeout(e,1200*Math.pow(2,r)))}s?(await g.from("pending_credit_refunds").insert({interview_id:e,reason:"connection_failed â revert-interview-session failed after 3 retries",status:"pending"}),b.warning("Your credits will be refunded shortly. Our team has been notified.",{duration:8e3})):(p(!0),b.success("Credits refunded to your account."))}catch(s){b.error("Something went wrong. Please contact support â your credits will be protected.")}finally{u(!1),setTimeout(()=>c("/dashboard"),1800)}},disabled:d,className:"w-full flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-semibold transition-all hover:opacity-90 disabled:opacity-50",style:{background:"rgba(239,68,68,0.15)",border:"1px solid rgba(239,68,68,0.35)",color:"#f87171"},children:[d?s.jsx(E,{className:"w-4 h-4 animate-spin"}):s.jsx(I,{className:"w-4 h-4"}),d?"Refunding creditsâ¦":"Exit & refund my credits"]})]})]})]})})},ee=5e3,te=({open:e,onComplete:t,onCancel:n})=>{const[i,a]=r.useState("requesting"),[o,l]=r.useState(0),[c,d]=r.useState(Array(20).fill(0)),[u,h]=r.useState(null),[p,f]=r.useState(""),m=r.useRef(null),g=r.useRef(null),v=r.useRef(null),x=r.useRef(null),b=r.useRef([]),w=r.useRef(0),y=r.useRef(Array(20).fill(0)),k=r.useRef(!0),S=r.useCallback(()=>{x.current&&cancelAnimationFrame(x.current),m.current&&m.current.getTracks().forEac
2h(e=>e.stop()),v.current&&"closed"!==v.current.state&&v.current.close().catch(()=>{}),x.current=null,m.current=null,g.current=null,v.current=null},[]);r.useEffect(()=>(k.current=!0,()=>{k.current=!1,S()}),[S]),r.useEffect(()=>{e&&(a("requesting"),l(0),d(Array(20).fill(0)),h(null),f(""),b.current=[],y.current=Array(20).fill(0),T())},[e]);const T=async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1},video:!1});if(!k.current)return void e.getTracks().forEach(e=>e.stop());m.current=e;const t=new AudioContext;v.current=t;const n=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=256,s.smoothingTimeConstant=.4,n.connect(s),g.current=s,a("measuring"),w.current=performance.now(),N()}catch(e){if(!k.current)return;const t="NotAllowedError"===(null==e?void 0:e.name)?"Microphone access denied. Please allow access in your browser settings.":"Could not access microphone. Please check it's connected and not in use.";f(t),a("error")}},N=r.useCallback(()=>{if(!k.current||!g.current)return;const e=g.current,t=new Float32Array(e.fftSize),n=performance.now()-w.current,s=Math.min(100,n/ee*100);e.getFloatTimeDomainData(t);let r=0;for(let a=0;a<t.length;a++)r+=t[a]*t[a];const i=Math.sqrt(r/t.length);b.current.push(i);const o=Math.min(1,10*i);if(y.current=[...y.current.slice(1),o],k.current&&(l(s),d([...y.current])),n>=ee){const e=b.current,t=e.reduce((e,t)=>e+t,0)/e.length,n=Math.min(1,t/.15);return S(),void(k.current&&(h(n),a("done"),l(100)))}x.current=requestAnimationFrame(N)},[S]);if(!e)return null;const C=null===u?"":u<.1?"ð¢ Very quiet â great conditions":u<.25?"ð¡ Normal â good to go":u<.5?"ð Noisy â we've adjusted settings":"ð´ Very noisy â consider a quieter spot";return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.75)",backdropFilter:"blur(10px)"},role:"dialog","aria-modal":"true","aria-label":"Microphone check",children:s.jsxs("div",{className:"w-full max-w-sm rounded-2xl overflow-hidden",style:{background:"rgba(21,0,43,0.98)",border:"1px solid rgba(139,92,246,0.40)"},children:[s.jsx("div",{style:{height:3,background:"linear-gradient(90deg,#7c3aed,#a78bfa)"}}),s.jsxs("div",{className:"p-6 flex flex-col items-center gap-5 text-center",children:[s.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"rgba(139,92,246,0.15)",border:"1px solid rgba(139,92,246,0.40)"},children:"error"===i?s.jsx(R,{className:"w-7 h-7",style:{color:"#f87171"}}):"done"===i?s.jsx(A,{className:"w-7 h-7",style:{color:"#6ee7b7"}}):"requesting"===i?s.jsx(E,{className:"w-7 h-7 animate-spin",style:{color:"#a78bfa"}}):s.jsx(P,{className:"w-7 h-7",style:{color:"#a78bfa"}})}),s.jsxs("h2",{className:"text-lg font-bold",style:{fontFamily:"'Roboto Slab', serif",color:"#ffffff"},children:["requesting"===i&&"Checking microphoneâ¦","measuring"===i&&"Measuring environmentâ¦","done"===i&&"All set!","error"===i&&"Microphone issue"]}),s.jsxs("p",{className:"text-sm leading-relaxed",style:{color:"rgba(255,255,255,0.65)"},children:["requesting"===i&&"Please allow microphone access when prompted.","measuring"===i&&"Stay quiet for 5 seconds so we can calibrate audio settings for your environment.","done"===i&&`${C}. We've tuned the interview audio to match your surroundings.`,"error"===i&&p]}),"measuring"===i&&s.jsx("div",{className:"flex items-end justify-center gap-0.5 h-10 w-full",children:c.map((e,t)=>s.jsx("div",{className:"rounded-full transition-all duration-75",style:{width:6,height:`${Math.max(8,36*e)}px`,background:e>.5?"rgba(245,158,11,0.85)":"rgba(139,92,246,0.70)",opacity:.6+.4*e}},t))}),"measuring"===i&&s.jsxs("div",{className:"w-full",children:[s.jsx("div",{className:"w-full h-1.5 rounded-full overflow-hidden",style:{background:"rgba(255,255,255,0.10)"},children:s.jsx("div",{className:"h-full rounded-full transition-all duration-200",style:{width:`${o}%`,background:"linear-gradient(90deg,#7c3aed,#a78bfa)"}})}),s.jsxs("p",{className:"text-xs mt-1.5",style:{color:"rgba(255,255,255,0.40)"},children:[Math.ceil((ee-o/100*ee)/1e3),"s remaining"]})]}),s.jsxs("div",{className:"flex flex-col gap-2 w-full",children:["done"===i&&s.jsx("button",{onClick:()=>t(u),className:"w-full py-3 rounded-xl text-sm font-semibold transition-all hover:opacity-90",style:{background:"linear-gradient(135deg,#7c3aed,#a78bfa)",color:"#ffffff"},children:"Start Interview â"}),"error"===i&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:T,className:"w-full py-3 rounded-xl text-sm font-semibold transition-all hover:opacity-90",style:{background:"linear-gradient(135deg,#7c3aed,#a78bfa)",color:"#ffffff"},children:"Try again"}),s.jsx("button",{onClick:()=>n(),className:"w-full py-2.5 rounded-xl text-sm font-medium",style:{background:"transparent",border:"1px solid rgba(255,255,255,0.15)",color:"rgba(255,255,255,0.55)"},children:"Skip check â use default settings"})]}),("requesting"===i||"measuring"===i)&&s.jsx("button",{onClick:()=>{S(),n()},className:"w-full py-2.5 rounded-xl text-sm font-medium",style:{background:"transparent",border:"1px solid rgba(255,255,255,0.12)",color:"rgba(255,255,255,0.45)"},children:"Skip â use default settings"})]})]})]})})},ne="interview_meta";function se(e){try{const t=sessionStorage.getItem(ne);if(!t)return null;const n=JSON.parse(t);return n.id===e?n:null}catch{return null}}
2const re={dark:{sectionBg:"linear-gradient(160deg, #15002B 0%, #2A044C 50%, #1A0235 100%)",cardBg:"rgba(255,255,255,0.04)",cardBorder:"rgba(255,255,255,0.09)",progressBg:"rgba(255,255,255,0.10)",progressFill:"linear-gradient(to right, #a78bfa, #7c3aed)",headlineColor:"#ffffff",bodyText:"rgba(255,255,255,0.65)",mutedText:"rgba(255,255,255,0.38)",accentText:"#a78bfa",gridLine:"rgba(255,255,255,0.022)",pillBg:"rgba(139,92,246,0.18)",pillBorder:"rgba(139,92,246,0.40)",successBg:"rgba(16,185,129,0.15)",successBorder:"rgba(16,185,129,0.40)",successText:"#6ee7b7",warningBg:"rgba(245,158,11,0.15)",warningBorder:"rgba(245,158,11,0.40)",warningText:"#fbbf24",dangerBorder:"rgba(239,68,68,0.35)",timerNormal:"#a78bfa",timerWarning:"#fbbf24",timerCritical:"#f87171",btnEndBg:"linear-gradient(135deg, #dc2626 0%, #ef4444 100%)",btnEndText:"#ffffff",spinnerColor:"#a78bfa"},light:{sectionBg:"linear-gradient(160deg, #2D0550 0%, #5B1280 50%, #3D0A6E 100%)",cardBg:"rgba(255,255,255,0.07)",cardBorder:"rgba(255,255,255,0.14)",progressBg:"rgba(255,255,255,0.18)",progressFill:"linear-gradient(to right, #c4b5fd, #8b5cf6)",headlineColor:"#ffffff",bodyText:"rgba(255,255,255,0.80)",mutedText:"rgba(255,255,255,0.50)",accentText:"#c4b5fd",gridLine:"rgba(255,255,255,0.038)",pillBg:"rgba(167,139,250,0.22)",pillBorder:"rgba(167,139,250,0.50)",successBg:"rgba(16,185,129,0.18)",successBorder:"rgba(16,185,129,0.45)",successText:"#a7f3d0",warningBg:"rgba(245,158,11,0.18)",warningBorder:"rgba(245,158,11,0.45)",warningText:"#fde68a",dangerBorder:"rgba(239,68,68,0.45)",timerNormal:"#c4b5fd",timerWarning:"#fde68a",timerCritical:"#fca5a5",btnEndBg:"linear-gradient(135deg, #b91c1c 0%, #dc2626 100%)",btnEndText:"#ffffff",spinnerColor:"#c4b5fd"}},ie=({p:e})=>s.jsx("div",{"aria-hidden":!0,className:"fixed inset-0 pointer-events-none",style:{backgroundImage:[`linear-gradient(${e.gridLine} 1px, transparent 1px)`,`linear-gradient(90deg, ${e.gridLine} 1px, transparent 1px)`].join(", "),backgroundSize:"40px 40px",zIndex:0}}),ae=({seconds:e,p:t,isRunning:n})=>{const r=Math.floor(e/60),i=e%60,a=e<=60,o=e<=120&&!a,l=a?t.timerCritical:o?t.timerWarning:t.timerNormal;return s.jsxs("div",{className:"flex flex-col items-center",role:"timer","aria-label":`${r} minutes ${i} seconds remaining`,"aria-live":a?"assertive":"polite",children:[s.jsxs("span",{className:"text-xs font-medium mb-0.5 flex items-center gap-1",style:{color:t.mutedText},children:[s.jsx(M,{style:{width:10,height:10},"aria-hidden":!0}),"Time Left"]}),s.jsxs("span",{className:"font-mono font-bold tabular-nums transition-colors duration-300",style:{fontSize:"clamp(26px, 5vw, 40px)",lineHeight:1,color:l,textShadow:a?`0 0 20px ${t.timerCritical}55`:o?`0 0 16px ${t.timerWarning}44`:`0 0 12px ${t.timerNormal}33`},"aria-hidden":!0,children:[String(r).padStart(2,"0"),s.jsx("span",{className:n?"animate-pulse":"",style:{display:"inline-block",margin:"0 1px"},children:":"}),String(i).padStart(2,"0")]}),a&&s.jsx("span",{className:"text-[10px] font-semibold mt-0.5 animate-pulse",style:{color:t.timerCritical},"aria-hidden":!0,children:"Wrapping upâ¦"})]})},oe=({value:e,p:t})=>s.jsx("div",{className:"relative w-full rounded-full overflow-hidden",style:{height:4,background:t.progressBg},role:"progressbar","aria-valuenow":Math.round(e),"aria-valuemin":0,"aria-valuemax":100,"aria-label":`Interview progress: ${Math.round(e)}%`,children:s.jsx("div",{className:"h-full rounded-full transition-all duration-1000 ease-out",style:{width:`${e}%`,background:t.progressFill,boxShadow:"0 0 8px rgba(139,92,246,0.50)"}})}),le=({isConnected:e,isConnecting:t,isListening:n,isSpeaking:r,p:i})=>{let a="Connectingâ¦",o=i.mutedText,l=!0;e?n?(a="Listening to you",o=i.successText):r?(a="AI is speaking",o=i.accentText):(a="Connected",o=i.successText,l=!1):t&&(o=i.warningText);const c=n?s.jsx(P,{style:{width:11,height:11},"aria-hidden":!0}):r?s.jsx(B,{style:{width:11,height:11},"aria-hidden":!0}):e?s.jsx(q,{style:{width:11,height:11},"aria-hidden":!0}):s.jsx(j,{style:{width:11,height:11},"aria-hidden":!0});return s.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold",style:{background:e?i.successBg:t?i.warningBg:i.cardBg,border:`1px solid ${e?i.successBorder:t?i.warningBorder:i.cardBorder}`,color:o},role:"status","aria-label":a,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full "+(l?"animate-pulse":""),style:{background:o,flexShrink:0},"aria-hidden":!0}),c,a]})},ce=({p:e,isEndingInterview:t,onClick:n,compact:r=!1})=>s.jsxs("button",{onClick:n,disabled:t,className:"flex items-center justify-center gap-2 rounded-xl font-bold transition-all active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed",style:{background:e.btnEndBg,color:e.btnEndText,boxShadow:"0 4px 18px rgba(239,68,68,0.30
2), 0 1px 4px rgba(0,0,0,0.22)",fontSize:r?12:14,padding:r?"9px 12px":"11px 14px",minWidth:r?88:112},"aria-label":"End interview",children:[s.jsx(F,{"aria-hidden":!0,style:{width:r?15:17,height:r?15:17}}),t?"Endingâ¦":"End"]}),de=()=>{var e;const t="true"===sessionStorage.getItem("corporate_candidate_mode"),m="true"===sessionStorage.getItem("credits_pre_deducted"),{id:x}=a(),b=i(),{toast:k}=w(),{session:S}=y(),{resolvedTheme:T}=v(),N="light"===T?re.light:re.dark,[C,_]=r.useState(x?se(x):null),j=r.useRef(C);r.useEffect(()=>{j.current=C},[C]);const[E,I]=r.useState(!1),[R,A]=r.useState(!1),[P,M]=r.useState(!1),[F,B]=r.useState(null),[q,O]=r.useState(!1),[$,L]=r.useState(!1),[D,Q]=r.useState(""),[H,z]=r.useState([]),[W,J]=r.useState(x?60*((null==(e=se(x))?void 0:e.duration_minutes)??30):1800),K=r.useRef(!1),V=r.useRef(!1),X=r.useRef(!1),ee=r.useRef(0),[de,ue]=r.useState({halfTime:!1,twoMinutes:!1,oneMinute:!1,final15sec:!1}),he=r.useRef(de);r.useEffect(()=>{he.current=de},[de]);const[pe,fe]=r.useState(!1),[me,ge]=r.useState(!1),[ve,xe]=r.useState(!1),[be,we]=r.useState(!0),[ye,ke]=r.useState(null),[Se,Te]=r.useState(!1),[Ne,Ce]=r.useState("connected"),[_e,je]=r.useState(0),Ee=r.useRef(0),Ie=r.useRef(null);((e=!1)=>{const t=r.useRef(null),n=r.useRef(!1),s=r.useCallback(async()=>{if(!n.current&&!t.current&&"wakeLock"in navigator)try{n.current=!0,t.current=await navigator.wakeLock.request("screen"),t.current.addEventListener("release",()=>{t.current=null})}catch(e){t.current=null}finally{n.current=!1}},[]),i=r.useCallback(async()=>{if(t.current)try{await t.current.release(),t.current=null}catch(e){}},[]);r.useEffect(()=>{if(!e)return;const n=async()=>{"visible"===document.visibilityState&&e&&(t.current||await s())},r=async()=>{e&&!t.current&&await s()};return document.addEventListener("visibilitychange",n),window.addEventListener("focus",r),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("focus",r)}},[e,s]),r.useEffect(()=>(e?s():i(),()=>{i()}),[e,s,i]),t.current})((E||P||R)&&!me);const Re=r.useRef(null),Ae=r.useRef(!1),Pe=r.useRef(!1),Me=r.useRef(!1),Fe=r.useRef(""),Be=r.useRef(null),qe=r.useRef(!1),[Oe,$e]=r.useState(null),Le=r.useRef(null);Le.current=Oe;const De=r.useRef([]),Ge=r.useRef(!1),Qe=r.useCallback(async e=>{await He(e)},[]);r.useEffect(()=>{if(!x)return void b(t?"/corporate-interview/complete":"/dashboard");Ae.current=!1,Pe.current=!1,qe.current=!1,Fe.current="",De.current=[],Ge.current=!1,Me.current=!1,K.current=!1,V.current=!1,X.current=!1,Ee.current=0,I(!1),A(!1),M(!1),ge(!1),xe(!1),Q(""),z([]),ue({halfTime:!1,twoMinutes:!1,oneMinute:!1,final15sec:!1}),Ce("connected"),je(0);const e=se(x);return e&&(_(e),j.current=e,J(60*e.duration_minutes)),Qe(x),()=>{var e;Ae.current=!0,null==(e=Re.current)||e.disconnect(),Re.current=null,Be.current&&(clearTimeout(Be.current),Be.current=null),Ie.current&&(clearTimeout(Ie.current),Ie.current=null)}},[x]),r.useEffect(()=>{x&&Se&&Ue(x)},[x,Se]);const He=async e=>{var n;try{const[s,r]=await Promise.all([g.from("interviews").select("*").eq("id",e).single(),g.from("interview_sessions").select("question_order").eq("interview_id",e).order("question_order",{ascending:!1}).limit(1)]);if(s.error)throw s.error;const i=s.data;if(!i)return k({title:"Interview Not Found",description:"The session could not be found.",variant:"destructive"}),void b(t?"/corporate-interview/complete":"/dashboard");try{sessionStorage.setItem(ne,JSON.stringify(i))}catch{}if(_(i),j.current=i,i.started_at&&"in_progress"===i.status){const e=60*(i.duration_minutes||30),t=Math.max(0,Math.floor((Date.now()-new Date(i.started_at).getTime())/1e3));if(t>=e)return void et();ee.current=t,J(e-t)}else J(60*(i.duration_minutes||30));!r.error&&(null==(n=r.data)?void 0:n.length)>0?$e(r.data[0].question_order):$e(1),"completed"!==i.status&&"cancelled"!==i.status||b(t?"/corporate-interview/complete":`/interview/${e}/feedback`,{replace:!0})}catch(s){k({title:"Error",description:"Failed to load interview session.",variant:"destructive"})}},Ue=async e=>{var t,n,s;if(Pe.current||Ae.current)return;Pe.current=!0,M(!0);performance.now();let r;try{const{data:i}=await g.auth.getSession();r=null==(t=null==i?void 0:i.session)?void 0:t.access_token;const a=null==(n=null==i?void 0:i.session)?void 0:n.expires_at;if(!r||a&&a-Date.now()/1e3<60){const{data:e,error:t}=await g.auth.refreshSession();if(t||!e.session)throw new Error("Session refresh failed");r=e.session.access_token}if(!r)throw new Error("No access token available");const o=new U(e,r,(null==(s=null==S?void 0:S.user)?void 0:s.id)||null,Je,Ke);o.ambientNoiseLevel=ye,o.onConnectionLost=()=>Ve(),o.onConnectionQuality=e=>B(e),o.onTokenRefreshed=e=>{},o.onTokenRefreshFailed=e=>{k({title:"Session about to expire",description:`We couldn't refresh your sign-in after ${e} attempts. Please save your progress and reconnect.`,variant:"destructive",duration:2e4})},Re.current=o;const l=[300,800,2e3];let c=0;const d=3,u=async()=>{var e;try{c++,await(null==(e=Re.current)?void 0:e.connect())}catch(t){if(c<d)return await new Promise(e=>setTimeout(e,l[c-1]??1e3)),u();throw t}};await u()}catch(i){const t=(null==i?void 0:i.message)||"Unknown error";G("revert-interview-session",{accessToken:r,body:{interview_id:e,reason:`Connection failed: ${t}`,scenario:"connection_failed"}}).then(e=>{(null==e?void 0:e.success)&&k({title:"Credits Refunded",description:`${e.refundedAmount} credits refunded.`,duration:8e3})}).catch(()=>{});/connection|network|timeout|webrtc/i.test(t)&&g.from("interviews").update({status:"connection_failed",completed_at:(new Date).toISOString()}).eq("id",e).then(()=>{},()=>{}),k({title:"Connection Failed",description:t||"Unable to connect. Credits refunded.",variant:"destructive",duration:8e3})}finally{Pe.current=!1,M(!1)}},ze=r.useCallback(async()=>
2{if(!Ge.current&&0!==De.current.length){for(Ge.current=!0;De.current.length>0;){const t=De.current.shift();try{await tt(t.transcript,t.questionOrder)}catch(e){De.current.unshift(t),await new Promise(e=>setTimeout(e,500))}}Ge.current=!1}},[]);r.useEffect(()=>{if(!E||K.current)return;const e=setInterval(()=>{var t;if(Ae.current)return void clearInterval(e);ee.current+=1;const n=60*((null==(t=j.current)?void 0:t.duration_minutes)||30);J(Math.max(0,n-ee.current))},1e3);return()=>clearInterval(e)},[E]),r.useEffect(()=>{var e,t,n,s,r;if(!E||!Re.current)return;const i=60*((null==(e=j.current)?void 0:e.duration_minutes)||30);W<=Math.floor(i/2)&&!he.current.halfTime&&(ue(e=>({...e,halfTime:!0})),null==(t=Re.current)||t.injectTimerContext("[INTERNAL_CONTEXT][TIMING_PACING][DO_NOT_VOCALIZE]:\nHalfway point. Maintain pacing. Do NOT conclude.")),W<=120&&!he.current.twoMinutes&&(ue(e=>({...e,twoMinutes:!0})),null==(n=Re.current)||n.injectTimerContext("[INTERNAL_CONTEXT][TIMING_PACING][DO_NOT_VOCALIZE]:\n2 minutes remaining. Keep concise. Do NOT conclude.")),W<=60&&!he.current.oneMinute&&(ue(e=>({...e,oneMinute:!0})),null==(s=Re.current)||s.injectTimerContext("[INTERNAL_CONTEXT][TIMING_NARROWING][DO_NOT_VOCALIZE]:\n1 minute. At most ONE final question. Do NOT conclude yet.")),W<=15&&!he.current.final15sec&&(ue(e=>({...e,final15sec:!0})),null==(r=Re.current)||r.injectTimerContext("[INTERNAL_CONTEXT][TIMING_SIGNAL_FINAL_15S]"),K.current=!0),W<=0&&!Ae.current&&!ve&&(k({title:"Time's up",description:"Wrapping up your interview and starting evaluationâ¦",duration:3e3}),et())},[W,E]);const We=r.useRef(()=>{}),Je=r.useCallback(async e=>{var t;if(!Ae.current)switch(e.type){case"connected":A(!0),M(!1);break;case"context_incomplete":M(!1),I(!1),k({title:"Interview Setup Issue",description:"Retrying connectionâ¦",duration:3e3});break;case"session_ready":{I(!0);const e=new Date,t=j.current;if((null==t?void 0:t.started_at)&&"in_progress"===t.status){const e=60*(t.duration_minutes||30),n=Math.max(0,Math.floor((Date.now()-new Date(t.started_at).getTime())/1e3));if(n>=e)return void et();ee.current=n,J(e-n)}else ee.current=0,J(60*((null==t?void 0:t.duration_minutes)||30));if(qe.current)break;if(m){qe.current=!0,sessionStorage.removeItem("credits_pre_deducted");const e=60*((null==t?void 0:t.duration_minutes)||30);Be.current=setTimeout(async()=>{V.current?setTimeout(()=>et(),3e3):Ae.current||await et()},1e3*e),k({title:"Interview Started! ð",description:"Speak naturally â the AI is listening.",duration:5e3});break}const{data:n,error:s}=await g.functions.invoke("start-interview-with-credits",{body:{interview_id:x}});if(null==n?void 0:n.alreadyStarted){qe.current=!0;const n=(null==t?void 0:t.started_at)?Math.max(0,60*(t.duration_minutes||30)-Math.floor((e.getTime()-new Date(t.started_at).getTime())/1e3)):60*((null==t?void 0:t.duration_minutes)||30);if(!(n>0))return void(await et());Be.current=setTimeout(async()=>{V.current?setTimeout(()=>et(),3e3):Ae.current||await et()},1e3*n),k({title:"Interview Resumed",description:"Continuing session.",duration:3e3});break}if(s||!(null==n?void 0:n.success))return k({title:(null==n?void 0:n.activeInterviewId)?"Interview Already Active":"Credit Deduction Failed",description:(null==n?void 0:n.activeInterviewId)?"You have another interview in progress.":"Unable to start interview.",variant:"destructive"}),void(await et());qe.current=!0;const r=(null==t?void 0:t.started_at)&&"in_progress"===t.status?Math.max(0,60*(t.duration_minutes||30)-Math.floor((e.getTime()-new Date(t.started_at).getTime())/1e3)):60*((null==t?void 0:t.duration_minutes)||30);Be.current=setTimeout(async()=>{V.current?setTimeout(()=>et(),3e3):Ae.current||await et()},1e3*r),k({title:"Interview Started! ð",description:`${n.creditsDeducted} credits used. ${n.remainingCredits} remaining.`,duration:5e3});break}case"recording_started":O(!0);break;case"user_speaking":O(e.speaking);break;case"ai_transcript":if(K.current)return;Q(t=>(t+" "+(e.text||"")).trim()),L(!0);break;case"ai_speech_completed":if(K.current){L(!1),Q("");break}z(e=>[...e,{id:crypto.randomUUID(),sender:"ai",content:D.trim(),timestamp:new Date}]),L(!1),Q(""),e.questionOrder&&$e(e.questionOrder);break;case"user_transcript":{const n=null==(t=e.text)?void 0:t.trim();if(!n)break;X.current=!0,V.current=!1,z(e=>[...e,{id:crypto.randomUUID(),sender:"user",content:n,timestamp:new Date}]),De.current.push({transcript:n,questionOrder:e.questionOrder||Le.current}),ze();break}case"user_speaking_started":O(!0),K.current&&(V.current=!0,X.current=!1);break;case"user_speaking_stopped":K.current||O(!1)}},[x,m,D,ze]);r.useEffect(()=>{We.current=Je},[Je]);const Ke=r.useCallback(e=>
2{k({title:"Connection Error",description:e,variant:"destructive"})},[k]),Ye=r.useCallback(()=>{var e,t;if(Re.current){try{null==(t=(e=Re.current).disconnect)||t.call(e)}catch{}Re.current=null}Ie.current&&(clearTimeout(Ie.current),Ie.current=null)},[]),Ve=r.useCallback(()=>{if(Ae.current||!x)return;if(Ee.current>=3)return Ce("failed"),void g.from("interviews").update({status:"connection_failed"}).eq("id",x).then(({error:e})=>{});Ce("reconnecting"),je(Ee.current);const e=3e3*Math.pow(2,Ee.current);Ie.current=setTimeout(()=>{Ee.current+=1,je(Ee.current),Ye(),Ue(x)},e)},[x,Ye]),Xe=r.useCallback(()=>{x&&(Ee.current=0,je(0),Ce("reconnecting"),Ye(),Ue(x))},[x,Ye]),Ze=r.useCallback(()=>{Ce("abandoned"),Ye()},[Ye]),et=r.useCallback(async()=>{var e,s,r;const i=Date.now();for(;V.current&&!X.current&&!(Date.now()-i>1e4);)await new Promise(e=>setTimeout(e,200));if(!Ae.current&&!ve){xe(!0),Ae.current=!0,ge(!0),k({title:"Saving Interviewâ¦",description:"Your session is being saved.",duration:2e3});try{await(null==(e=Re.current)?void 0:e.disconnect()),Re.current=null;try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>{e.stop(),e.enabled=!1})}catch{}Be.current&&(clearTimeout(Be.current),Be.current=null);const{data:i,error:a}=await g.from("interview_sessions").select("*").eq("interview_id",x),o=(null==i?void 0:i.some(e=>{var t;return(null==(t=e.user_response)?void 0:t.trim().length)>0}))??!1,l=o?"completed":"cancelled";if(await g.from("interviews").update({status:l,completed_at:o?(new Date).toISOString():null}).eq("id",x),!o)return g.functions.invoke("revert-interview-session",{body:{interview_id:x,reason:(null==i?void 0:i.length)?"No user responses recorded":"No transcript recorded",scenario:"no_transcript"}}).catch(()=>{}),k({title:"Interview Cancelled",description:"No responses recorded. Credits refunded.",variant:"destructive"}),void b(t?"/corporate-interview/complete":"/dashboard",{replace:!0});if(k({title:"Interview Complete!",description:"Generating evaluationâ¦",duration:2e3}),t){const e=sessionStorage.getItem("corporate_interview_type")||(null==(s=j.current)?void 0:s.interview_type)||"overall",t={technical:"technical-interview-evaluator",behavioral:"behavioral-interview-evaluator",overall:"overall-interview-evaluator"}[e]||"overall-interview-evaluator",{data:i}=await g.auth.getSession(),a=null==(r=null==i?void 0:i.session)?void 0:r.access_token;try{const{SUPABASE_URL:e,SUPABASE_PUBLISHABLE_KEY:s}=await n(async()=>{const{SUPABASE_URL:e,SUPABASE_PUBLISHABLE_KEY:t}=await import("./index.CdjOtu-m.js").then(e=>e.a6);return{SUPABASE_URL:e,SUPABASE_PUBLISHABLE_KEY:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12]));fetch(`${e}/functions/v1/${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a||""}`,apikey:s},body:JSON.stringify({interview_id:x}),keepalive:!0}).catch(()=>{})}catch{}b("/corporate-interview/complete",{replace:!0})}else b(`/interview/${x}/feedback`,{replace:!0})}catch(a){Ae.current=!1,ge(!1),xe(!1),k({title:"Error Ending Interview",description:"Please try again",variant:"destructive"})}}},[x,t,ve,b,k]),tt=async(e,t)=>{var n;if(!x||!(null==e?void 0:e.trim()))return;const s=t??Le.current;if(null!==s){for(let t=1;t<=5;t++)try{const{data:{session:r}}=await g.auth.getSession();if(!(null==r?void 0:r.access_token))throw new Error("No valid session");const{data:i,error:a}=await g.functions.invoke("save-user-response",{body:{interview_id:x,question_order:s,user_response:e.trim()}});if(a)throw a;if(null==i?void 0:i.success)return void(Fe.current=e);if(null==(n=null==i?void 0:i.message)?void 0:n.includes("Question not found")){await new Promise(e=>setTimeout(e,100*t));continue}throw new Error((null==i?void 0:i.message)||"Unknown error")}catch(r){if(r instanceof Error&&r.message.includes("Question not found")&&t<5){await new Promise(e=>setTimeout(e,100*t));continue}if(t>=5)break}k({title:"Save Error",description:"Failed to save your response. Interview continues.",variant:"destructive"})}},nt=60*((null==C?void 0:C.duration_minutes)||30),st=E?(nt-W)/nt*100:0;return C?s.jsxs("div",{className:"flex flex-col transition-colors duration-300",style:{background:N.sectionBg,height:"100dvh",overflow:"hidden"},children:[s.jsx(ie,{p:N}),s.jsx("div",{className:"relative z-10 flex flex-col flex-1 overflow-hidden",style:{paddingTop:"env(safe-area-inset-top,0px)",paddingBottom:"env(safe-area-inset-bottom,0px)"},children:s.jsxs("div",{className:"flex flex-col flex-1 overflow-hidden mx-auto w-full",style:{maxWidth:672,padding:"clamp(12px,2.5vw,24px) clamp(12px,4vw,24px)"},children:[s.jsxs("div",{className:"rounded-2xl sm:rounded-3xl flex-shrink-0",style:{background:N.cardBg,border:`1px solid ${N.cardBorder}`,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",padding:"clamp(14px,3vw,20px) clamp(16px,4vw,24px)"},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("h1",{className:"font-bold leading-tight truncate",style:{color:N.headlineColor,fontSize:"clamp(14px,2.8vw,19px)",fontFamily:"'Roboto Slab',serif"},children:C.role_title}),s.jsx("p",{className:"text-xs sm:text-sm mt-0.5 truncate",style:{color:N.bodyText},children:C.company_name}),s.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[s.jsx("span",{className:"inline-block px-2 py-0.5 rounded-full text-xs font-semibold capitalize",style:{background:N.pillBg,border:`1px solid ${N.pillBorder}`,color:N.accentText},children:C.interview_type}),s.jsx(le,{isConnected:R,isConnecting:P,isListening:q,isSpeaking:$,p:N}),R&&F&&s.jsxs("span",{title:`Connection quality: ${F}`,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wide",style:{background:"good"===F?"rgba(16,185,129,0.15)":"fair"===F?"rgba(245,158,11,0.15)":"rgba(239,68,68,0.15)",border:"1px solid "+("good"===F?"rgba(16,185,129,0.4)":"fair"===F?"rgba(245,158,11,0.4)":"rgba(239,68,68,0.4)"),color:"good"===F?"#6ee7b7":"fair"===F?"#fbbf24":"#fca5a5"},children:[s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full",style:{background:"good"===F?"#10b981":"fair"===F?"#f59e0b":"#ef4444"}}),"Network: ","good"===F?"Strong":"fair"===F?"Fair":"Weak"]})]})]}),s.jsxs("div",{className:"flex-shrink-0 flex items-start gap-2",children:[(E||P||R)&&!me&&s.jsx(ce,{p:N,isEndingInterview:ve,onClick:()=>fe(!0),compact:!0}),E&&s.jsx(ae,{seconds:W,p:N,isRunning:!me})]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex justify-between text-xs mb-1.5",style:{color:N.mutedText},children:[s.jsx("span",{children:"Progress"}),s.jsx("span",{children:E?(rt=nt-W,`${Math.floor(rt/60)}:${String(rt%60).padStart(2,"0")}`)+" elapsed":`${C.duration_minutes||30} min`})]}),s.jsx(oe,{value:st,p:N})]})]}),s.jsx("div",{className:"rounded-2xl sm:rounded-3xl flex flex-col items-center justify-center flex-1 overflow-hidden",style:{background:N.cardBg,border:`1px solid ${N.cardBorder}`,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",margin:"clamp(8px,1.8vw,14px) 0",padding:"clamp(20px,4vw,40px)",minHeight:0},children:E?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex-1 flex items-center justify-center w-full min-h-0",children:s.jsx(Y,{isActive:q||$})}),s.jsx("p",{className:"text-xs sm:text-sm font-medium text-center mt-3 flex-shrink-0",style:{color:q?N.successText:$?N.accentText:N.mutedText},"aria-live":"polite",children:q?"ð Listeningâ¦":$?"ð AI is speakingâ¦":R?"â³ Ready for your response":"Connectingâ¦"})]}):me||!P&&("in_progress"!==(null==C?void 0:C.status)||R)?null:s.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[s.jsx("div",{className:"w-14 h-14 roun
2ded-full border-2 border-transparent animate-spin",style:{borderTopColor:N.spinnerColor,borderRightColor:`${N.spinnerColor}44`},role:"status","aria-label":"Connecting to AI interviewer"}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-lg sm:text-xl font-bold mb-1",style:{color:N.headlineColor,fontFamily:"'Roboto Slab',serif"},children:"Starting Your Interview"}),s.jsx("p",{className:"text-sm",style:{color:N.bodyText},children:"Connecting to your AI interviewerâ¦"})]})]})})]})}),s.jsx(o,{open:pe,onOpenChange:fe,children:s.jsxs(l,{style:{background:re.dark.sectionBg,border:`1px solid ${N.cardBorder}`,borderRadius:20},children:[s.jsxs(c,{children:[s.jsx(d,{style:{color:N.headlineColor,fontFamily:"'Roboto Slab',serif"},children:"End Interview?"}),s.jsx(u,{style:{color:N.bodyText},children:"Are you sure you want to end the interview? This action cannot be undone and your responses so far will be evaluated."})]}),s.jsxs(h,{children:[s.jsx(p,{style:{background:N.cardBg,border:`1px solid ${N.cardBorder}`,color:N.bodyText,borderRadius:12},children:"Continue Interview"}),s.jsx(f,{onClick:async()=>{fe(!1),await et()},style:{background:N.btnEndBg,color:N.btnEndText,borderRadius:12,border:"none"},children:"End Interview"})]})]})}),s.jsx(te,{open:be,onComplete:e=>{ke(e),we(!1),Te(!0)},onCancel:()=>{ke(null),we(!1),Te(!0)}}),x&&("reconnecting"===Ne||"failed"===Ne)&&s.jsx(Z,{interviewId:x,connectionState:Ne,reconnectAttempt:_e,maxReconnectAttempts:3,onRetry:Xe,onAbandon:Ze})]}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center",style:{background:N.sectionBg},"aria-live":"polite","aria-busy":"true",children:[s.jsx(ie,{p:N}),s.jsxs("div",{className:"relative z-10 text-center p-10 rounded-3xl",style:{background:N.cardBg,border:`1px solid ${N.cardBorder}`},children:[s.jsx("div",{className:"w-12 h-12 rounded-full border-2 border-transparent animate-spin mx-auto mb-4",style:{borderTopColor:N.spinnerColor,borderRightColor:`${N.spinnerColor}44`},role:"status","aria-label":"Loading"}),s.jsx("p",{className:"text-sm font-medium",style:{color:N.bodyText},children:"Loading interview sessionâ¦"})]}),s.jsx(te,{open:be,onComplete:e=>{ke(e),we(!1),Te(!0)},onCancel:()=>{ke(null),we(!1),Te(!0)}})]});var rt},ue=()=>s.jsx(X,{fallbackTitle:"Interview Session Error",onRetry:()=>window.location.reload(),children:s.jsx(de,{})});export{ue as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.