1import{D as oe,u as ie,aS as ce,b as le,r as f,f as T,j as t,G as de,o as $,B as v,E as F,d as ue,aT as q,aU as me,aQ as he,y as pe}from"./index-QiiZ-xPT.js";import{B as G}from"./badge-IOHUIid2.js";import{C as ge,a as fe}from"./card-DkXabqFf.js";import{a as H}from"./sanitize-DKP1LTNb.js";import{L as xe}from"./lock-keyhole-BUZqojmh.js";import{C as be}from"./circle-alert-BZ1suj-l.js";const Q="lc-learning-embed",V=1,ye=["ready","route_changed","lesson_started","lesson_completed","height_changed","auth_required","error"];new Set(ye);function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W(e,n){return e.protocol===Q&&e.version===V&&typeof e.embedId=="string"&&e.embedId.length>0&&(!n||e.embedId===n)}function we(e,n){return!K(e)||!W(e,n)?!1:e.type==="launch"&&typeof e.launchToken=="string"&&e.launchToken.length>=16&&e.launchToken.length<=8192}function je(e,n){return!K(e)||!W(e,n)?!1:e.type==="initialize"&&typeof e.hostOrigin=="string"&&e.hostOrigin.length>0}function Ne(e,n){return e.source===n.source&&je(e.data,n.embedId)&&e.data.hostOrigin===e.origin}function J(e,n,a){return{protocol:Q,version:V,type:e,embedId:n,timestamp:new Date().toISOString(),...a?{payload:a}:{}}}function Se(e){if(!e)return null;try{const n=new URL(e);return n.protocol==="https:"||n.hostname==="localhost"?n.origin:null}catch{return null}}function Ce(e){return e.handshakeReady?!e.authenticatedMode||e.hasSessionToken?"portal":e.exchanging?"exchanging":"ready":"handshake"}const Re={"cmi.core.lesson_location":"lessonLocation","cmi.core.lesson_status":"lessonStatus","cmi.core.score.raw":"scoreRaw","cmi.core.session_time":"sessionTime","cmi.suspend_data":"suspendData","cmi.location":"lessonLocation","cmi.completion_status":"completionStatus","cmi.success_status":"successStatus","cmi.score.raw":"scoreRaw","cmi.session_time":"sessionTime"};function B(e){return Re[e]||null}function Ee(e,n){if(e==="scoreRaw"){const r=Number(n);return Number.isFinite(r)&&r>=0&&r<=100?r:null}const a=e==="suspendData"?12e3:512;return n.length>a||e.endsWith("Status")&&!["not attempted","incomplete","completed","passed","failed","unknown"].includes(n.toLowerCase())?null:n}function Le(e,n){const a={...e};let r="0";const b=y=>{const p=B(y);return p?(r="0",a[p]===void 0?"":String(a[p])):(r="401","")},m=(y,p)=>{const d=B(y),x=d?Ee(d,p):null;return!d||x===null?(r="405","false"):(a[d]=x,r="0","true")},c=()=>(n({...a}),r="0","true"),w=()=>(n({...a}),r="0","true");return{state:a,api12:{LMSInitialize:()=>"true",LMSFinish:w,LMSGetValue:b,LMSSetValue:m,LMSCommit:c,LMSGetLastError:()=>r,LMSGetErrorString:()=>"",LMSGetDiagnostic:()=>""},api2004:{Initialize:()=>"true",Terminate:w,GetValue:b,SetValue:m,Commit:c,GetLastError:()=>r,GetErrorString:()=>"",GetDiagnostic:()=>""}}}function D(e,n){return e&&/^(#[\da-f]{3,8}|(?:rgb|hsl)a?\([\d\s.,%]+\))$/i.test(e)?e:n}function X(e){if(!e)return null;try{const n=new URL(e,window.location.origin);return n.protocol==="https:"||n.origin===window.location.origin?n.href:null}catch{return null}}function Ue(e){switch(e){case"access_disabled":return["Learning access unavailable",pe];case"disabled":return["Learning portal unavailable","This organization has disabled its embedded learning portal."];case"origin":return["Website not approved","This portal cannot be opened from the current website. Contact your organization administrator."];case"expired":return["Launch expired","Request a new secure launch from the website where you started."];case"content":return["Content unavailable","This content is unavailable or outside this portal's allowed learning scope."];case"auth":return["Sign-in required","Your browser could not continue the embedded sign-in. Open the secure portal to continue."];default:return["Portal could not load","Check your connection and try again."]}}function ve(e,n){return n==="LEARNING_ACCESS_DISABLED"?"access_disabled":n==="EMBED_DISABLED"||e===410?"disabled":n==="ORIGIN_NOT_ALLOWED"||e===403?"origin":n==="LAUNCH_EXPIRED"||n==="LAUNCH_REPLAYED"?"expired":n==="AUTH_REQUIRED"||e===401?"auth":n==="CONTENT_UNAVAILABLE"||e===404?"content":"unknown"}async function P(e,n=!1){const a=await e.json().catch(()=>null);return!n&&q(e.status,a)&&me(e.url),{type:n&&q(e.status,a)?"unknown":ve(e.status,a?.code),detail:a?.message}}function Fe(){const{embedId:e=""}=oe(),{user:n,isLoading:a}=ie(),r=!!n&&ce(n),[,b]=le(),m=f.useRef(null),[c,w]=f.useState(()=>
1Se(document.referrer)),[y,p]=f.useState(null),[d,x]=f.useState(null),[u,l]=f.useState(null),[g,L]=f.useState(!1),N=new URLSearchParams(window.location.search).get("destination")||"",S=f.useCallback((s,o)=>{window.parent===window||!c||window.parent.postMessage(J(s,e,o),c)},[e,c]),U=T({queryKey:["/api/embed",e,"handshake",c,r],queryFn:async()=>{const s=await fetch(`/api/embed/${encodeURIComponent(e)}/handshake`,{headers:{...c?{"X-Embed-Origin":c}:{}}});if(!s.ok)throw await P(s,r);const o=await s.json();return{embedId:o.embedId,enabled:o.enabled!==!1,mode:o.mode,branding:o.organization,display:o.theme}},enabled:!!e&&!!c&&!a,retry:!1,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchInterval:3e4,refetchIntervalInBackground:!0}),M=f.useCallback(async s=>{if(!(g||!c)){L(!0),l(null);try{const o=await fetch(`/api/embed/${encodeURIComponent(e)}/exchange`,{method:"POST",headers:{"Content-Type":"application/json","X-Embed-Origin":c},body:JSON.stringify({launchToken:s,origin:c})});if(!o.ok)throw await P(o,r);const R=await o.json();if(typeof R.accessToken!="string")throw{type:"unknown",detail:"The launch response was invalid."};x(R.accessToken)}catch(o){const R=o,C={type:R.type||"unknown",detail:R.detail};l(C),S(C.type==="auth"||C.type==="expired"?"auth_required":"error",{code:C.type})}finally{L(!1)}}},[e,g,r,c,S]);f.useEffect(()=>{const o=new URLSearchParams(window.location.hash.replace(/^#/,"")).get("launch");o&&(history.replaceState(null,"",window.location.pathname+window.location.search),p(o))},[]),f.useEffect(()=>{function s(o){if(Ne(o,{source:window.parent,embedId:e})){w(o.origin);return}o.source===window.parent&&(!c||o.origin!==c||we(o.data,e)&&p(o.data.launchToken))}return window.addEventListener("message",s),()=>window.removeEventListener("message",s)},[e,M,c]),f.useEffect(()=>{!y||!c||!U.data||(p(null),M(y))},[U.data,M,y,c]);const j=U.data,Z=Ce({handshakeReady:!!j,authenticatedMode:j?.mode==="authenticated",hasSessionToken:!!d,exchanging:g}),ee=(j?.enabled||r)&&(j?.mode==="anonymous"||!!d),h=T({queryKey:["/api/embed/learning",e,"portal",N,d?"session":"anonymous",c,r],queryFn:async()=>{const s=N.startsWith("content:")?N.slice(8):"",o=N.startsWith("module:")?N.slice(7):"",R=s?`/api/embed/${encodeURIComponent(e)}/content/${encodeURIComponent(s)}`:o?`/api/embed/${encodeURIComponent(e)}/modules/${encodeURIComponent(o)}`:N?`/api/embed/${encodeURIComponent(e)}/portal?destination=${encodeURIComponent(N)}`:`/api/embed/${encodeURIComponent(e)}/portal`,C=await fetch(R,{headers:{...c?{"X-Embed-Origin":c}:{},...d?{Authorization:`Bearer ${d}`}:{}}});if(!C.ok)throw await P(C,r);const E=await C.json();if(s){const i=E.content||{};return{title:i.title||"Learning content",destination:N,items:[],content:{id:String(i.id),title:i.title||"Learning content",kind:i.contentType||i.type||"lesson",html:i.content||i.body||i.description,mediaUrl:i.contentUrl||i.mediaUrl,completionPercent:E.progress?.progressPercent},breadcrumbs:[{label:"Learning",destination:""},{label:i.title||"Content"}]}}if(o){const i=E.module||E,A=E.progress||i.progress||null;return{title:i.title||"Learning module",destination:N,items:[],content:{id:String(i.id||o),moduleSlug:o,title:i.title||"Learning module",kind:"module",html:i.transcript||i.content||i.summary||i.shortSummary,mediaUrl:i.audioUrl||i.mediaUrl,completionPercent:A?.progress??A?.progressPercent,module:{...i,progress:A}},breadcrumbs:[{label:"Learning",destination:"catalog"},{label:i.title||"Module"}]}}const ae=Array.isArray(E.items)?E.items:[];return{...E,destination:E.destination||N||"assigned",title:E.title||(j?.mode==="anonymous"?"Learning showcase":"Your learning"),items:ae.map(i=>({...i,id:String(i.id),title:i.title||i.name||"Untitled content",imageUrl:i.thumbnailUrl||i.imageUrl,type:i.type||"lesson",slug:i.slug,destination:i.type==="custom_content"?`content:${i.id}`:i.type==="path"?`path:${i.id}`:i.destination}))}},enabled:ee&&!a,retry:!1,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchInterval:3e4,refetchIntervalInBackground:!0});f.useEffect(()=>{j&&S("ready",{mode:j.mode})},[j,S]),f.useEffect(()=>{h.data&&S("route_changed",{destination:h.data.destination})},[h.data,S]),f.useEffect(()=>{const s=m.current;if(!s||typeof ResizeObserver>"u")return;let o=0;const R=new ResizeObserver(()=>{const C=Math.ceil(s.getBoundingClientRect().height);Math.abs(C-o)>=2&&(o=C,S("height_changed",{height:C}))});return R.observe(s),()=>R.disconnect()},[S]);const te=U.error||h.error,_=u||(j&&!j.enabled&&!r?{type:"disabled"}:null)||te,ne=Z==="ready"&&!_,k=j?.branding,se=`${window.location.origin}/embed/learning/${encodeURIComponent(e)}${N?`?destination=${encodeURIComponent(N)}`:""}`,z=`/api/embed/learning/${encodeURIComponent(e)}/auth/start?returnTo=${encodeURIComponent(se)}`;function re(s){if(s.type==="module"&&s.slug){S("lesson_started",{moduleSlug:s.slug}),b(`/embed/learning/${encodeURIComponent(e)}?destination=${encodeURIComponent(`module:${s.slug}`)}`);return}const o=s.destination||`${s.type}:${s.id}`;s.type==="lesson"&&S("lesson_started",{contentId:s.id}),b(`/embed/learning/${encodeURIComponent(e)}?destination=${encodeURIComponent(o)}`)}return t.jsxs("div",{ref:m,className:"min-h-screen",style:{background:D(k?.backgroundColor,"hsl(var(--background))"),color:D(k?.textColor,"hsl(var(--foreground))")},"data-testid":"embed-learning-shell",children:[j?.display?.showHeader!==!1&&t.jsx("header",{className:"border-b bg-background/95 px-4 py-3",children:t.jsxs("div",{className:"mx-auto flex max-w-6xl items-center gap-3",children:[k?.logoUrl?t.jsx("img",{src:k.logoUrl,alt:"",className:"h-9 max-w-36 object-contain"}):t.jsx(de,{className:"h-7 w-7","aria-hidden":"true"}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"truncate font-semibold",children:k?.portalName||k?.name||"Learning portal"}),j?.mode&&t.jsx("p",{className:"text-xs text-muted-foreground",children:j.mode==="anonymous"?"Public learning showcase":"Secure learner portal"})]})]})}),t.jsxs("main",{className:"mx-auto max-w-6xl p-4 sm:p-6","aria-live":"polite",children:[(U.isLoading||U.isFetching||g||h.isLoading||h.isFetching)&&t.jsxs("div",{className:"flex min-h-72 flex-col items-center justify-center gap-3",children:[t.jsx($,{className:"h-8 w-8 animate-spin"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:g?"Starting your secure sessionâ¦":"Loading learning portalâ¦"})]}),ne&&t.jsx(Y,{icon:xe,title:"Secure launch required",description:"Return to your organization's website to start a secure learning session.",action:t.jsx(v,{asChild:!0,children:t.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",children:["Open secure learning portal",t.jsx(F,{className:"ml-2 h-4 w-4"})]})})}),_&&!U.isFetching&&!h.isFetching&&t.jsx(_e,{error:_.type||"unknown",detail
1:_.detail,secureUrl:z,onRetry:()=>{l(null),U.refetch(),h.refetch()}}),h.data&&!_&&t.jsxs("div",{className:"space-y-5",children:[h.data.breadcrumbs&&h.data.breadcrumbs.length>1&&t.jsx("nav",{"aria-label":"Breadcrumb",className:"flex flex-wrap gap-2 text-sm",children:h.data.breadcrumbs.map((s,o)=>t.jsxs("button",{className:"hover:underline disabled:no-underline",disabled:!s.destination,onClick:()=>s.destination&&b(`/embed/learning/${e}?destination=${encodeURIComponent(s.destination)}`),children:[s.label,o<h.data.breadcrumbs.length-1&&" /"]},`${s.label}-${o}`))}),t.jsxs("div",{className:"flex flex-col justify-between gap-3 sm:flex-row sm:items-end",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold sm:text-3xl",children:h.data.title}),h.data.description&&t.jsx("p",{className:"mt-1 text-muted-foreground",children:h.data.description})]}),j?.display?.showProgress!==!1&&h.data.learner?.progressPercent!==void 0&&t.jsxs(G,{variant:"secondary",className:"self-start text-sm",children:[Math.round(h.data.learner.progressPercent),"% complete"]})]}),!h.data.content&&t.jsx("nav",{className:"flex flex-wrap gap-2","aria-label":"Learning portal destinations",children:[["assigned","Assigned learning"],["path","Learning paths"],["catalog","Catalog"],["progress","My progress"]].map(([s,o])=>t.jsx(v,{size:"sm",variant:h.data.destination===s?"default":"outline",onClick:()=>b(`/embed/learning/${encodeURIComponent(e)}?destination=${encodeURIComponent(s)}`),children:o},s))}),h.data.content?t.jsx(Ie,{content:h.data.content,embedId:e,authenticated:j?.mode==="authenticated",sessionToken:d,parentOrigin:c,post:S,onComplete:async()=>{const s=await fetch(`/api/embed/${encodeURIComponent(e)}/content/${encodeURIComponent(h.data.content.id)}/progress`,{method:"POST",headers:{"Content-Type":"application/json",...c?{"X-Embed-Origin":c}:{},...d?{Authorization:`Bearer ${d}`}:{}},body:JSON.stringify({progressPercent:100,isCompleted:!0})});if(!s.ok)throw await P(s,r);S("lesson_completed",{contentId:h.data.content.id}),await h.refetch()}}):h.data.items.length?t.jsx("div",{className:`grid gap-4 ${j?.display?.compactNavigation?"grid-cols-1":"sm:grid-cols-2 lg:grid-cols-3"}`,children:h.data.items.map(s=>t.jsx(ke,{item:s,onSelect:()=>re(s)},`${s.type}-${s.id}`))}):t.jsxs("div",{className:"rounded-lg border border-dashed py-16 text-center",children:[t.jsx(ue,{className:"mx-auto mb-3 h-10 w-10 text-muted-foreground"}),t.jsx("h2",{className:"font-semibold",children:"No learning available"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"There is no content available for this destination."})]})]})]})]})}function ke({item:e,onSelect:n}){return t.jsx(ge,{className:"overflow-hidden",children:t.jsxs("button",{className:"w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:n,children:[e.imageUrl&&t.jsx("img",{src:e.imageUrl,alt:"",className:"h-36 w-full object-cover"}),t.jsxs(fe,{className:"p-4",children:[t.jsx(G,{variant:"outline",className:"mb-2",children:e.type}),t.jsx("h2",{className:"font-semibold",children:e.title}),e.description&&t.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:e.description}),e.progressPercent!=null&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:t.jsx("div",{className:"h-full bg-primary",style:{width:`${Math.max(0,Math.min(100,e.progressPercent))}%`}})}),t.jsxs("span",{className:"mt-1 block text-xs text-muted-foreground",children:[Math.round(e.progressPercent),"% complete"]})]})]})]})})}function Ie({content:e,embedId:n,authenticated:a,sessionToken:r,parentOrigin:b,post:m,onComplete:c}){const[w,y]=f.useState(!1),[p,d]=f.useState("");f.useEffect(()=>{e.completionPercent===100&&m("lesson_completed",{embedId:n,title:e.title})},[e.completionPercent,e.title,n,m]);const x=X(e.mediaUrl);if(e.kind==="module"&&e.moduleSlug)return t.jsx(Te,{module:e,embedId:n,sessionToken:r,parentOrigin:b,post:m});if(e.kind==="scorm")return t.jsx($e,{contentId:e.id,title:e.title,embedId:n,sessionToken:r,parentOrigin:b});const l=a&&new Set(["article","document","link"]).has(e.kind),g=["scorm","quiz","module","video","audio"].includes(e.kind);return t.jsxs("section",{className:"rounded-lg border bg-card p-4 sm:p-6",children:[t.jsx("h2",{className:"text-xl font-semibold",children:e.title}),x&&t.jsx("iframe",{src:x,title:e.title,className:"mt-4 min-h-[420px] w-full rounded-md border",allow:"fullscreen",referrerPolicy:"str
1ict-origin-when-cross-origin"}),e.html&&t.jsx("div",{className:"prose prose-neutral mt-4 max-w-none",dangerouslySetInnerHTML:{__html:H(e.html)}}),g&&t.jsxs("p",{className:"mt-5 text-sm text-muted-foreground",children:["Progress for this ",e.kind.toUpperCase()," activity is recorded by its learning player."]}),l&&e.completionPercent!==100&&t.jsxs("div",{className:"mt-6",children:[t.jsxs(v,{disabled:w,onClick:async()=>{y(!0),d("");try{await c()}catch{d("Progress could not be saved. Try again.")}finally{y(!1)}},children:[w&&t.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),"Mark complete"]}),p&&t.jsx("p",{role:"alert",className:"mt-2 text-sm text-destructive",children:p})]}),e.completionPercent===100&&t.jsx("p",{className:"mt-6 text-sm font-medium text-green-700 dark:text-green-300",children:"Completed"})]})}function _e({error:e,detail:n,secureUrl:a,onRetry:r}){const[b,m]=Ue(e);return t.jsx(Y,{icon:be,title:b,description:n||m,action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[t.jsxs(v,{onClick:r,variant:"outline",children:[t.jsx(he,{className:"mr-2 h-4 w-4"}),"Try again"]}),(e==="auth"||e==="expired"||e==="unknown")&&t.jsx(v,{asChild:!0,children:t.jsxs("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:["Open secure learning portal",t.jsx(F,{className:"ml-2 h-4 w-4"})]})})]})})}function Y({icon:e,title:n,description:a,action:r}){return t.jsxs("div",{className:"mx-auto flex min-h-80 max-w-xl flex-col items-center justify-center text-center",children:[t.jsx(e,{className:"mb-4 h-10 w-10 text-muted-foreground"}),t.jsx("h1",{className:"text-xl font-semibold",children:n}),t.jsx("p",{className:"mb-5 mt-2 text-sm text-muted-foreground",children:a}),r]})}function I(e,n){return{...n?{"X-Embed-Origin":n}:{},...e?{Authorization:`Bearer ${e}`}:{}}}function Te({module:e,embedId:n,sessionToken:a,parentOrigin:r,post:b}){const m=e.module,c=e.moduleSlug,[w,y]=f.useState(e.completionPercent||0),[p,d]=f.useState(!1),x=X(e.mediaUrl);f.useEffect(()=>{y(e.completionPercent||0)},[e.completionPercent,c]);const u=async(l=!1,g=w)=>{d(!0);try{if(!(await fetch(`/api/embed/${encodeURIComponent(n)}/modules/${encodeURIComponent(c)}/progress`,{method:"POST",headers:{"Content-Type":"application/json",...I(a,r)},body:JSON.stringify({progress:l?100:g,completed:l})})).ok)throw new Error("Progress could not be saved");l&&(y(100),b("lesson_completed",{moduleSlug:c}))}finally{d(!1)}};return t.jsxs("section",{className:"space-y-5 rounded-lg border bg-card p-4 sm:p-6",children:[t.jsxs("div",{children:[t.jsx("h2",{className:"text-xl font-semibold",children:e.title}),m?.shortSummary&&t.jsx("p",{className:"mt-2 text-muted-foreground",children:m.shortSummary})]}),x&&t.jsx("audio",{controls:!0,className:"w-full",src:x,onLoadedMetadata:l=>{const g=Number(m?.progress?.positionSeconds??m?.progress?.playbackPosition??m?.progress?.lastPositionSeconds??0);Number.isFinite(g)&&g>0&&g<l.currentTarget.duration&&(l.currentTarget.currentTime=g)},onTimeUpdate:l=>{l.currentTarget.duration&&y(Math.round(l.currentTarget.currentTime/l.currentTarget.duration*100))},onPause:l=>{l.currentTarget.duration&&u(!1,Math.round(l.currentTarget.currentTime/l.currentTarget.duration*100))},onEnded:()=>{u(!0)},children:"Audio for this learning module is unavailable in this browser."}),e.html&&t.jsx("div",{className:"prose prose-neutral max-w-none",dangerouslySetInnerHTML:{__html:H(e.html)}}),Array.isArray(m?.takeaways)&&t.jsx(O,{title:"Key takeaways",items:m.takeaways}),Array.isArray(m?.actionItems)&&t.jsx(O,{title:"Actions to try",items:m.actionItems}),Array.isArray(m?.discussionQuestions)&&t.jsx(O,{title:"Discussion prompts",items:m.discussionQuestions}),t.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t pt-4",children:[t.jsxs("span",{className:"text-sm text-muted-foreground",children:[Math.round(w),"% complete"]}),t.jsxs(v,{disabled:p||w===100,onClick:()=>{u(!0)},children:[p&&t.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),"Mark module complete"]})]}),a&&t.jsx(Pe,{embedId:n,moduleSlug:c,sessionToken:a,parentOrigin:r,onComplete:(l,g)=>b("lesson_completed",{moduleSlug:c,passed:l,score:g})})]})}function O({title:e,items:n}){return t.jsxs("section",{children:[t.jsx("h3",{className:"font-semibold",children:e}),t.jsx("ul",{className:"mt-2 list-disc space-y-1 pl-5 text-sm",children:n.map((a,r)=>
1t.jsx("li",{children:typeof a=="string"?a:JSON.stringify(a)},r))})]})}function Pe({embedId:e,moduleSlug:n,sessionToken:a,parentOrigin:r,onComplete:b}){const[m,c]=f.useState({}),[w,y]=f.useState(null),p=T({queryKey:["/api/embed",e,"quiz",n],queryFn:async()=>{const u=await fetch(`/api/embed/${encodeURIComponent(e)}/modules/${encodeURIComponent(n)}/quiz`,{headers:I(a,r)});if(u.status===404)return null;if(!u.ok)throw new Error("Quiz could not be loaded");return u.json()},retry:!1}),d=p.data?.quiz;if(!d||!Array.isArray(p.data?.questions))return null;const x=async()=>{const u=await fetch(`/api/embed/${encodeURIComponent(e)}/modules/${encodeURIComponent(n)}/quiz/${encodeURIComponent(d.id)}/attempts`,{method:"POST",headers:{"Content-Type":"application/json",...I(a,r)},body:JSON.stringify({answers:Object.entries(m).map(([g,L])=>({questionId:g,answerId:L}))})});if(!u.ok)return;const l=await u.json();y({passed:!!l.passed,score:Number(l.score||0)}),b(!!l.passed,Number(l.score||0))};return t.jsxs("section",{className:"border-t pt-5",children:[t.jsx("h3",{className:"text-lg font-semibold",children:d.title}),d.description&&t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:d.description}),t.jsx("div",{className:"mt-4 space-y-5",children:p.data.questions.map((u,l)=>t.jsxs("fieldset",{children:[t.jsxs("legend",{className:"font-medium",children:[l+1,". ",u.questionText]}),t.jsx("div",{className:"mt-2 space-y-2",children:(u.answers||[]).map(g=>t.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm",children:[t.jsx("input",{type:"radio",name:u.id,value:g.id,checked:m[u.id]===g.id,onChange:()=>c(L=>({...L,[u.id]:g.id}))}),g.answerText]},g.id))})]},u.id))}),w?t.jsxs("p",{className:"mt-4 font-medium",children:[w.passed?"Passed":"Submitted",": ",w.score,"%"]}):t.jsx(v,{className:"mt-5",disabled:Object.keys(m).length!==p.data.questions.length,onClick:()=>{x()},children:"Submit quiz"})]})}function $e({contentId:e,title:n,embedId:a,sessionToken:r,parentOrigin:b}){const[m,c]=f.useState(!1),w=f.useRef(Symbol("embed-scorm-runtime")),y=f.useRef(()=>{}),p=T({queryKey:["/api/embed",a,"scorm-state",e],queryFn:async()=>{const x=await fetch(`/api/embed/${encodeURIComponent(a)}/content/${encodeURIComponent(e)}/scorm-state`,{headers:I(r,b)});if(!x.ok)throw new Error("SCORM state could not be loaded");return x.json()},enabled:!!r,retry:!1}),d=T({queryKey:["/api/embed",a,"scorm",e],queryFn:async()=>{const x=await fetch(`/api/embed/${encodeURIComponent(a)}/content/${encodeURIComponent(e)}/scorm-launch`,{headers:I(r,b)});if(!x.ok)throw new Error("SCORM package could not launch");return x.json()},enabled:!!r,retry:!1});return y.current=x=>{fetch(`/api/embed/${encodeURIComponent(a)}/content/${encodeURIComponent(e)}/scorm-state`,{method:"PUT",headers:{"Content-Type":"application/json",...I(r,b)},body:JSON.stringify({state:x})}).then(async u=>{if(!u.ok)return;(await u.json()).completed&&b&&window.parent!==window&&window.parent.postMessage(J("lesson_completed",a,{contentId:e}),b)}).catch(()=>{})},f.useLayoutEffect(()=>{if(!p.data||!d.data)return;const x=Le(p.data.state||{},L=>y.current(L)),u=window;u.API=x.api12,u.API_1484_11=x.api2004,u.__lcScormOwner=w.current,c(!0);const l=()=>y.current(x.state),g=window.setInterval(l,3e4);return window.addEventListener("visibilitychange",l),()=>{window.clearInterval(g),window.removeEventListener("visibilitychange",l),l(),u.__lcScormOwner===w.current&&(delete u.API,delete u.API_1484_11,delete u.__lcScormOwner)}},[p.data,d.data]),d.isLoading||p.isLoading||!m?t.jsx("div",{className:"flex min-h-72 items-center justify-center",children:t.jsx($,{className:"h-7 w-7 animate-spin"})}):d.error||p.error||!d.data?.launchUrl?t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"This SCORM activity could not be launched. Try again or open the secure portal."}):t.jsxs("section",{children:[t.jsx("h2",{className:"mb-3 text-xl font-semibold",children:n}),t.jsx("iframe",{src:d.data.launchUrl,title:n,className:"min-h-[640px] w-full rounded-md border",allow:"fullscreen",referrerPolicy:"strict-origin-when-cross-origin"})]})}
1export{Fe 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.