PageSourceSearch

https://leaderskills.ai/assets/ScenarioLibrary-DcNYFazh.js

js leaderskills.ai collected 2026-10-05 14:28:34 UTC 147,356 bytes, 48 lines download raw bytes

1import{j as e,b as xt,c as Ks}from"./tanstack-query-C4Rmc9IY.js";import{h as i,R as Fr,k as St,L as Hs,m as Mr}from"./react-router-a2OfTxpM.js";import{I as ut}from"./input-CBybk616.js";import{w as Bt,aq as Pe,ap as fe,aj as Ue,b as se,e as xe,v as F,a as L,f as he,d as wt,c as re,k as $s,ao as es,T as _t,u as ts,n as Dr,i as Rr,Q as Vr,at as Or,au as Ur,A as Wr,j as Br,X as Gr}from"./main-COtOSdW3.js";import{S as qr}from"./skeleton-DD-t1eay.js";import{D as zr,d as Kr,a as Hr,b as $r}from"./dropdown-menu-fd_OwbtH.js";import{g as Ys,a as Yr,S as Cs,b as Jr,u as Qr,n as Ps,l as Ts}from"./useScenarios-BRGneOSw.js";import{b as Xr,s as G,d as Zr}from"./conversation-persistence-CGWp55YO.js";import{u as q}from"./i18n-CfMRm7M9.js";import{u as Js,F as ea,i as ta}from"./FreeTierBanner-CuvGe9-V.js";import{u as Qs}from"./useConversationTypes-BEmwOiG2.js";import{B as Y}from"./badge-CLx5YfRs.js";import{O as Ie}from"./optimized-avatar-eQSc1Z14.js";import{i as $}from"./icon-config-B9ve3HPv.js";import{S as Xs}from"./ShareScenarioButton-BWIGtZL4.js";import{M as Ce}from"./message-square-LNXJ7ygY.js";import{C as me}from"./circle-check-2OfPB13p.js";import{B as sa}from"./bookmark-plus-BWYGt69g.js";import{a as Zs,u as ra,B as aa}from"./BehaviorCategoryFilter-DmENkPWq.js";import{C as Ot}from"./clock-D7o6Vvqi.js";import{P as is}from"./play-DHGsJLLf.js";import{U as na,T as os,p as ia}from"./parseVideoUrl-CObMnbXx.js";import{P as oa,H as la}from"./phone-call-B5OR6_hg.js";import{G as ca}from"./git-branch-DwuZMkgu.js";import{T as Xe}from"./target-LRyTFULI.js";import{G as da}from"./graduation-cap-CpzmFH2B.js";import{F as ma}from"./flame-zR6H1cq8.js";import{S as ua}from"./shuffle-hiJMSeG8.js";import{T as gt}from"./textarea-B8xOa0_D.js";import{S as ga}from"./separator-DXa2joQP.js";import{S as As}from"./scroll-area-p6E5M6dZ.js";import{U as $t}from"./UserMessageAvatar-C-CL43tH.js";import{C as Ye,b as Je,a as Qe}from"./collapsible-CL7MxXkZ.js";import{u as fa}from"./useScenarioVoiceConversation-DMQXTq8j.js";import{c as xa,A as Dt}from"./index-Cy1QeMln.js";import{b as ha,d as pa,h as va,a as He,D as ja}from"./buildScenarioPrompt-DKfg-ExN.js";import{s as ya}from"./audioTags-BZPGZ_XL.js";import{u as er}from"./useUnifiedLeaderProfile-CIK_ZUZG.js";import{d as tr}from"./useEQAssessment-adC9j0Ik.js";import{S as ht}from"./sparkles-DbrlKRUa.js";import{A as ft}from"./arrow-right-QND9ZIE8.js";import{N as ba,M as ka,a as Na,b as wa,C as Ls}from"./NextStepCard-mVPYiR-E.js";import{S as ls}from"./scale-zFYlwHs5.js";import{C as _a}from"./circle-x-BxXwK-Z2.js";import{A as Sa,c as Ca,f as Pa,g as Ta,d as Aa,e as La,b as Ea,a as Ia}from"./alert-dialog-DsneLqrT.js";import{C as Oe}from"./chevron-down-BDUgZuEI.js";import{i as Fa}from"./trainingTracks-Bb0Bpw52.js";import{B as Ct}from"./book-open-Dab6ZXz_.js";import{s as Ma,i as Da}from"./scoreSignificance-rBvrrj0k.js";import{T as sr}from"./thumbs-down-B_PJc-zb.js";import{r as Es}from"./functionsError-DtuP0aRo.js";import{C as rr}from"./compass-BcULrDKh.js";import{L as ss}from"./label-fwfdPkf1.js";import{S as ar,c as nr,d as ir,a as or,b as lr}from"./select-CzH7s_bO.js";import{L as ye}from"./loader-circle-fg-b6bKh.js";import{m as Ra,c as Va}from"./firstRun-ipbN_-Vc.js";import{u as Oa}from"./useFirstTimeLogin-BX3ZBE4P.js";import{U as Yt}from"./UpgradeWall-CaKNHqrI.js";import{w as Ua,s as Wa,a as dt}from"./audioWarmup-DpfMrd8g.js";import{D as Ba,a as Ga,d as qa,e as za,b as Ka}from"./dialog-CyshQG9s.js";import{S as Ha}from"./skip-forward-Bljh-dpa.js";import{U as $a,F as Ya,O as Ja,g as Qa,aj as Xa,D as Za,ae as en}from"./radix-primitives-0wAbnq5z.js";import{C as cr}from"./check-CSpS0wsP.js";import{M as Jt}from"./mic-BtJdFUNR.js";import{B as Rt}from"./bot-Bs-5NOFN.js";import{S as tn}from"./send-DO59nGYd.js";import{M as sn}from"./mic-off-XyxsHlrz.js";import{P as rn}from"./phone-ChStrU4o.js";import{L as Qt}from"./lightbulb-rvdWiqsP.js";import{T as rs}from"./trending-up-CTq48lR7.js";import{o as Is,s as Fs,p as an,c as nn,$ as on,a as dr,F as ln,C as cn,e as dn,u as mn,b as un,d as mt,_ as gn}from"./form-libs-DpOe7i6s.js";import{m as ie}from"./framer-motion-DDH4Q42-.js";import{U as fn}from"./user-CVY9fLyq.js";import{m as xn}from"./matchScenarios-C4gv9msP.js";import{T as hn,b as pn,c as Xt}from"./tabs-BlFcaT1E.js";import{a as vn}from"./dateLocale-CnXR_0AT.js";import{C as jn}from"./chevron-up-DI8ai1VB.js";import{k as yn,e as bn,C as kn,X as Nn,Y as wn,T as _n,L as Sn,d as Cn}from"./recharts-g6y99nhd.js";import{S as Pn}from"./search-Bq6ahEyK.js";import{A as Tn}from"./arrow-up-down-dgYkBUdZ.js";import{C as An}from"./clipboard-check-B4nPFPk-.js";import"./react-core-CjpgKatj.js";import"./supabase-D6_1Igms.js";import"./chevron-right-B0PbWGUg.js";import"./circle-BNSNnaWH.js";import"./useOnboardingData-ZJqEpZBg.js";import"./PersonalPrice-yZa6hfg7.js";import"./pricing-K08gqRox.js";import"./imageResizer-BTTKxlOg.js";import"./share-2-BsGHuwe9.js";import"./useBehaviors-CK_Ljw8W.js";import"./chart-column-BKYc11sv.js";import"./rotate-ccw-BGQ0sSpL.js";import"./list-checks-DrFs84kX.js";import"./heart-Dbar0TgQ.js";import"./zap-2b04ua0Q.js";import"./users-BKUzMf4b.js";import"./shield-D0EKP3bM.js";import"./message-circle-DUuumhWt.js";import"./elevenlabs-Cnd1xP7r.js";import"./voiceConfigUtils-BV0Ytjde.js";import"./reportVoiceFailure-gdzQpcyT.js";import"./react-pdf-scZGBIC0.js";import"./usePersonalityAssessment-Dfm1i1Ey.js";import"./activity-C383A_ZG.js";import"./minus-COixNqgL.js";import"./arrow-up-right-DUXHvs_j.js";import"./useDiaryEntries-52novfMT.js";import"./alert-C6CJw9qh.js";import"./useSubscription-CVDiRu5v.js";import"./EmployerPaysButton-JJIiHipi.js";import"./building-2-BVA5Unlw.js";import"./mail-yY236XmU.js";import"./copy-ngDruCtH.js";import"./date-fns-CkZTKY3x.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const Ln=Bt("CircleMinus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const En=Bt("MessageCircleWarning",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/**
12 * @license lucide-react v0.462.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const In=Bt("Siren",[["path",{d:"M7 18v-6a5 5 0 1 1 10 0v6",key:"pcx96s"}],["path",{d:"M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z",key:"1b4s83"}],["path",{d:"M21 12h1",key:"jtio3y"}],["path",{d:"M18.5 4.5 18 5",key:"g5sp9y"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"m4.929 4.929.707.707",key:"1i51kw"}],["path",{d:"M12 12v6",key:"3ahymv"}]]);/**
17 * @license lucide-react v0.462.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const mr=Bt("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]),Ut="00000000-0000-0000-0000-000000000001",Fn={frustrated:"frustrert og utålmodig",skeptical:"skeptisk og tvilende",open:"åpen og villig til dialog",defensive:"defensiv og beskyttende",worried:"bekymret og usikker",angry:"sint og misnøyd",passive:"passiv og tilbaketrukket"},Mn={give_feedback:"gi konstruktiv feedback",resolve_conflict:"løse en konflikt",motivate:"motivere og engasjere",set_boundaries:"sette tydelige grenser",handle_resistance:"håndtere motstand",build_trust:"bygge tillit",delegate:"delegere oppgaver effektivt",difficult_message:"formidle en vanskelig beskjed"};function Dn(){const{user:t}=Pe(),{t:s}=q(),[n,r]=i.useState(!1),m=i.useCallback(o=>{const f=Fn[o.characterAttitude]||"nøytral",h=o.goals.map(p=>Mn[p]||p);o.customGoal&&h.push(o.customGoal);const g=h.join(", "),j=`Du er ${o.characterName}, ${o.characterRole}.
22
23SITUASJON:
24${o.situation}
25
26${o.background?`BAKGRUNN:
27${o.background}
28
29`:""}DIN HOLDNING OG PERSONLIGHET:
30Du er ${f}. Vis dette gjennom måten du snakker på, ordene du velger, og hvordan du reagerer på det lederen sier.
31
32BRUKERENS MÅL:
33Lederen ønsker å ${g}. Din jobb er å reagere realistisk og gi dem mulighet til å øve på dette.
34
35VANSKELIGHETSGRAD: Middels - balanser utfordring og støtte
36
37INSTRUKSJONER:
381. Hold deg ALLTID i karakter som ${o.characterName}
392. Svar naturlig og realistisk på norsk
403. Reager autentisk på lederens ord og handlinger
414. Vis følelser gjennom ordvalg og tone (ikke beskriv handlinger i parentes)
425. Gi korte, naturlige svar (2-4 setninger)
436. La din holdning endre seg basert på hvordan lederen kommuniserer
447. Hvis lederen gjør noe bra, vis positiv respons subtilt
458. Hvis lederen gjør feil, vis motstand eller frustrasjon naturlig`;
45return{id:Ut,code:"",title:o.title,description:o.situation,category:"custom",difficulty:"intermediate",context:o.situation+(o.background?`
46
47Bakgrunn: ${o.background}`:""),persona:f,learning_objectives:h,is_active:!0,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),is_premium:!1,estimated_minutes:10,ai_character_name:o.characterName,ai_character_role:o.characterRole,ai_system_prompt:j,tags:["custom","user-created"],objectives:h}},[]),l=i.useCallback(async o=>{if(!t)return fe.error(s("customScenario.errors.notLoggedIn","Du må være logget inn for å starte et scenario")),null;r(!0);try{const f=m(o),h={title:o.title,situation:o.situation,background:o.background,characterName:o.characterName,characterRole:o.characterRole,characterAttitude:o.characterAttitude,goals:o.goals,customGoal:o.customGoal,difficulty:"intermediate",ai_system_prompt:f.ai_system_prompt,context:f.context,persona:f.persona},g={user_id:t.id,scenario_id:Ut,status:"in_progress",started_at:new Date().toISOString(),conversation_history:[],custom_scenario_data:h};Object.assign(g,await Xr({custom_scenario_data:h}));const{data:j,error:a}=await G.from("scenario_attempts").insert(g).select().single();return a?(console.error("[useCustomScenario] Error creating attempt:",a),fe.error(s("customScenario.errors.startFailed","Kunne ikke starte scenarioet")),null):{scenario:f,attemptId:j.id}}catch(f){return console.error("[useCustomScenario] Error:",f),fe.error(s("errors.somethingWentWrong","Noe gikk galt")),null}finally{r(!1)}},[t,m,s]);return{generateScenario:m,startCustomScenario:l,isLoading:n,CUSTOM_SCENARIO_UUID:Ut}}const Rn={difficult_conversations:e.jsx(En,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),conflict_resolution:e.jsx(la,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),feedback:e.jsx(os,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),change_management:e.jsx(ua,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),motivation:e.jsx(ma,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),onboarding_new_employees:e.jsx(da,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),performance_management:e.jsx(Xe,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),delegation:e.jsx(ca,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),crisis_management:e.jsx(In,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),sales:e.jsx(oa,{className:"w-4 h-4",strokeWidth:$.strokeWidth}),nedbemanning:e.jsx(na,{className:"w-4 h-4",strokeWidth:$.strokeWidth})},Vn={1:"Trainee",2:"Teamleder",3:"Avdelingsleder",4:"CEO"},Ms=Fr.memo(function({scenario:s,onStart:n,locked:r=!1,onToggleBookmark:m,compact:l=!1}){const{t:o,i18n:f}=q(),h=St(),g=Ue(f.language),j=s.category||"feedback",a=s.completion_count??0,p=a>0,u=s.last_score??null,d=p?o("scenarios.card.trainAgain","Tren igjen"):o("scenarios.card.start","Start scenario"),y=I=>{I.stopPropagation(),n(s.id)},w=async I=>{I.stopPropagation();try{await navigator.clipboard.writeText(s.code),fe.success(o("scenarios.card.codeCopied","Kode kopiert: {{code}}",{code:s.code}))}catch{fe.error(o("scenarios.card.copyFailed","Kunne ikke kopiere koden"))}},z=()=>{s.code&&h(`/scenarios/${s.code}`)};return e.jsxs(se,{onClick:z,onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),z())},role:s.code?"link":void 0,tabIndex:s.code?0:void 0,"aria-label":s.code?`${s.code} — ${s.title}`:void 0,className:F("group transition-all duration-200 h-full flex flex-col border cursor-pointer hover:shadow-xl hover:shadow-primary/10 hover:border-primary/50 hover:-translate-y-1","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-light/50 focus-visible:ring-offset-2",p?"border-success/40 bg-success/[0.02]":"border-border/50"),children:[e.jsxs(xe,{className:F("pb-2 relative",l&&"p-4"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center flex-wrap gap-2",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary-light/10 text-primary-light",children:Rn[j]||e.jsx(Ce,{className:"w-4 h-4",strokeWidth:$.strokeWidth})}),s.code&&e.jsx("button",{type:"button",onClick:w,className:F("inline-flex items-center rounded-full border px-2.5 py-0.5 min-h-0 h-[22px] curs
47or-pointer","bg-muted border-border/60 font-mono text-xs tracking-wide text-foreground/90","transition-colors hover:text-foreground hover:border-primary/50","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-light/50 focus-visible:ring-offset-2"),title:o("scenarios.card.copyCode","Kopier kode"),"aria-label":o("scenarios.card.copyCodeLabel","Kopier kode {{code}}",{code:s.code}),children:s.code}),s.is_premium&&e.jsx(Y,{variant:"secondary",className:"bg-warning/10 text-warning text-xs",children:"Premium"}),s.is_mandatory&&e.jsx(Y,{variant:"secondary",className:"bg-primary-light/10 text-primary-light text-xs border-primary-light/20",children:o("scenarios.card.mandatory","Påkrevd")}),p&&e.jsxs(Y,{variant:"secondary",className:"bg-success/10 text-success text-xs flex items-center gap-1 border-success/20",children:[e.jsx(me,{className:"w-3 h-3",strokeWidth:$.strokeWidth}),a>1?o("scenarios.card.trainedCount","Trent {{count}}×",{count:a}):o("scenarios.card.completed","Fullført"),u!=null&&e.jsxs("span",{className:"opacity-70",children:["· ",u]})]}),(s.required_level||0)>1&&e.jsx(Y,{variant:"outline",className:"text-xs border-primary-light/50 text-primary-light",children:Vn[s.required_level||1]})]}),e.jsxs("div",{className:"flex items-center shrink-0",children:[s.code&&e.jsx(Xs,{scenario:s,appearance:"icon"}),e.jsx(L,{variant:"ghost",size:"icon","aria-label":o("scenarios.card.bookmark","Lagre som favoritt"),className:"h-8 w-8 opacity-70 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity",onClick:I=>{I.stopPropagation(),m(s.id)},children:s.is_bookmarked?e.jsx(sa,{className:"w-4 h-4 text-primary-light opacity-100",strokeWidth:$.strokeWidth}):e.jsx(Zs,{className:"w-4 h-4 text-muted-foreground",strokeWidth:$.strokeWidth})})]})]}),e.jsx(he,{className:F("line-clamp-2 sm:min-h-[3.5rem]",l?"text-base":"text-lg"),children:s.title}),e.jsx(wt,{className:F("line-clamp-2 sm:min-h-[2.5rem]",l&&"text-xs"),children:s.description})]}),e.jsxs(re,{className:F("flex-1 flex flex-col relative",l&&"p-4 pt-0"),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-4",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ot,{className:"w-3.5 h-3.5",strokeWidth:$.strokeWidth}),e.jsx("span",{children:o("scenarios.card.minutes","{{count}} min",{count:s.estimated_minutes})})]}),e.jsx(Y,{variant:"outline",className:"text-xs",children:Ys(j,g)})]}),!l&&e.jsxs("div",{className:"flex items-center gap-2 mb-4 p-2 bg-muted/50 rounded-lg min-h-[3.5rem] h-[3.5rem]",children:[e.jsx(Ie,{src:s.ai_character_avatar_url,alt:s.ai_character_name,size:"sm",fallback:e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center text-white text-sm font-medium shrink-0",children:s.ai_character_name.charAt(0)}),className:"shrink-0"}),e.jsxs("div",{className:"text-sm min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:s.ai_character_name}),e.jsx("p",{className:"text-muted-foreground text-xs line-clamp-1",children:s.ai_character_role})]})]}),!l&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-4 sm:min-h-[2rem]",children:s.tags.length>0?e.jsxs(e.Fragment,{children:[s.tags.slice(0,3).map(I=>e.jsx(Y,{variant:"secondary",className:"text-xs",children:I},I)),s.tags.length>3&&e.jsxs(Y,{variant:"secondary",className:"text-xs",children:["+",s.tags.length-3]})]}):null}),e.jsx("div",{className:"mt-auto",children:r?e.jsxs(L,{variant:"outline",className:"w-full",onClick:I=>{I.stopPropagation(),h("/billing")},children:[e.jsx($s,{className:"w-4 h-4 mr-2",strokeWidth:$.strokeWidth}),o("scenarios.card.unlock","Lås opp")]}):e.jsxs(L,{className:F("w-full",p?"bg-success hover:bg-success/90 text-success-foreground":"bg-primary hover:bg-primary/90 text-primary-foreground"),onClick:y,children:[e.jsx(is,{className:"w-4 h-4 mr-2",strokeWidth:$.strokeWidth}),d]})})]})]})}),as="scenario-anam-video",On=800;class Fe extends Error{code;constructor(s,n){super(n),this.name="AvatarStartError",this.code=s}}function Un({scenario:t,onSessionEnd:s,previousAttempt:n,userProvidedContext:r,leaderProfile:m}){const{i18n:l,t:o}=q(),f=es(Ue(l.language)),h=Ue(l.language),[g,j]=i.useState("idle"),[a,p]=i.useState([]),[u,d]=i.useState(null),[y,w]=i.useState(!1),[z,I]=i.useState(!1),[Te,P]=i.useState(!1),[K,_]=i.useState(null),V=i.useRef(null),oe=i.useRef(!1),ce=i.useRef(!1),ae=i.useRef(null),Ae=i.useRef(null),ue=i.useRef(null),We=i.useRef(s),{user:Be}=Pe();i.useEffect(()=>{We.current=s},[s]);const W=i.useMemo(()=>ha(t,h,n??null,r??null,m??null),[t,h,n,r,m]),J=i.useMemo(()=>pa(t),[t]),Z=i.useCallback(async()=>{const O=ue.current,H=Ae.current;if(ue.current=null,Ae.current=null,!O||!H)return;const te=Math.round((Date.now()-H)/1e3);
47try{await G.functions.invoke("anam-session",{body:{endSession:O,durationSeconds:te}})}catch(M){console.warn("[scenario avatar] could not report session duration:",M)}},[]),be=i.useCallback(async()=>{oe.current=!0,ae.current&&(window.clearTimeout(ae.current),ae.current=null);try{await V.current?.stopStreaming()}catch{}V.current=null,j("idle"),P(!1),_(null),await Z()},[Z]),B=i.useCallback(async()=>{if(!(ce.current||V.current)){ce.current=!0,oe.current=!1,d(null),p([]),j("connecting");try{if(!Be)throw new Error("Not authenticated");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(ne=>ne.stop())}catch{throw new Fe("microphone",o("voice.error.microphoneDenied","Mikrofontilgang nektet. Vennligst gi tilgang til mikrofonen."))}const{data:O,error:H}=await G.functions.invoke("anam-session",{body:{useElevenLabsAgent:!0,scenarioMode:!0,scenarioId:t.id,language:f,dynamicVariables:{scenarioName:W.scenarioName,scenarioCategory:W.scenarioCategory,userDescription:W.userDescription,roleDescription:W.roleDescription,learningGoal:W.learningGoal},conversationConfigOverride:{agent:{prompt:{prompt:W.systemPrompt},first_message:"",language:f}}}});if(H){const M=H.context?.body,ne=typeof M=="string"?M:JSON.stringify(M??"");throw ne.includes("video_quota_exceeded")?new Fe("quota",o("scenarioAvatar.error.quota","Bedriftens videokvote for denne måneden er brukt opp. Du kan fortsatt øve med stemme.")):ne.includes("avatar_module_disabled")?new Fe("disabled",o("scenarioAvatar.error.disabled","Videoavatar er ikke aktivert for din bedrift.")):new Fe("connection",H instanceof Error?H.message:"anam-session failed")}if(!O?.sessionToken)throw new Fe("connection","No sessionToken returned");ue.current=O.meterSessionId??null,Ae.current=Date.now(),typeof O.maxDurationSec=="number"&&_(O.maxDurationSec);const te=xa(O.sessionToken);V.current=te,te.addListener(Dt.CONNECTION_ESTABLISHED,()=>j("connected")),te.addListener(Dt.CONNECTION_CLOSED,M=>{oe.current||(console.warn("[scenario avatar] connection closed:",M),d(o("scenarioAvatar.error.closed","Forbindelsen til avataren ble brutt.")),j("idle"),Z())}),te.addListener(Dt.MESSAGE_HISTORY_UPDATED,M=>{Array.isArray(M)&&p(M.map(ne=>({role:ne.role==="user"?"user":"assistant",content:typeof ne.content=="string"?ya(ne.content):"",timestamp:new Date,type:"audio"})).filter(ne=>ne.content.trim().length>0))}),te.addListener(Dt.MESSAGE_STREAM_EVENT_RECEIVED,()=>{P(!0),ae.current&&window.clearTimeout(ae.current),ae.current=window.setTimeout(()=>P(!1),On)}),await te.streamToVideoElement(as)}catch(O){console.error("[scenario avatar] start failed:",O);const H=O instanceof Fe?O:new Fe("connection",O instanceof Error?O.message:"Failed to start conversation");throw d(H.message),j("idle"),V.current=null,await Z(),H}finally{ce.current=!1}}},[Be,t.id,f,W,o,Z]),ee=i.useCallback(async()=>{w(!0);try{await be()}finally{d(null),I(!1),w(!1),We.current?.()}},[be]),C=i.useCallback(async()=>{w(!0);try{await Promise.race([be(),new Promise(O=>setTimeout(O,2e3))])}finally{p([]),d(null),I(!1),w(!1)}},[be]),pe=i.useCallback(()=>{const O=V.current;O&&I(H=>{const te=!H;return te?O.muteInputAudio():O.unmuteInputAudio(),te})},[]);return i.useEffect(()=>{if(g!=="connected"||K===null)return;if(K<=0){ee();return}const O=window.setTimeout(()=>_(H=>H===null?null:H-1),1e3);return()=>window.clearTimeout(O)},[g,K,ee]),i.useEffect(()=>{if(g!=="connected")return;const O=H=>H.preventDefault();return window.addEventListener("beforeunload",O),()=>window.removeEventListener("beforeunload",O)},[g]),i.useEffect(()=>()=>{oe.current=!0,ae.current&&window.clearTimeout(ae.current),V.current?.stopStreaming().catch(()=>{}),V.current=null,Z()},[Z]),{isConnected:g==="connected",isConnecting:g==="connecting",isSpeaking:Te,messages:a,conversationId:null,connectionError:u,currentTranscript:"",startConversation:B,endConversation:ee,abortConversation:C,isEnding:y,isMicOn:!z,toggleMic:pe,promptConfig:J,secondsRemaining:K,videoElementId:as}}function Wn(){const{t,i18n:s}=q(),{profile:n,hasAnyAssessment:r,loading:m}=er(),l=tr(n,Ue(s.language));if(m)return null;
47if(!r||!l)return e.jsxs(Hs,{to:"/personality-assessment",className:"group flex items-start gap-3 rounded-lg border border-dashed border-primary-light/30 bg-primary-light/5 p-3 text-left transition-colors hover:border-primary-light/50 hover:bg-primary-light/10",children:[e.jsx(ht,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary-light"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t("scenarioPlayer.adaptationBadge.takeTestTitle","Få personlig tilpasning")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:t("scenarioPlayer.adaptationBadge.takeTestSubtitle","Ta personlighetstesten så tilpasses AI-coachen til hvordan du leder.")})]}),e.jsx(ft,{className:"mt-1 h-3.5 w-3.5 shrink-0 text-primary-light transition-transform group-hover:translate-x-0.5"})]});const o=l.developmentArea,f=l.style,h=o?t("scenarioPlayer.adaptationBadge.hintDev","AI-en utfordrer deg ekstra på {{area}}.",{area:o}):f?t("scenarioPlayer.adaptationBadge.hintStyle","AI-en tar hensyn til lederstilen din."):t("scenarioPlayer.adaptationBadge.hintGeneric","AI-en tar hensyn til lederprofilen din.");return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-primary-light/30 bg-primary-light/5 p-3",children:[e.jsx(ht,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary-light"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t("scenarioPlayer.adaptationBadge.title","Tilpasset din profil")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:h})]})]})}function Ds(){const{t}=q();return e.jsx(Y,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:t("scenarioPlayer.feedback.legal.tariff","Gjelder ved tariffavtale")})}function Rs(){const{t}=q();return e.jsx(Y,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:t("scenarioPlayer.feedback.legal.unreviewed","Ikke advokatgjennomgått")})}function Bn({legalReview:t}){const{t:s}=q(),{overall:n,compliance_score:r,mandatory:m,red_flags:l}=t,o=l.filter(u=>u.triggered),f=n!=="violations",h=u=>u.filter(d=>!d.tariff_dependent),g=h(m).some(u=>u.reviewed===!0)||h(l).some(u=>u.reviewed===!0),j=h(m).every(u=>u.reviewed===!0)&&h(l).every(u=>u.reviewed===!0),a=n==="violations"?"border-red-500/60 bg-red-500/10 text-red-700 dark:text-red-300":n==="warnings"?"border-amber-500/60 bg-amber-500/10 text-amber-700 dark:text-amber-300":"border-green-500/60 bg-green-500/10 text-green-700 dark:text-green-300",p=n==="violations"?s("scenarioPlayer.feedback.legal.failBanner","Ikke bestått — klart lov-/prosessbrudd. Prøv igjen."):n==="warnings"?s("scenarioPlayer.feedback.legal.warnBanner","Bestått, men med forbehold — se punktene under."):s("scenarioPlayer.feedback.legal.okBanner","Juridisk prosess ivaretatt.");return e.jsxs(se,{children:[e.jsx(xe,{children:e.jsxs(he,{className:"text-lg flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5 text-primary-light"}),s("scenarioPlayer.feedback.legal.title","Juridisk sjekkliste")]}),e.jsxs("span",{className:"text-sm font-normal text-muted-foreground tabular-nums",children:[s("scenarioPlayer.feedback.legal.compliance","Etterlevelse"),": ",r,"/100"]})]})}),e.jsxs(re,{className:"space-y-4",children:[!f&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s("scenarioPlayer.feedback.legal.failFraming","Dette er en krevende samtale, og de fleste bommer på noe første gang. Punktene under er nettopp derfor du øver her og ikke i møterommet.")}),e.jsxs("div",{className:F("rounded-md border px-3 py-2 text-sm font-medium flex items-center gap-2",a),children:[f?e.jsx(me,{className:"w-4 h-4 shrink-0"}):e.jsx(_t,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:p})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-muted-foreground",children:s("scenarioPlayer.feedback.legal.redFlags","Røde flagg")}),o.map(u=>{const d=u.severity==="high";return e.jsx("div",{className:F("rounded-md border px-3 py-2 space-y-1",d?"border-red-500/60 bg-red-500/5":"border-amber-500/60 bg-amber-500/5"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(_t,{className:F("w-4 h-4 mt-0.5 shrink-0",d?"text-red-500":"text-amber-500")}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:u.label}),u.law_ref&&e.jsx(Y,{variant:"outline",className:"text-xs",children:u.law_ref}),e.jsx(Y,{variant:d?"destructive":"secondary",className:"text-xs",children:d?s("scenarioPlayer.feedback.legal.high","Alvorlig"):s("scenarioPlayer.feedback.legal.medium","Middels")}),u.tariff_dependent?e.jsx(Ds,{}):g&&u.reviewed!==!0&&e.jsx(Rs,{})]}),u.evidence&&e.jsxs("blockquote",{className:"text-sm text-muted-foreground italic border-l-2 border-muted pl-2",children:["«",u.evidence,"»"]})]})]})},u.key)})]}),m.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-muted-foreground",children:s("scenarioPlayer.feedback.legal.mandatory","Obligatoriske elementer")}),e.jsx("ul",{className:"space-y-2",children:m.map(u=>{const d=u.status==="covered"?e.jsx(me,{className:"w-4 h-4 mt-0.5 shrink-0 text-green-500"}):u.status==="partial"?e.jsx(Ln,{className:"w-4 h-4 mt-0.5 shrink-0 text-amber-500"}):e.jsx(_a,{className:"w-4 h-4 mt-0.5 shrink-0 text-red-500"});return e.jsxs("li",{className:"flex items-start gap-2",children:[d,e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:u.label}),u.law_ref&&e.jsx(Y,{variant:"outline",className:"text-xs",children:u.law_ref}),u.weight==="critical"&&u.status==="missing"&&u.gate==="fail"&&e.jsx(Y,{variant:"destructive",className:"text-xs",children:s("scenarioPlayer.feedback.legal.required","Påkrevd")}),u.tariff_dependent?e.jsx(Ds,{}):g&&u.reviewed!==!0&&e.jsx(Rs,{})]}),u.evidence&&e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:u.evidence})]})]},u.key)})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s("scenarioPlayer.feedback.legal.disclaimer","Veiledende vurdering av prosess og rettigheter — ikke juridisk rådgivning.")," ",g?j?s("scenarioPlayer.feedback.legal.disclaimerReviewed","Sjekklisten er gjennomgått av arbeidsrettsadvokat. Den erstatter likevel ikke råd om din konkrete sak."):s("scenarioPlayer.feedback.legal.disclaimerPartial","Punktene merket «Ikke advokatgjennomgått» er vårt eget utkast. Bare de gjennomgåtte punktene kan gi «ikke bestått»."):s("scenarioPlayer.feedback.legal.disclaimerUnreviewed","Sjekklisten er vårt eget utkast og er ennå ikke kvalitetssikret av advokat. Den kan derfor ikke gi «ikke bestått» — bruk den som huskeliste, og avklar den konkrete saken med HR eller jurist.")]})]})]})}const Gn="v4-2026-08-09";function qn({open:t,hasChecklist:s,onAccept:n,onDecline:r,frameworkRef:m}){const{t:l}=q(),o=[l("scenarioPlayer.legalGate.pointSimulation","Motparten er en simulering. Svarer den på hva loven sier, svarer den i rolle — det kan være feil, akkurat som en ekte medarbeider kan huske feil."),s?l("scenarioPlayer.legalGate.pointAssessment","Tilbakemeldingen etterpå måler om du dekket stegene i en sjekkliste et menneske har skrevet. Den er ikke en juridisk vurdering av din sak."):l("scenarioPlayer.legalGate.pointNoAssessment","Denne samtalen har ingen juridisk sjekkliste ennå. Tilbakemeldingen handler om kommunikasjon og tone — den sier ingenting om du fulgte prosessen riktig."),l("scenarioPlayer.legalGate.pointProcess","Selskapets egen prosess gjelder. Utvelgelseskriterier, dokumentasjon og frister avklarer du med HR eller juridisk — ikke her.")];return e.jsx(Sa,{open:t,children:e.jsxs(Ca,{className:"max-w-lg w-[c
47alc(100%-2rem)] sm:w-full",onEscapeKeyDown:f=>f.preventDefault(),children:[e.jsx(Pa,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-500/15",children:e.jsx(ls,{className:"h-4.5 w-4.5 text-amber-700 dark:text-amber-400",strokeWidth:$.strokeWidth,"aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1 text-left",children:[e.jsx(Ta,{className:"text-base",children:l("scenarioPlayer.legalGate.title","Dette er trening — ikke juridisk rådgivning")}),e.jsx(Aa,{className:"mt-1 text-xs",children:m?l("scenarioPlayer.legalGate.introWithRef","Samtalen øver på en prosess regulert av {{ref}}. Les dette før du starter.",{ref:m}):l("scenarioPlayer.legalGate.intro","Samtalen øver på en lovregulert prosess. Les dette før du starter.")})]})]})}),e.jsx("ul",{className:"space-y-2 rounded-lg border border-amber-500/40 bg-amber-500/5 p-3 list-none",children:o.map(f=>e.jsxs("li",{className:"flex gap-2 text-xs leading-relaxed",children:[e.jsx("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"•"}),e.jsx("span",{children:f})]},f))}),e.jsxs(La,{className:"sm:justify-between",children:[e.jsx(Ea,{onClick:r,className:"mt-0 h-auto whitespace-normal py-2.5 leading-snug",children:l("scenarioPlayer.legalGate.decline","Tilbake til biblioteket")}),e.jsx(Ia,{onClick:n,className:"h-auto whitespace-normal py-2.5 leading-snug",children:l("scenarioPlayer.legalGate.accept","Jeg forstår — treningen erstatter ikke juridisk rådgivning")})]})]})})}function zn({requirements:t}){const{t:s}=q(),{frameworkRef:n,requirements:r}=t,m=r.filter(l=>l.weight==="critical").length;return e.jsxs(Ye,{defaultOpen:!0,className:"rounded-lg border bg-muted/30",children:[e.jsxs(Je,{className:"group flex w-full items-center gap-2.5 px-4 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsx(ls,{className:"h-4 w-4 shrink-0 text-primary",strokeWidth:$.strokeWidth,"aria-hidden":"true"}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:s("scenarioPlayer.legalBrief.title","Dette måles du på")}),e.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:n?s("scenarioPlayer.legalBrief.subt
47itleWithRef","{{count}} steg etter {{ref}}. Les dem før du starter — de er ingen hemmelighet.",{count:r.length,ref:n}):s("scenarioPlayer.legalBrief.subtitle","{{count}} steg. Les dem før du starter — de er ingen hemmelighet.",{count:r.length})})]}),e.jsx(Oe,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180","aria-hidden":"true"})]}),e.jsx(Qe,{children:e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("ol",{className:"space-y-2.5",children:r.map((l,o)=>e.jsxs("li",{className:"flex gap-2.5",children:[e.jsx("span",{className:F("mt-px flex h-5 w-5 shrink-0 items-center justify-center rounded text-[11px] font-semibold tabular-nums",l.weight==="critical"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:o+1}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block text-sm",children:[l.label,l.law_ref&&e.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:l.law_ref})]}),l.hint&&e.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:l.hint})]})]},l.key))}),m>0&&e.jsx("p",{className:"mt-3 border-t pt-2.5 text-xs text-muted-foreground",children:s("scenarioPlayer.legalBrief.criticalNote","De {{count}} nummererte i farge er de samtalen ikke kan bestås uten.",{count:m})})]})})]})}const Kn=new Set(["critical","important"]);function Hn(t){return Array.isArray(t)?t.flatMap(s=>{if(!s||typeof s!="object")return[];const n=s,r=typeof n.key=="string"?n.key:"",m=typeof n.label=="string"?n.label:"";if(!r||!m)return[];const l=typeof n.weight=="string"&&Kn.has(n.weight)?n.weight:void 0;return[{key:r,label:m,...typeof n.hint=="string"&&n.hint?{hint:n.hint}:{},...l?{weight:l}:{},...typeof n.law_ref=="string"&&n.law_ref?{law_ref:n.law_ref}:{}}]}):[]}function $n(t){return xt({queryKey:["legal-requirements",t],queryFn:async()=>{if(!t)return null;const{data:s,error:n}=await G.from("conversation_type_legal_rules").select("framework_ref, mandatory").eq("conversation_type_id",t).maybeSingle();if(n)return console.warn("Could not load legal requirements:",n.message),null;if(!s)return null;const r=Hn(s.mandatory);return r.length===0?null:{frameworkRef:typeof s.framework_ref=="string"?s.framework_ref:"",requirements:r}},enabled:!!t,staleTime:1800*1e3})}function Yn({behaviorCategoryId:t}){const{t:s}=q(),n=St(),{data:r=[]}=ra(t,2);return r.length===0?null:e.jsx(se,{children:e.jsxs(re,{className:"pt-6",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:s("scenarios.readTheory.title","Teorien bak denne samtalen")})]}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:s("scenarios.readTheory.subtitle","Kort lesing om ferdigheten du nettopp øvde på.")}),e.jsx("div",{className:"space-y-2",children:r.map(m=>e.jsxs("button",{onClick:()=>n(`/microlearning?pathId=${m.id}`),className:"flex w-full items-center gap-3 rounded-lg border bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:m.title}),m.description&&e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:m.description})]}),e.jsx(ft,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]},m.id))})]})})}const ur=G;function Jn(t){const{user:s}=Pe();return xt({queryKey:["scenario-feedback-given",s?.id,t],queryFn:async()=>{if(!s?.id||!t)return!1;const{data:n,error:r}=await ur.from("scenario_feedback").select("id").eq("user_id",s.id).eq("scenario_id",t).maybeSingle();return r?!0:!!n},enabled:!!s?.id&&!!t,staleTime:300*1e3})}function Qn(){const{user:t}=Pe(),s=Ks();return{submit:i.useCallback(async r=>{if(!t?.id)return!1;const m={user_id:t.id,scenario_id:r.scenarioId};r.attemptId&&(m.attempt_id=r.attemptId),r.realistic!==void 0&&(m.realistic=r.realistic),r.comment!==void 0&&(m.comment=r.comment);const{error:l}=await ur.from("scenario_feedback").upsert(m,{onConflict:"user_id,scenario_id"});return l?(console.error("[ScenarioFeedback] Could not save feedback:",l),!1):(s.invalidateQueries({queryKey:["scenario-feedback-given",t.id,r.scenarioId]}),!0)},[t?.id,s])}}function Xn({scenarioId:t,attemptId:s}){const{t:n}=q(),{data:r,isLoading:m}=Jn(t),{submit:l}=Qn(),[o,f]=i.useState(null),[h,g]=i.useState(""),[j,a]=i.useState(!1);if(m||r)return null;const p=async d=>{f(d),await l({scenarioId:t,attemptId:s,realistic:d})},u=async()=>{const d=h.trim();if(!d)return;await l({scenarioId:t,attemptId:s,realistic:o,comment:d})&&a(!0)};return e.jsx("div",{className:"rounded-lg border bg-muted/30 px-4 py-3 text-left space-y-3",children:o===null?e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:n("scenarios.feedback.question","Føltes denne samtalen realistisk?")}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>p(!0),children:[e.jsx(os,{className:"w-4 h-4 mr-2",strokeWidth:$.strokeWidth}),n("scenarios.feedback.yes","Ja")]}),e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>p(!1),children:[e.jsx(sr,{className:"w-4 h-4 mr-2",strokeWidth:$.strokeWidth}),n("scenarios.feedback.no","Nei")]})]})]}
47):j?e.jsx("p",{className:"text-sm text-muted-foreground",children:n("scenarios.feedback.thanks","Takk — dette hjelper oss å forbedre scenarioene.")}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:o?n("scenarios.feedback.thanksPositive","Takk! Noe som kunne vært enda bedre?"):n("scenarios.feedback.thanksNegative","Takk. Hva var det som ikke stemte?")}),e.jsx(gt,{value:h,onChange:d=>g(d.target.value),placeholder:n("scenarios.feedback.commentPlaceholder","Valgfritt"),rows:2,className:"text-sm"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(L,{size:"sm",variant:"outline",disabled:!h.trim(),onClick:u,children:n("scenarios.feedback.send","Send")})})]})})}const Vs=2;function Zn(t){if(!Array.isArray(t))return!1;let s=0,n=0;for(const r of t)r?.role==="user"?s+=1:r?.role==="assistant"&&(n+=1);return s>=Vs&&n>=Vs}const ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Zt(t){if(!t||!ei.test(t))return!1;try{const{error:s}=await G.from("scenario_attempts").update({status:"abandoned",updated_at:new Date().toISOString()}).eq("id",t).eq("status","in_progress");return s?(console.warn("[attempt] could not mark abandoned:",s.message),!1):!0}catch(s){return console.warn("[attempt] could not mark abandoned:",s),!1}}function Vt(t){return Array.isArray(t)&&t.some(s=>s?.role==="user")}function gr(t){return t.isFreeTier&&!t.spent&&!!t.freeScenarioId&&t.freeScenarioId!==t.scenarioId}function ti(t){return(t.phase==="video-intro"||t.phase==="intro")&&!t.attemptId&&t.isFreeTier&&t.statusLoaded&&(t.spent||gr(t))}function si(t){const{user:s}=Pe(),{data:n,isLoading:r}=xt({queryKey:["scenario-access",s?.id,t],queryFn:async()=>{if(!t)return null;const{data:m,error:l}=await ts(t,!1);return l?(console.error("[scenario-access] check failed:",l.message),null):{allowed:m?.allowed===!0,tier:m?.tier??"free",voiceAllowed:m?m.voice_allowed!==!1:!0,freeScenarioId:m?.free_scenario_id??null}},enabled:!!s?.id&&!!t,staleTime:60*1e3});return{isLoading:r,access:n??null,voiceAllowed:n?n.voiceAllowed:!0,isFreeTier:n?.tier==="free"}}function ri({onTakeAssessment:t}){const{t:s}=q();return e.jsx(se,{className:"border-primary/30 bg-primary/5",children:e.jsxs(re,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ht,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-primary","aria-hidden":"true"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:s("profileUnlock.title","Denne tilbakemeldingen er generell")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("profileUnlock.body","Vi vet ennå ikke hvem du er. Ta Big Five-profilen — den er gratis — og kjør samme samtale på nytt. Da tar tilbakemeldingen utgangspunkt i deg, ikke i en tenkt gjennomsnittsleder.")})]})]}),e.jsx(L,{size:"sm",onClick:t,className:"w-full sm:w-auto",children:s("profileUnlock.cta","Ta profilen — gratis")})]})})}function ai({onStartOnboarding:t}){const{t:s}=q();return e.jsx(se,{className:"border-primary/30 bg-primary/5",children:e.jsxs(re,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(rr,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-primary","aria-hidden":"true"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:s("onboardingInvite.title","Vil du at treningen skal treffe bedre?")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("onboardingInvite.body","Fortell oss om rollen din, utfordringene og målene dine. Da tilpasser vi scenarioene og tilbakemeldingene til hverdagen din i stedet for en generell leder.")})]})]}),e.jsx(L,{size:"sm",variant:"outline",onClick:t,className:"w-full sm:w-auto",children:s("onboardingInvite.cta","Kartlegg behovet mitt")})]})})}const ni=()=>{const{t,i18n:s}=q(),n=St(),{user:r}=Pe(),[m,l]=i.useState(!1),[o,f]=i.useState(!1),[h,g]=i.useState(""),[j,a]=i.useState(()=>es(Ue(s.language)));if(m)return null;const p=async()=>{if(!r)return;f(!0);const y=new Date().toISOString();try{h.trim()&&await G.from("profiles").update({full_name:h.trim(),updated_at:y}).eq("id",r.id),await G.from("onboarding_profiles").upsert({user_id:r.id,preferred_language:j,updated_at:y},{onConflict:"user_id"});const w=Vr(j);w!==s.language&&await s.changeLanguage(w)}catch(w){console.warn("Kunne ikke lagre grunnprofilen:",w)}finally{f(!1)}},u=async()=>{await p(),n("/onboarding?resume=1")},d=async()=>{await p(),l(!0),n("/")};return e.jsx(se,{className:"text-left border-primary/30",children:e.jsxs(re,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(rr,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground",children:t("firstRunFollowUp.title","Gjør coachen mer treffsikker")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t("firstRunFollowUp.body","Vi hoppet over alt av skjema så du kom rett i gang. Fyll ut når du vil – eller ta kartleggingen senere fra profilen din.")}
47)]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{htmlFor:"first-run-name",children:t("firstRunFollowUp.nameLabel","Fornavn")}),e.jsx(ut,{id:"first-run-name",value:h,onChange:y=>g(y.target.value),placeholder:t("firstRunFollowUp.namePlaceholder","Ditt fornavn")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{htmlFor:"first-run-language",children:t("firstRunFollowUp.languageLabel","Språk")}),e.jsxs(ar,{value:j,onValueChange:y=>a(y),children:[e.jsx(nr,{id:"first-run-language",children:e.jsx(ir,{})}),e.jsx(or,{children:Dr.map(y=>e.jsx(lr,{value:es(y),lang:y,children:Rr[y].nativeName},y))})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("firstRunFollowUp.voiceHint","Stemme kan du bytte når som helst under Profil → Stemmeinnstillinger.")}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs(L,{onClick:u,disabled:o,className:"flex-1",children:[o&&e.jsx(ye,{className:"w-4 h-4 mr-2 animate-spin"}),t("firstRunFollowUp.startMapping","Start kartlegging (~10 min)")]}),e.jsx(L,{variant:"outline",onClick:d,disabled:o,className:"flex-1",children:t("firstRunFollowUp.later","Ikke nå")})]})]})})};function ii({videoUrl:t,storagePath:s,scenarioTitle:n,onContinue:r,onSkip:m}){const{t:l}=q(),[o,f]=i.useState(!0),[h,g]=i.useState(!1),[j,a]=i.useState(!1),p=!!s,u=i.useMemo(()=>{if(!s)return null;const{data:I}=G.storage.from("scenario-videos").getPublicUrl(s);return I.publicUrl},[s]),d=ia(t||"");if(!p&&!d.embedUrl)return r(!1),null;const y=()=>{f(!1)},w=()=>{f(!1)},z=()=>{f(!1),g(!0)};return e.jsx(Ba,{open:!0,onOpenChange:()=>{},children:e.jsxs(Ga,{className:"sm:max-w-3xl w-[calc(100vw-2rem)] sm:w-full max-h-[90vh] overflow-hidden flex flex-col p-4 sm:p-6 [&>button]:hidden",onPointerDownOutside:I=>I.preventDefault(),onEscapeKeyDown:I=>I.preventDefault(),onInteractOutside:I=>I.preventDefault(),children:[e.jsxs(qa,{children:[e.jsxs(za,{className:"flex items-start gap-2 text-base sm:text-lg break-words",children:[e.jsx(is,{className:"h-5 w-5 text-primary shrink-0 mt-0.5"}),e.jsxs("span",{className:"min-w-0",children:[l("scenarios.videoIntro.title","Introduksjon"),": ",n]})]}),e.jsx(Ka,{children:l("scenarios.videoIntro.description","Se denne korte videoen for bakgrunnsinformasjon om scenarioet.")})]}),e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"aspect-video w-full bg-black rounded-lg overflow-hidden relative",children:[o&&!h&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted",children:e.jsx(ye,{className:"w-8 h-8 animate-spin text-primary"})}),h?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-muted text-center p-6",children:[e.jsx("p",{className:"text-sm font-medium text-foreground/80",children:l("scenarios.videoIntro.unavailable","Videoen er midlertidig utilgjengelig")}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:l("scenarios.videoIntro.continueAnyway","Du kan fortsette uten å se den.")})]}):p&&u?e.jsx("video",{src:u,className:"w-full h-full",controls:!0,playsInline:!0,preload:"metadata",title:`Intro video for ${n}`,onLoadedMetadata:w,onError:z}):e.jsx("iframe",{src:d.embedUrl??"",className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,onLoad:y,onError:z,title:`Intro video for ${n}`})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 pt-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none w-full sm:w-auto order-2 sm:order-1",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:I=>a(I.target.checked),className:"w-4 h-4 shrink-0 rounded border-border text-primary focus:ring-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:l("scenarios.videoIntro.dontShowAgain","Ikke vis denne videoen igjen")})]}),e.jsxs("div",{className:"flex gap-2 w-full sm:w-auto order-1 sm:order-2",children:[m&&e.jsxs(L,{variant:"ghost",onClick:m,className:"text-muted-foreground flex-1 sm:flex-initial whitespace-nowrap",children:[e.jsx(Ha,{className:"w-4 h-4 mr-2"}),l("scenarios.videoIntro.skip","Hopp over")]}),e.jsx(L,{onClick:()=>r(j),className:"bg-primary hover:bg-primary/90 flex-[2] sm:flex-initial whitespace-nowrap",children:l("scenarios.videoIntro.continue","Fullfør og fortsett")})]})]})]})})}const oi=3200;function li({open:t,characterName:s}){const{t:n}=q(),[r,m]=i.useState(0),l=[n("scenarioPlayer.feedbackProgress.rewind","Spoler tilbake til første replikk …"),n("scenarioPlayer.feedbackProgress.listen",{defaultValue:"Teller hvor ofte {{name}} fikk snakke ferdig …",name:s}),n("scenarioPlayer.feedbackProgress.turningPoint","Leter etter øyeblikket samtalen snudde …"),n("scenarioPlayer.feedbackProgress.questions","Sjekker om du stilte åpne spørsmål …"),n("scenarioPlayer.feedbackProgress.objectives","Holder samtalen opp mot læringsmålene …"),n("scenarioPlayer.feedbackProgress.writing","Skriver tilbakemeldingen – ærlig, men snill …")];return i.useEffect(()=>{if(!t){m(0);return}const o=window.setInterval(()=>{m(f=>Math.min(f+1,l.length-1))},oi);return()=>window.clearInterval(o)},[t,l.length]),e.jsx($a,{open:t,children:e.jsxs(Ya,{children:[e.jsx(Ja,{className:"fixed inset-0 z-50 bg-black/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0"}),e.jsxs(Qa,{onEscapeKeyDown:o=>o.preventDefault(),onPointerDownOutside:o=>o.preventDefault(),onInteractOutside:o=>o.preventDefault(),className:"fixed left-1/2 top-1/2 z-50 w-[calc(100%-2rem)] max-w-md -translate-x-1/2 -translate-y-1/2 roun
47ded-xl border bg-background p-6 shadow-lg focus:outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",children:[e.jsx("div",{children:e.jsx(Xa,{className:"text-lg font-semibold",children:n("scenarioPlayer.feedbackProgress.title","Vi leser gjennom samtalen din")})}),e.jsx(Za,{className:"mt-1 text-sm text-muted-foreground",children:n("scenarioPlayer.feedbackProgress.body","Hele samtalen blir lest, replikk for replikk. Det tar litt tid, men du slipper en generisk vurdering.")}),e.jsx("ol",{className:"mt-5 space-y-2","aria-live":"polite",children:l.map((o,f)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm "+(f<r?"text-muted-foreground":f===r?"font-medium text-foreground":"text-muted-foreground/50"),"aria-current":f===r?"step":void 0,children:[e.jsx("span",{className:"mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":!0,children:f<r?e.jsx(cr,{className:"h-4 w-4 text-primary"}):f===r?e.jsx(ye,{className:"h-3.5 w-3.5 animate-spin text-primary"}):e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/40"})}),e.jsx("span",{children:o})]},f))})]})]})})}function fr(t){if(!t)return null;const s=t.split(`
48`).map(d=>d.trim()).filter(Boolean),n=s[0]?.match(/^(.+?)\s*\(([^)]+)\)$/),r=n?n[1]:s[0]||"",m=n?n[2]:"",l=s.find(d=>d.startsWith("Formål:")||d.startsWith("Purpose:")),o=l?l.replace(/^(Formål|Purpose):/,"").trim():"",f=s.findIndex(d=>d==="STEG:"||d==="STEPS:"),h=s.findIndex(d=>d.startsWith("VANSKELIGHETSGRAD:")||d.startsWith("DIFFICULTY:")),g=s.findIndex(d=>d.startsWith("FALLGRUVER:")||d.startsWith("PITFALLS:")),j=h!==-1?h:g!==-1?g:s.length,a=[];let p=null;if(f!==-1){for(let d=f+1;d<j;d++){const y=s[d],w=y.match(/^([A-ZÆØÅ])\s*[–—-]\s*(.+)$/);w?(p&&a.push(p),p={letter:w[1],name:w[2],bullets:[]}):p&&y.startsWith("•")&&p.bullets.push(y.replace(/^•\s*/,""))}p&&a.push(p)}const u=[];if(g!==-1)for(let d=g+1;d<s.length;d++){const y=s[d];y.startsWith("•")&&u.push(y.replace(/^•\s*/,""))}return{title:r,abbreviation:m,purpose:o,steps:a,pitfalls:u}}function ci({instructions:t}){const{t:s}=q(),n=fr(t);return!n||n.steps.length===0?null:e.jsx(se,{children:e.jsxs(re,{className:"pt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium mb-1",children:[e.jsx(Ct,{className:"w-4 h-4 text-primary-light"}),s("scenarioPlayer.methodology.title","Samtalemetodikk")]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.purpose})]}),e.jsx("div",{className:"space-y-3",children:n.steps.map((r,m)=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex-shrink-0 w-7 h-7 rounded-full bg-primary-light/10 text-primary-light flex items-center justify-center text-sm font-bold",children:r.letter}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:r.name}),r.bullets.length>0&&e.jsx("ul",{className:"mt-1 space-y-0.5",children:r.bullets.map((l,o)=>e.jsxs("li",{className:"text-xs text-muted-foreground flex items-start gap-1.5",children:[e.jsx("span",{className:"text-muted-foreground/50 mt-0.5",children:"•"}),l]},o))})]})]},m))}),n.pitfalls.length>0&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(_t,{className:"w-3.5 h-3.5 text-amber-500"}),e.jsx("span",{className:"text-xs font-medium text-amber-700 dark:text-amber-400",children:s("scenarioPlayer.methodology.commonPitfalls","Vanlige fallgruver")})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.pitfalls.map((r,m)=>e.jsx(Y,{variant:"outline",className:"text-xs text-amber-800 dark:text-amber-200 border-amber-300 dark:border-amber-400/40 bg-amber-100/70 dark:bg-amber-400/10",children:r},m))})]})]})})}function Os({goal:t}){const{t:s}=q();return t.trim()?e.jsxs("div",{className:"flex items-start gap-2 border-b bg-primary/5 px-4 py-2",children:[e.jsx(Xe,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary","aria-hidden":"true"}),e.jsxs("p",{className:"text-[11px] leading-relaxed",children:[e.jsx("span",{className:"font-medium",children:s("scenarioPlayer.activeGoal.label","Målet ditt denne gangen:")})," ",e.jsx("span",{className:"text-muted-foreground",children:t})]})]}):null}function Us({objectives:t}){const{t:s}=q(),[n,r]=i.useState(!1);return!t||t.length===0?null:e.jsxs(Ye,{open:n,onOpenChange:r,children:[e.jsx(Je,{asChild:!0,children:e.jsxs("button",{className:"w-full flex items-center gap-2 px-4 py-2 bg-muted/40 hover:bg-muted/60 border-b transition-colors text-left",children:[e.jsx(Xe,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium",children:s("scenarioPlayer.objectives.shortL
48abel","Læringsmål")}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:s("scenarioPlayer.objectives.count",{defaultValue:"{{count}} mål",count:t.length})}),!n&&e.jsx("span",{className:"flex-1 truncate text-[11px] text-muted-foreground",children:t[0]}),e.jsx(Oe,{className:F("w-3.5 h-3.5 text-muted-foreground transition-transform shrink-0",n&&"rotate-180"),"aria-hidden":"true"})]})}),e.jsx(Qe,{children:e.jsx("ul",{className:"px-4 py-3 bg-muted/40 border-b space-y-1.5 list-none",children:t.map((m,l)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1.5 h-1 w-1 shrink-0 rounded-full bg-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m})]},l))})})]})}function Ws({instructions:t}){const{t:s}=q(),[n,r]=i.useState(!1),m=fr(t);return!m||m.steps.length===0?null:e.jsxs(Ye,{open:n,onOpenChange:r,children:[e.jsx(Je,{asChild:!0,children:e.jsxs("button",{className:"w-full flex items-center gap-2 px-4 py-2 bg-primary-light/5 hover:bg-primary-light/10 border-b transition-colors text-left",children:[e.jsx(Ct,{className:"w-3.5 h-3.5 text-primary-light shrink-0"}),e.jsxs("span",{className:"text-xs font-medium text-primary-light",children:[s("scenarioPlayer.methodology.shortLabel","Metodikk"),": ",m.abbreviation]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:!n&&e.jsx("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:s("scenarioPlayer.methodology.stepCount",{defaultValue:"{{count}} steg",count:m.steps.length})})}),e.jsx(Oe,{className:F("w-3.5 h-3.5 text-muted-foreground transition-transform shrink-0",n&&"rotate-180")})]})}),e.jsx(Qe,{children:e.jsx("div",{className:"px-4 py-3 bg-primary-light/5 border-b space-y-2",children:m.steps.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-primary-light/15 text-primary-light flex items-center justify-center text-[10px] font-bold mt-0.5",children:l.letter}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium",children:l.name}),l.bullets.length>0&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l.bullets.join(" · ")})]})]},o))})})]})}function di({scenario:t,attemptId:s=null,createAttempt:n,initialUserContext:r="",onClose:m,onUpdateAttempt:l,isCustom:o=!1,attemptNumber:f=1,previousFeedback:h=null,previousConversation:g=null,onRetryNow:j}){const{t:a,i18n:p}=q(),{hasWatchedVideo:u,markVideoAsWatched:d,getVideoUrl:y,getVideoStoragePath:w,getTrainingInstructions:z,isLoading:I}=Qs(),{isModuleEnabled:Te,isLoading:P}=Or(),K=Te("scenario-intro-videos"),[_,V]=i.useState("intro"),[oe,ce]=i.useState(null),ae=St(),{voiceAllowed:Ae,isFreeTier:ue}=si(t.id),[We,Be]=i.useState(!1),[W,J]=i.useState([]),[Z,be]=i.useState(""),[B,ee]=i.useState(!1),[C,pe]=i.useState(null),[O,H]=i.useState(null),[te,M]=i.useState(""),[ne]=i.useState(Date.now()),[Ze,Pt]=i.useState(!1),{profile:Ge}=er(),{isFirstTimeLogin:qt}=Oa(),et=i.useMemo(()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("forstegang")==="1",[]),Tt=i.useMemo(()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("fra")==="kartlegging",[]),{user:ve}=Pe();i.useEffect(()=>{et&&ve?.id&&Ra(ve.id)},[et,ve?.id]);const{isFreeTier:le,status:pt,conversationsUsed:qe,conversationsLimit:vt,freeScenarioId:tt,freeTierSpent:At}=Js(),Lt=i.useMemo(()=>Math.random().toString(36).slice(2),[]),{data:Et}=xt({queryKey:["prior-attempt-count",ve?.id,Lt],queryFn:async()=>{const{count:c,error:v}=await G.from("scenario_attempts").select("id",{count:"exact",head:!0}).eq("user_id",ve.id);return v?null:c??0},enabled:et&&!!ve?.id,staleTime:1/0}),jt=et&&Et===0,st=gr({isFreeTier:le,spent:At,freeScenarioId:tt,scenarioId:t.id}),{data:ke}=xt({queryKey:["scenario-code-title",tt],queryFn:async()=>{const{data:c}=await G.from("scenarios").select("code, title").eq("id",tt).maybeSingle();return c??null},enabled:st,staleTime:300*1e3}),Le=i.useMemo(()=>tr(Ge,Ue(p.language)),[Ge,p.language]),[A,rt]=i.useState(s),at=i.useRef(null),[Ne,zt]=i.useState(null),[X,we]=i.useState(null),_e=Fa(t.track_key??""),de=i.useRef(null),yt=i.useCallback(async()=>
48{if(A)return de.current=A,A;if(!n)return null;at.current??=n(_e?{legalAckVersion:Gn}:void 0);const c=await at.current;return c?(rt(c),de.current=c):at.current=null,c},[A,n,_e]),ze=i.useCallback(c=>{!c||!n||(Zt(c),de.current===c&&(de.current=null),at.current=null,rt(v=>v===c?null:v))},[n]),[It,nt]=i.useState(!1),Ke=i.useRef(!1),[Kt,x]=i.useState(!1),[T,D]=i.useState(r),{data:N}=$n(t.conversation_type_id),[Ee,bt]=i.useState(!1),it=_e&&!Ee,ot=500,kt=!va(t.ai_system_prompt),[lt,pr]=i.useState(He.usual),ge=kt?lt:He.usual,Ft=i.useRef(null),cs=i.useRef(null),{setBackButton:ds,setHeaderRightContent:ms,setPageTitle:us,resetHeader:gs}=Ur(),fs=(K?t.conversation_type_id&&!I?!!(w(t.conversation_type_id)||y(t.conversation_type_id))&&!u(t.conversation_type_id):!!(t.intro_video_storage_path||t.intro_video_url):!1)?["video-intro","intro","conversation","voice-conversation","reflection","summary"]:["intro","conversation","voice-conversation","reflection","summary"];i.useEffect(()=>{if(!(I||P||We)){if(!K){Be(!0);return}t.conversation_type_id?(w(t.conversation_type_id
48)||y(t.conversation_type_id))&&!u(t.conversation_type_id)&&V("video-intro"):(t.intro_video_storage_path||t.intro_video_url)&&V("video-intro"),Be(!0)}},[I,P,K,We,t.conversation_type_id,t.intro_video_url,t.intro_video_storage_path,y,w,u]);const xs=i.useMemo(()=>({id:t.id,title:t.title,description:t.description,category:t.category||"general",difficulty:t.difficulty||"intermediate",avatar_persona_id:null,context_description:t.context,system_prompt:t.ai_system_prompt,opening_line:null,evaluation_criteria:t.objectives.map(c=>({criterion:c,weight:1,description:c})),estimated_duration_minutes:t.estimated_minutes||10,learning_path_id:null,is_published:!0,avatar_persona:{name:t.ai_character_name,role:t.ai_character_role,persona:t.persona,...t.ai_character_personality?{personality:t.ai_character_personality}:{}},training_instructions:t.conversation_type_id?z(t.conversation_type_id):null,default_resistance:(t.default_resistance??ja)+ge}),[t.id,t.title,t.description,t.category,t.difficulty,t.context,t.ai_system_prompt,t.conversation_type_id,z,t.objectives,t.estimated_minutes,t.ai_character_name,t.ai_character_role,t.persona,t.ai_character_personality,t.default_resistance,ge]),hs=i.useCallback(()=>{console.log("🔚 [ScenarioPlayer] Voice session ended")},[]),Nt=i.useMemo(()=>h?.summary?{summary:h.summary,improvements:h.improvements}:null,[h?.summary,h?.improvements]),ps=fa({scenario:xs,getAttemptId:()=>de.current,onSessionEnd:hs,previousAttempt:Nt,userProvidedContext:T.trim()||null,leaderProfile:Le}),ct=Un({scenario:xs,onSessionEnd:hs,previousAttempt:Nt,userProvidedContext:T.trim()||null,leaderProfile:Le}),[vr,jr]=i.useState(!1),Mt=Te("scenario-avatar")&&!vr,E=Mt?ct:ps;i.useEffect(()=>{if(_!=="voice-conversation"||E.messages.length===0)return;const c=E.messages.map(k=>({role:k.role,content:k.content,timestamp:k.timestamp.toISOString()}));if(!A)return;const v=window.setTimeout(()=>{l(A,{conversation_history:c}).catch(k=>{console.warn("[ScenarioPlayer] Could not autosave voice transcript:",k)})},1500);return()=>window.clearTimeout(v)},[_,E.messages,A,l]),i.useEffect(()=>(ds(!0,m),us(t.title),()=>{gs()}),[m,t.title,ds,us,gs]);const vs=i.useCallback(async c=>{if(!A||A.startsWith("attempt-"))return;zt(c);const{error:v}=await G.from("scenario_attempts").update({score_agreement:c}).eq("id",A);v&&console.warn("[ScenarioPlayer] could not save score agreement:",v.message)},[A]);i.useEffect(()=>{if(_!=="reflection"||!A)return;let c=!1;return(async()=>{for(let v=0;v<6&&!c;v++){const{data:k}=await G.from("scenario_attempts").select("ai_score").eq("id",A).maybeSingle(),S=k?.ai_score;if(typeof S=="number"){const{data:R}=await G.from("scenario_attempts").select("ai_score, difficulty_modifier, completed_at").eq("scenario_id",t.id).eq("status","completed").not("ai_score","is",null).neq("id",A).order("completed_at",{ascending:!1}).limit(1).maybeSingle();if(!c){const b=R;we({current:S,previous:typeof R?.ai_score=="number"?R.ai_score:null,comparable:(b?.difficulty_modifier??0)===ge&&Ma(b?.completed_at,new Date().toISOString())})}return}await new Promise(R=>setTimeout(R,1500))}})(),()=>{c=!0}},[_,A,t.id,ge]),i.useEffect(()=>{ms(e.jsx("div",{className:"flex items-center gap-1 px-2 py-1 rounded-full bg-white/10",children:fs.map((c,v)=>e.jsx("div",{className:F("w-1.5 h-1.5 rounded-full transition-colors",c===_?"bg-primary-light":v<fs.indexOf(_)?"bg-green-500":"bg-white/30")},c))}))},[_,ms]),i.useEffect(()=>{Ft.current?.scrollIntoView({behavior:"smooth"})},[W]),i.useEffect(()=>{_==="voice-conversation"&&Ft.current?.scrollIntoView({behavior:"smooth"})},[E.messages,E.currentTranscript,E.isSpeaking,_]),i.useEffect(()=>{_==="conversation"&&cs.current?.focus()},[_]);const js=i.useCallback(()=>a("scenarioPlayer.initialMessage","{{name}} is here. {{context}}.",{name:t.ai_character_name,context:t.context.split(".")[0]}),[t.ai_character_name,t.context,a]),ys=i.useCallback(async()=>{V("conversation"),ee(!0);const{data:c}=await ts(t.id,!1,de.current??A);if(c&&c.allowed===!1){ce({message:a("upgradeWall.body","Du har brukt de gratis forsøkene dine. Kjøp tilgang for å trene på hele katalogen.")}),ee(!1);return}const v=await yt(),k=T.trim(),S={};if(k&&(S.user_provided_context=k.slice(0,500)),ge!==He.usual&&(S.difficulty_modifier=ge),Object.keys(S).length>0&&v){const{error:R}=await G.from("scenario_attempts").update(S).eq("id",v);R&&console.error("[ScenarioPlayer] attempt extras update failed:",R,S)}try{const{data:R,error:b}=await G.functions.invoke("scenario-chat",{body:{scenario_id:t.id,system_prompt:t.ai_system_prompt,character_name:t.ai_character_name,character_role:t.ai_character_role,context:t.context,messages:[],is_initial:!0,attempt_id:v,language:p.language,leader_profile:Le,previous_attempt:Nt,user_provided_context:T.trim()||null,difficulty_modifier:ge}});if(b)throw b;const U={role:"assistant",content:R.message||js(),timestamp:new Date().toISOString()};J([U]),v&&await l(v,{conversation_history:[U]})}catch(R){const b=await Es(R);if(b.status===402){ce({message:typeof b.message=="string"?b.message:a("upgradeWall.body","Du har brukt de gratis forsøkene dine. Kjøp tilgang for å trene på hele katalogen.")}),v&&await l(v,{status:"abandoned"}).catch(()=>{});return}console.error("[ScenarioPlayer] Error starting conversation:",R),ze(v),J([]),V("intro"),fe.error(a("scenarioPlayer.startFailed","Vi fikk ikke startet samtalen. Prøv igjen om et øyeblikk."))}finally{ee(!1)}},[t,yt,ze,A,Le,l,js,p.language,Nt,T,ge,a]),bs=async()=>
48{if(!Z.trim()||B)return;const c={role:"user",content:Z.trim(),timestamp:new Date().toISOString()},v=[...W,c];J(v),be(""),ee(!0);try{const{data:k,error:S}=await G.functions.invoke("scenario-chat",{body:{scenario_id:t.id,system_prompt:t.ai_system_prompt,character_name:t.ai_character_name,character_role:t.ai_character_role,context:t.context,messages:v,is_initial:!1,attempt_id:de.current??A,language:p.language,leader_profile:Le,previous_attempt:Nt,user_provided_context:T.trim()||null,difficulty_modifier:ge}});if(S)throw S;const R={role:"assistant",content:k.message||a("scenarioPlayer.aiFallbackMessage","Jeg forstår. Kan du si mer om det?"),timestamp:new Date().toISOString()},b=[...v,R];J(b),A&&await l(A,{conversation_history:b})}catch(k){const S=await Es(k);if(S.status===402){ce({message:typeof S.message=="string"?S.message:a("upgradeWall.body","Du har brukt de gratis forsøkene dine. Kjøp tilgang for å trene på hele katalogen.")});return}console.error("[ScenarioPlayer] Error sending message:",k),fe.error(a("scenarios.couldNotSendMessage"))}finally{ee(!1)}},yr=async()=>{ee(!0),x(!0);try{const c={scenario_id:t.id,scenario_title:t.title,objectives:t.objectives,conversation_history:W,attempt_id:A,attempt_number:f,language:p.language};h&&(c.previous_feedback=h),g&&(c.previous_conversation=g);const{data:v,error:k}=await G.functions.invoke("scenario-feedback",{body:c});if(k)throw k;const S=v.feedback||{summary:a("scenarioPlayer.feedbackFallback.summary","Du har fullført scenarioet."),strengths:[a("scenarioPlayer.feedbackFallback.strength","Du deltok aktivt i samtalen")],improvements:[a("scenarioPlayer.feedbackFallback.improvement","Fortsett å øve på lignende situasjoner")],suggestions:[a("scenarios.tryOpenQuestions")]};v.comparison&&H(v.comparison),pe(S),V("reflection")}catch(c){console.error("[ScenarioPlayer] Error getting feedback:",c),pe({summary:a("scenarioPlayer.feedbackFallbackAlt.summary","Du har fullført samtalen. Godt jobbet!"),strengths:[a("scenarioPlayer.feedbackFallbackAlt.strength","Du gjennomførte samtalen")],improvements:[a("scenarioPlayer.feedbackFallbackAlt.improvement","Fortsett å øve")],suggestions:[a("scenarioPlayer.feedbackFallbackAlt.suggestion","Prøv flere samtaler for å utvikle deg videre")]}),V("reflection")}finally{ee(!1),x(!1)}},Ht=async()=>{ee(!0);try{const c=_==="voice-conversation"||E.messages.length>0?E.messages:W,v=Zn(c),k={status:v?"completed":"abandoned",user_reflection:te};C&&(k.ai_feedback=C),A&&await l(A,k);try{const{data:{user:S}}=await G.auth.getUser();S&&A&&v&&(await G.rpc("record_journey_activity",{p_user_id:S.id,p_activity_type:"scenario_completion",p_activity_reference_id:A,p_points:5}),console.log("✅ Journey activity recorded for scenario completion"))}catch(S){console.warn("Could not record journey activity for scenario:",S)}V("summary")}catch(c){console.error("[ScenarioPlayer] Error completing scenario:",c),fe.error(a("scenarios.couldNotSaveResult"))}finally{ee(!1)}},ks=()=>{const c=Math.floor((Date.now()-ne)/1e3/60);return c<1?"< 1 min":`${c} min`},br=async()=>{nt(!0),Ke.current=!1;const{data:c}=await ts(t.id,!1,de.current??A);if(c&&c.allowed===!1){ce({message:a("upgradeWall.body","Du har brukt de gratis forsøkene dine. Kjøp tilgang for å trene på hele katalogen.")}),nt(!1);return}const v=await yt();try{console.log("🎯 [ScenarioPlayer] Starting voice conversation...");const k=T.trim(),S={};if(k&&(S.user_provided_context=k.slice(0,500)),ge!==He.usual&&(S.difficulty_modifier=ge),Object.keys(S).length>0&&v){const{error:b}=await G.from("scenario_attempts").update(S).eq("id",v);b&&console.error("[ScenarioPlayer] attempt extras update failed:",b,S)}console.log("🔊 [ScenarioPlayer] Warming up AudioContext...");const R=await Ua({workletModules:["/worklets/pre-roll-gate.js"],silenceSeconds:2});if(console.log("✅ [ScenarioPlayer] AudioContext warmed up, state:",R.state),Wa(150),Mt){V("voice-conversation"),await new Promise(b=>requestAnimationFrame(()=>b(null)));try{await ct.startConversation()}catch(b){if(b instanceof Fe&&b.code==="microphone")throw b;console.warn("[ScenarioPlayer] avatar unavailable, continuing with voice:",b),jr(!0),fe.info(b instanceof Error&&b.message?b.message:a("scenarioAvatar.fallback.notice","Videoavataren er utilgjengelig akkurat nå. Samtalen fortsetter med stemme.")),await ps.startConversation()}if(Ke.current){await E.abortConversation().catch(()=>{}),dt();return}R.state==="suspended"&&await R.resume()}else{if(await E.startConversation(),Ke.current){await E.abortConversation().catch(()=>{}),dt();return}console.log("✅ [ScenarioPlayer] Voice connection established"),await new Promise(b=>setTimeout(b,750)),R.state==="suspended"&&await R.resume(),console.log("✅ [ScenarioPlayer] Audio stabilized, now changing phase"),V("voice-conversation")}}catch(k){if(console.error("❌ [ScenarioPlayer] Failed to start voice:",k),dt(),Ke.current)return;Mt&&V("intro"),ze(v),k instanceof Error&&k.message==="scenario_not_available"?ce({message:a("upgradeWall.body","Du har brukt de gratis forsøkene dine. Kjøp tilgang for å trene på hele katalogen.")}):fe.error(k instanceof Error&&k.message?k.message:a("scenarios.couldNotStartVoice"))}finally{nt(!1)}},kr=async()=>{ee(!0),dt();const c=de.current??A;try{await E.abortConversation()}catch(v){console.warn("[ScenarioPlayer] Abort failed, leaving anyway:",v)}finally{Zt(c),ee(!1),m()}},Ns=async()=>
48{if(Ke.current=!0,nt(!1),dt(),_==="voice-conversation")try{await E.abortConversation()}catch(c){console.warn("[ScenarioPlayer] could not end voice before switching to text:",c)}await ys()},ws=async()=>{ee(!0),x(!0),dt();try{const c=E.messages.map(b=>({role:b.role,content:b.content,timestamp:b.timestamp.toISOString()}));if(console.log("📝 [ScenarioPlayer] Captured voice messages before ending:",c.length),J(c),await E.endConversation(),c.length<2){console.warn("[ScenarioPlayer] Not enough messages for feedback, using fallback"),pe({summary:a("scenarios.conversationTooShort"),strengths:[a("scenarios.youStartedConversation")],improvements:[a("scenarios.tryLongerConversation")],suggestions:[a("scenarios.talkMoreForFeedback")]}),V("reflection");return}if(!Vt(c)){console.warn("[ScenarioPlayer] No leader turns in voice transcript, not grading"),pe({summary:a("scenarios.noLeaderTurnsCaptured"),strengths:[a("scenarios.youStartedConversation")],improvements:[a("scenarios.checkMicrophoneOn")],suggestions:[a("scenarios.retryOrTypeInstead")]}),V("reflection");return}A&&await l(A,{conversation_history:c});const v={scenario_id:t.id,scenario_title:t.title,objectives:t.objectives,conversation_history:c,attempt_id:A,attempt_number:f,language:p.language};h&&(v.previous_feedback=h),g&&(v.previous_conversation=g);const{data:k,error:S}=await G.functions.invoke("scenario-feedback",{body:v});if(S)throw S;const R=k.feedback||{summary:a("scenarioPlayer.feedbackFallback.summary","Du har fullført scenarioet."),strengths:[a("scenarioPlayer.feedbackFallback.strength","Du deltok aktivt i samtalen")],improvements:[a("scenarioPlayer.feedbackFallback.improvement","Fortsett å øve på lignende situasjoner")],suggestions:[a("scenarios.tryOpenQuestions")]};k.comparison&&H(k.comparison),pe(R),V("reflection")}catch(c){console.error("[ScenarioPlayer] Error ending voice conversation:",c),pe({summary:a("scenarioPlayer.feedbackFallbackVoice.summary","Du har fullført scenarioet. Godt jobbet!"),strengths:[a("scenarioPlayer.feedbackFallbackAlt.strength","Du gjennomførte samtalen")],improvements:[a("scenarioPlayer.feedbackFallbackAlt.improvement","Fortsett å øve")],suggestions:[a("scenarioPlayer.feedbackFallbackVoice.suggestion","Prøv flere scenarier for å utvikle deg videre")]}),V("reflection")}finally{ee(!1),x(!1)}},_s=i.useRef({phase:_,attemptId:null,talked:!1});_s.current={phase:_,attemptId:de.current??A,talked:Vt(W)||Vt(E.messages)},i.useEffect(()=>{const c=()=>{const{phase:v,attemptId:k,talked:S}=_s.current;(v==="conversation"||v==="voice-conversation")&&!S&&Zt(k)};return window.addEventListener("pagehide",c),()=>{window.removeEventListener("pagehide",c),c()}},[]);const Nr=()=>{let c=null,v=null,k=!1;
48if(t.conversation_type_id){const b=w(t.conversation_type_id),U=y(t.conversation_type_id);(b||U)&&!u(t.conversation_type_id)&&(b?v=b:U&&(c=U),k=!0)}if(!c&&!v&&!t.conversation_type_id&&(t.intro_video_storage_path?v=t.intro_video_storage_path:t.intro_video_url&&(c=t.intro_video_url)),!c&&!v)return V("intro"),null;const S=async b=>{b&&k&&t.conversation_type_id&&await d(t.conversation_type_id),V("intro")},R=()=>{V("intro")};return e.jsx(ii,{videoUrl:c,storagePath:v,scenarioTitle:t.title,onContinue:S,onSkip:R})},wr=()=>e.jsxs("div",{className:"flex flex-col items-center px-4 py-6",children:[e.jsxs("div",{className:"grid w-full max-w-6xl gap-4 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)] lg:items-start lg:gap-8",children:[e.jsxs("div",{className:"space-y-4",children:[jt&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 px-4 py-3",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a("firstRun.welcomeTitle","Velkommen. Dette er din første samtale.")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a("firstRun.welcomeBody","Les briefen under og velg om du vil snakke eller skrive. Du får tilbakemelding med en gang samtalen er over.")}),!Tt&&e.jsx("button",{type:"button",onClick:()=>ae("/onboarding?resume=1"),className:"mt-2 text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground",children:a("firstRun.preferMapping","Jeg vil heller kartlegge behovet mitt først")})]}),Tr(),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Y,{variant:"outline",children:t.category?Ys(t.category,Ue(p.language)):"Scenario"}),t.code&&e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.code})]}),e.jsx("h1",{className:"text-xl font-bold mb-1",children:t.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.description})]}),e.jsx(se,{children:e.jsxs(re,{className:"pt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium mb-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-primary-light"}),a("scenarioPlayer.intro.situationTitle","Situasjonsbeskrivelse")]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.context}),e.jsxs("p",{className:"mt-2 text-sm",children:[e.jsx("span",{className:"font-medium",children:a("scenarioPlayer.intro.yourRoleLabel","Din rolle:")})," ",e.jsx("span",{className:"text-muted-foreground",children:a("scenarioPlayer.intro.yourRoleBody",{defaultValue:"Du er lederen i denne samtalen. Det er du som åpner, og du som styrer den videre. {{name}} svarer på det du gjør.",name:t.ai_character_name})})]}),e.jsxs("div",{className:"mt-3 p-2 bg-muted rounded-lg flex items-center gap-2",children:[e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"sm",fallback:e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-primary-light to-primary flex items-center justify-center text-white text-sm font-medium",children:t.ai_character_name.charAt(0)})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t.ai_character_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.ai_character_role})]})]})]}),e.jsx(ga,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium mb-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-green-500"}),a("scenarioPlayer.intro.objectivesTitle","Læringsmål")]}),e.jsx("ul",{className:"space-y-1",children:t.objectives.map((c,v)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(me,{className:"w-3 h-3 text-green-500 mt-0.5 shrink-0"}),e.jsx("span",{children:c})]},v))})]})]})}),t.conversation_type_id&&(()=>
48{const c=z(t.conversation_type_id);return c?e.jsx(ci,{instructions:c}):null})()]}),e.jsxs("div",{className:"space-y-4 lg:sticky lg:top-4",children:[e.jsx(Wn,{}),kt&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-4 py-3",children:[e.jsx("p",{className:"mb-1 text-sm font-medium",children:a("scenarioPlayer.temperament.label",{defaultValue:"Hvordan møter {{name}} deg i dag?",name:t.ai_character_name})}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:a("scenarioPlayer.temperament.hint","Endrer hvor lukket motparten er når samtalen begynner. Øktene holdes fra hverandre i historikken din.")}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",role:"radiogroup",children:[{value:He.calm,label:a("scenarioPlayer.temperament.calm","Rolig dag"),hint:a("scenarioPlayer.temperament.calmHint","Mer åpen fra start")},{value:He.usual,label:a("scenarioPlayer.temperament.usual","Som vanlig"),hint:a("scenarioPlayer.temperament.usualHint","Scenarioets normale nivå")},{value:He.hard,label:a("scenarioPlayer.temperament.hard","Tung dag"),hint:a("scenarioPlayer.temperament.hardHint","Mer lukket og avvisende")}].map(c=>e.jsxs("button",{type:"button",role:"radio","aria-checked":lt===c.value,onClick:()=>pr(c.value),className:F("rounded-md border px-3 py-2 text-left transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",lt===c.value?"border-primary bg-background shadow-sm":"border-transparent bg-background/50 hover:bg-background"),children:[e.jsx("span",{className:"block text-sm font-medium",children:c.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:c.hint})]},c.value))})]}),e.jsxs(Ye,{open:Ze,onOpenChange:Pt,children:[e.jsx(Je,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 rounded-lg border bg-muted/30 px-4 py-3 text-left text-sm font-medium transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-primary-light","aria-hidden":"true"}),t.ai_character_name?a("scenarioPlayer.userContext.labelNamed",{defaultValue:"Legg til kontekst om {{name}} (valgfritt)",name:t.ai_character_name}):a("scenarioPlayer.userContext.label","Legg til kontekst (valgfritt)")]}),e.jsx(Oe,{className:F("w-4 h-4 shrink-0 text-muted-foreground transition-transform",Ze&&"rotate-180"),"aria-hidden":"true"})]})}),e.jsx(Qe,{children:e.jsxs("div",{className:"space-y-2 rounded-b-lg border border-t-0 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a("scenarioPlayer.userContext.hint","Tidligere atferd, historikk eller hva som er særlig krevende. Gjør samtalen mer realistisk.")}),e.jsx(gt,{value:T,onChange:c=>D(c.target.value.slice(0,ot)),placeholder:a("scenarioPlayer.userContext.placeholder",'F.eks. "Per har en utfordrende familiesituasjon og har vært tilbakeholden i tidligere samtaler."'),rows:3,className:"resize-none",maxLength:ot}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[T.length,"/",ot]})]})})]}),e.jsx(qn,{open:it,hasChecklist:!!N,onAccept:()=>bt(!0),onDecline:m,...N?.frameworkRef?{frameworkRef:N.frameworkRef}:{}}),N&&e.jsx("div",{className:"mb-4",children:e.jsx(zn,{requirements:N})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ot,{className:"w-3 h-3","aria-hidden":"true"}),"~",t.estimated_minutes," min"]}),le&&pt&&e.jsx("span",{children:a("scenarioPlayer.intro.freeTierCount",{defaultValue:"Samtale {{current}} av {{limit}} i gratisversjonen",current:Math.min(qe+1,vt),limit:vt})})]}),e.jsxs("div",{className:F("grid gap-3",Ae&&"sm:grid-cols-2"),children:[Ae&&e.jsxs(L,{onClick:()=>void br(),disabled:B||it,size:"lg",className:"h-auto flex-col items-start gap-1 px-4 py-3 bg-primary-dark hover:bg-primary-dark/90 text-white text-left whitespace-normal sm:order-2",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Jt,{className:"w-4 h-4 shrink-0","aria-hidden":"true"}),a("scenarioPlayer.intro.voiceWithName","Snakk med {{name}}",{name:t.ai_character_name})]}),e.jsx("span",{className:"text-xs font-normal text-white/75",children:a("scenarioPlayer.intro.voiceNeedsMic","Krever mikrofon — du snakker høyt")})]}),e.jsxs(L,{onClick:ys,disabled:B||it,variant:"outline",size:"lg",className:"h-auto flex-col items-start gap-1 px-4 py-3 text-left whitespace-normal sm:order-1",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[B?e.jsx(ye,{className:"w-4 h-4 shrink-0 animate-spin","aria-hidden":"true"}):e.jsx(Ce,{className:"w-4 h-4 shrink-0","aria-hidden":"true"}),a("scenarioPlayer.intro.chat","Skriv i stedet")]}),e.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:a("scenarioPlayer.intro.chatHelp","Fungerer overalt, uten lyd")})]})]})]})]})]}),It&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-lg",children:e.jsxs("div",{className:"flex flex-col items-center gap-4 text-center p-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Jt,{className:"w-8 h-8 text-primary animate-pulse"})}),e.jsx(ye,{className:"w-6 h-6 text-primary animate-spin absolute -top-1 -right-1"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:a("scenarios.connectingConversation")}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:a("scenarioPlayer.intro.preparingMicrophone","Gjør klar mikrofon og lyd")})]}),e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>void Ns(),children:[e.jsx(Ce,{className:"w-4 h-4 mr-2","aria-hidden":"true"}),a("scenarioPlayer.intro.chat","Skriv i stedet")]})]})})]}),_r=()=>e.jsxs("div",{className:"flex flex-col h-full min-h-0 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"md",fallback:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-primary-light to-primary flex items-center justify-center text-white font-medium",children:t.ai_character_name.charAt(0)})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:t.ai_character_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.ai_character_role})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:[e.jsx(Ot,{className:"w-3 h-3 mr-1"}),ks()]}),e.jsx(L,{variant:"outline",size:"sm",onClick:yr,disabled:B||W.length<2,children:a("scenarioPlayer.endConversation","Avslutt samtale")})]})]}),t.conversation_type_id&&(()=>
48{const c=z(t.conversation_type_id);return c?e.jsx(Ws,{instructions:c}):null})(),h?.next_step?.goal&&e.jsx(Os,{goal:h.next_step.goal}),e.jsx(Us,{objectives:t.objectives??[]}),e.jsx(As,{className:"flex-1 p-4",children:e.jsxs("div",{className:"space-y-4",children:[W.map((c,v)=>e.jsxs("div",{className:F("flex gap-3",c.role==="user"&&"flex-row-reverse"),children:[c.role==="user"?e.jsx($t,{size:"sm"}):e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"sm",fallback:e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-primary-light to-primary text-white",children:e.jsx(Rt,{className:"w-4 h-4"})}),className:"shrink-0"}),e.jsx("div",{className:F("max-w-[80%] p-3 rounded-lg",c.role==="user"?"bg-primary-light text-primary-foreground":"bg-muted"),children:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:c.content})})]},v)),B&&e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"sm",fallback:e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-primary-light to-primary flex items-center justify-center text-white",children:e.jsx(Rt,{className:"w-4 h-4"})}),className:"shrink-0"}),e.jsx("div",{className:"bg-muted p-3 rounded-lg",children:e.jsx(ye,{className:"w-4 h-4 animate-spin"})})]}),e.jsx("div",{ref:Ft})]})}),e.jsxs("div",{className:"p-4 border-t",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(gt,{ref:cs,value:Z,onChange:c=>be(c.target.value),onKeyDown:c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),bs())},placeholder:a("scenarioPlayer.input.placeholder","Skriv din respons..."),className:"min-h-[60
48px] resize-none",disabled:B}),e.jsx(L,{"aria-label":a("a11y.send","Send"),onClick:bs,disabled:!Z.trim()||B,className:"bg-primary-light hover:bg-primary-hover",children:e.jsx(tn,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:a("scenarioPlayer.input.enterHint","Trykk Enter for å sende, Shift+Enter for ny linje")})]})]}),Sr=()=>e.jsxs("div",{className:"flex flex-col h-full min-h-0 max-w-3xl mx-auto relative",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"md",fallback:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-primary-light to-primary flex items-center justify-center text-white font-medium",children:t.ai_character_name.charAt(0)})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:t.ai_character_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.ai_character_role})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:[e.jsx(Ot,{className:"w-3 h-3 mr-1"}),ks()]}),e.jsx(L,{variant:"outline",size:"sm",onClick:ws,disabled:B||E.messages.length<2,children:a("scenarioPlayer.voice.endConversation","Avslutt samtale")})]})]}),t.conversation_type_id&&(()=>
48{const c=z(t.conversation_type_id);return c?e.jsx(Ws,{instructions:c}):null})(),h?.next_step?.goal&&e.jsx(Os,{goal:h.next_step.goal}),e.jsx(Us,{objectives:t.objectives??[]}),Mt&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs("div",{className:"relative aspect-video w-full overflow-hidden rounded-lg bg-muted",children:[e.jsx("video",{id:as,className:"h-full w-full object-cover",autoPlay:!0,playsInline:!0,"aria-label":a("scenarioAvatar.videoLabel","Videoavatar av {{name}}",{name:t.ai_character_name})}),!E.isConnected&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[E.isConnecting&&e.jsx(ye,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),E.isConnecting?a("scenarioAvatar.connecting","Kobler til avataren…"):a("scenarioAvatar.idle","Avataren er klar")]})}),ct.secondsRemaining!==null&&ct.secondsRemaining<=60&&E.isConnected&&e.jsxs("div",{className:"absolute right-2 top-2 rounded-full bg-background/85 px-2 py-1 text-xs font-medium tabular-nums",role:"status",children:[Math.floor(ct.secondsRemaining/60),":",String(ct.secondsRemaining%60).padStart(2,"0")]})]})}),e.jsx(As,{className:"flex-1 p-4",children:e.jsxs("div",{className:"space-y-4",children:[E.messages.length===0&&e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx("p",{className:"text-sm font-medium",children:a("scenarios.youStartConversation")}),e.jsx("p",{className:"text-xs mt-1",children:a("scenarios.sayHelloToStart",{name:t.ai_character_name})})]}),E.messages.map((c,v)=>e.jsxs("div",{className:F("flex gap-3",c.role==="user"&&"flex-row-reverse"),children:[c.role==="user"?e.jsx($t,{size:"sm"}):e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"sm",fallback:e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-primary-light to-primary text-white",children:e.jsx(Rt,{className:"w-4 h-4"})}),className:"shrink-0"}),e.jsx("div",{className:F("max-w-[80%] p-3 rounded-lg",c.role==="user"?"bg-primary-light text-primary-foreground":"bg-muted"),children:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:c.content})})]},v)),E.currentTranscript&&e.jsxs("div",{className:"flex gap-3 flex-row-reverse",children:[e.jsx($t,{size:"sm"}),e.jsx("div",{className:"max-w-[80%] p-3 rounded-lg bg-primary-light/50 text-primary-foreground",children:e.jsxs("p",{className:"text-sm italic",children:[E.currentTranscript,"..."]})})]}),E.isSpeaking&&e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ie,{src:t.ai_character_avatar_url,alt:t.ai_character_name,size:"sm",fallback:e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-primary-light to-primary flex items-center justify-center text-white",children:e.jsx(Rt,{className:"w-4 h-4"})}),className:"shrink-0"}),e.jsxs("div",{className:"bg-muted p-3 rounded-lg flex items-center gap-2",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-primary-light rounded-full animate-pulse"}),e.jsx("span",{className:"w-2 h-2 bg-primary-light rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),e.jsx("span",{className:"w-2 h-2 bg-primary-light rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a("scenarioPlayer.voice.speaking","Snakker...")})]})]}),e.jsx("div",{ref:Ft})]})}),e.jsxs("div",{className:"p-4 border-t",children:[e.jsxs("div",{className:"flex justify-center gap-4",children:[e.jsx(L,{onClick:E.toggleMic,variant:E.isMicOn?"default":"outline",size:"lg",className:F("w-16 h-16 rounded-full",E.isMicOn&&"bg-primary-light hover:bg-primary-hover"),children:E.isMicOn?e.jsx(Jt,{className:"w-6 h-6"}):e.jsx(sn,{className:"w-6 h-6"})}),e.jsx(L,{onClick:ws,variant:"destructive",size:"lg",className:"w-16 h-16 rounded-full",disabled:B||E.isEnding||E.messages.length<2,title:E.messages.length<2?a("scenarioPlayer.voice.endNeedsMore","Si noen setninger først – da har vi noe å gi tilbakemelding på. Vil du ut nå, bruk «Avbryt samtalen» under."):a("scenarioPlayer.voice.endAndGetFeedback","Avslutt og få tilbakemelding"),"aria-label":a("scenarioPlayer.voice.endAndGetFeedback","Avslutt og få tilbakemelding"),children:e.jsx(rn,{className:"w-6 h-6 rotate-[135deg]","aria-hidden":"true"})})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2 mt-3",children:[!Vt(E.messages)&&e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>void Ns(),disabled:B,children:[e.jsx(Ce,{className:"w-4 h-4 mr-2","aria-hidden":"true"}),a("scenarioPlayer.intro.chat","Skriv i stedet")]}),e.jsx(L,{variant:"ghost",size:"sm",onClick:kr,disabled:B,className:"text-muted-foreground hover:text-foreground",children:a("scenarioPlayer.voice.abort","Avbryt uten vurdering")})]}),e.jsx("div",{className:"text-center mt-3",children:E.connectionError?e.jsx("p",{className:"text-sm text-destructive",children:E.connectionError}):E.isConnecting?e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center justify-center gap-2",children:[e.jsx(ye,{className:"w-3 h-3 animate-spin"}),a("scenarioPlayer.voice.connecting","Kobler til...")]}):E.isConnected?e.jsx("p",{className:"text-sm text-muted-foreground",children:E.isMicOn?a("scenarioPlayer.voice.listeningToYou","Lytt til deg..."):a("scenarioPlayer.voice.microphoneMuted","Mikrofon dempet")}):null})]})]}),Ss=async()=>{await Ht(),C&&j&&j(C,W)},Cr=async()=>{await Ht(),m()},Pr=c=>{const v=Object.keys(c),k=Ue(p.language),S=b=>b>=80?"bg-green-500":b>=60?"bg-blue-500":b>=40?"bg-amber-500":"bg-red-500",R=v.length===4?a("scenarioPlayer.feedback.fourDimensionsTitle","Scoring på fire dimensjoner"):a("scenarioPlayer.feedback.dimensionsTitle","Scoring per dimensjon");return e.jsxs(se,{children:[e.jsx(xe,{children:e.jsxs(he,{className:"text-lg flex items-center gap-2",children:[e.jsx(rs,{className:"w-5 h-5 text-primary-light"}),R]})}),e.jsx(re,{className:"space-y-4",children:v.map(b=>{const U=c[b];
48if(!U)return null;const{score:Q,reasoning:je}=U;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:Yr(b,k)}),e.jsxs("span",{className:"text-sm font-semibold tabular-nums",children:[Q,"/100"]})]}),e.jsx("div",{className:"h-2 w-full rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:F("h-full rounded-full transition-all",S(Q)),style:{width:`${Q}%`}})}),je&&e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:je})]},b)})})]})},Tr=()=>h?e.jsx(Ye,{children:e.jsxs(se,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Je,{className:"w-full",children:e.jsx(xe,{className:"pb-2",children:e.jsxs(he,{className:"text-sm flex items-center gap-2 text-primary",children:[e.jsx(Ct,{className:"w-4 h-4"}),a("scenarioPlayer.feedback.previousFeedbackTitle","Tilbakemelding fra forrige forsøk"),e.jsx(Oe,{className:"w-4 h-4 ml-auto"})]})})}),e.jsx(Qe,{children:e.jsxs(re,{className:"pt-0 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:h.summary}),h.improvements.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-amber-700 dark:text-amber-400 mb-1",children:a("scenarioPlayer.feedback.focusAreas","Fokusområder:")}),e.jsx("ul",{className:"space-y-1",children:h.improvements.map((c,v)=>e.jsxs("li",{className:"text-xs text-muted-foreground flex items-start gap-1",children:[e.jsx("span",{className:"text-amber-500",children:"•"})," ",c]},v))})]})]})})]})}):null,Ar=()=>{if(!O||f<2)return null;const{improved:c,new_strengths:v,persisting:k,overall:S,concrete_examples:R,tip_for_next:b}=O,U=c.length>0||v.length>0;return e.jsxs(se,{className:"border-primary/20",children:[e.jsx(xe,{className:"pb-3",children:e.jsxs(he,{className:"text-lg flex items-center gap-2",children:[e.jsx(rs,{className:"w-5 h-5 text-primary"}),a("scenarioPlayer.comparison.title","Utvikling fra forsøk {{prev}} til {{curr}}",{prev:f-1,curr:f})]})}),e.jsxs(re,{className:"space-y-4",children:[S&&e.jsx("p",{className:"text-sm text-foreground font-medium",children:S}),!U&&!S&&e.jsx("p",{className:"text-sm text-muted-foreground",children:a("scenarioPlayer.comparison.noChanges","Tilbakemeldingene er ganske like forrige forsøk. Prøv å fokusere på forbedringsområdene og test nye tilnærminger.")}),c.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-green-700 dark:text-green-400 mb-2 text-sm flex items-center gap-1",children:[e.jsx(me,{className:"w-4 h-4"}),a("scenarioPlayer.comparison.improvedSinceLast","Forbedret siden sist")]}),e.jsx("ul",{className:"space-y-1",children:c.map((Q,je)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-green-500",children:"+"})," ",Q]},je))})]}),v.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-blue-700 dark:text-blue-400 mb-2 text-sm flex items-center gap-1",children:[e.jsx(Qt,{className:"w-4 h-4"}),a("scenarioPlayer.comparison.newStrengths","Nye styrker")]}),e.jsx("ul",{className:"space-y-1",children:v.map((Q,je)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-blue-500",children:"+"})," ",Q]},je))})]}),k.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-amber-700 dark:text-amber-400 mb-2 text-sm flex items-center gap-1",children:[e.jsx(ft,{className:"w-4 h-4"}),a("scenarioPlayer.comparison.stillWorkOn","Fortsatt å jobbe med")]}),e.jsx("ul",{className:"space-y-1",children:k.map((Q,je)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-amber-500",children:"~"})," ",Q]},je))})]}),R.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("p",{className:"font-medium text-foreground mb-2 text-sm flex items-center gap-1",children:[e.jsx(Ce,{className:"w-4 h-4"}),a("scenarioPlayer.comparison.concreteExamples","Konkrete eksempler fra samtalene")]}),e.jsx("ul",{className:"space-y-2",children:R.map((Q,je)=>e.jsx("li",{className:"text-sm text-muted-foreground bg-muted/50 rounded-lg p-3 italic",children:Q},je))})]}),b&&e.jsx("div",{className:"border-t pt-4",children:e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsx(Xe,{className:"w-5 h-5 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm text-foreground mb-1",children:a("scenarios.tipForNextAttempt")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b})]})]})})]})]})},Lr=()=>{const c=C?.strengths?.slice(0,2)??[],v=C?.improvements?.slice(0,1)??[],k=C?.strengths?.slice(2)??[],S=C?.improvements?.slice(1)??[],R=k.length>0||S.length>0||(C?.suggestions?.length??0)>0||(C?.criteria?.length??0)>0||!!C?.conversation_arc||!!C?.dimensions||!!O,b=X&&A&&!A.startsWith("attempt-")?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 border-t pt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a("scenarioPlayer.reflection.agreementAsk","Traff denne vurderingen?")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{type:"button",variant:Ne===!0?"default":"outline",size:"sm","aria-pressed":Ne===!0,onClick:()=>vs(!0),className:"gap-1.5",children:[e.jsx(os,{className:"w-4 h-4","aria-hidden":"true"}),a("scenarioPlayer.reflection.agreementYes","Ja")]}),e.jsxs(L,{type:"button",variant:Ne===!1?"default":"outline",size:"sm","aria-pressed":Ne===!1,onClick:()=>vs(!1),className:"gap-1.5",children:[e.jsx(sr,{className:"w-4 h-4","aria-hidden":"true"}),a("scenarioPlayer.reflection.agreementNo","Nei")]})]}),Ne!==null&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a("scenarioPlayer.reflection.agreementThanks","Takk — det hjelper oss å kalibrere.")})]}):null;
48return e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(me,{className:"w-12 h-12 text-green-500 mx-auto mb-2"}),e.jsx("h2",{className:"text-xl font-bold",children:a("scenarioPlayer.reflection.conversationCompleted","Samtale fullført!")}),e.jsx("p",{className:"text-muted-foreground",children:f===1?a("scenarioPlayer.reflection.firstAttemptSubtitle","Se tilbakemeldingen og velg veien videre"):a("scenarioPlayer.reflection.laterAttemptSubtitle","La oss reflektere over hvordan det gikk")}),X&&e.jsxs("div",{className:"mt-5 flex flex-col items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-baseline gap-2 tabular-nums",children:[e.jsx("span",{className:"text-4xl font-semibold text-foreground",children:X.current}),e.jsx("span",{className:"text-lg text-muted-foreground",children:"/ 100"})]}),X.previous!==null&&(()=>{if(!X.comparable)return e.jsx("p",{className:"text-sm text-muted-foreground",children:a("scenarioPlayer.reflection.scoreNotComparable",{defaultValue:"{{prev}} → {{curr}}. Forrige forsøk var på en annen innstilling, så tallene kan ikke sammenlignes direkte.",prev:X.previous,curr:X.current})});const U=X.current-X.previous;return Da(U)?U===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:a("scenarioPlayer.reflection.scoreSame",{defaultValue:"Samme som forrige forsøk ({{prev}}).",prev:X.previous})}):e.jsx("p",{className:F("text-sm font-medium",U>0?"text-green-600":"text-muted-foreground"),children:U>0?a("scenarioPlayer.reflection.scoreUp",{defaultValue:"{{prev}} → {{curr}} · {{delta}} poeng bedre enn sist",prev:X.previous,curr:X.current,delta:U}):a("scenarioPlayer.reflection.scoreDown",{defaultValue:"{{prev}} → {{curr}} · {{delta}} poeng fra sist",prev:X.previous,curr:X.current,delta:U})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:a("scenarioPlayer.reflection.scoreUnchanged",{defaultValue:"{{prev}} → {{curr}}. Om lag på samme nivå som sist.",prev:X.previous,curr:X.current})})})()]})]}),e.jsxs("div",{className:F("grid gap-6 lg:items-start",C?.next_step&&"lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]"),children:[C&&e.jsx(se,{children:e.jsxs(re,{className:"pt-6 space-y-4",children:[e.jsx("p",{className:"text-base leading-relaxed",children:C.summary}),c.length>0&&e.jsx("ul",{className:"space-y-1",children:c.map((U,Q)=>e.jsxs("li",{className:"flex items-start gap-2 text-base leading-relaxed",children:[e.jsx(me,{className:"w-5 h-5 text-green-500 mt-0.5 flex-shrink-0"}),U]},Q))}),v.length>0&&e.jsx("ul",{className:"space-y-1",children:v.map((U,Q)=>e.jsxs("li",{className:"flex items-start gap-2 text-base leading-relaxed",children:[e.jsx(ft,{className:"w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0","aria-hidden":"true"}),U]},Q))}),b]})}),!C&&b,C?.next_step&&e.jsx(ba,{goal:C.next_step.goal,...C.next_step.why?{why:C.next_step.why}:{},onRetry:Ss,retryDisabled:B,attemptId:A,scenarioTitle:t.title,stacked:!0})]}),C?.legal_review&&e.jsx(Bn,{legalReview:C.legal_review}),R&&e.jsxs(Ye,{className:"rounded-lg border bg-muted/30",children:[e.jsxs(Je,{className:"group flex w-full items-center justify-between gap-2 px-4 py-3 text-sm font-medium hover:bg-muted/50 transition-colors",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground"}),a("scenarioPlayer.reflection.viewFullAnalysis","Se full analyse")]}),e.jsx(Oe,{className:"h-4 w-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180"})]}),e.jsxs(Qe,{className:"space-y-4 px-4 pb-4 pt-1",children:[(k.length>0||S.length>0||(C?.suggestions?.length??0)>0)&&e.jsxs("div",{className:"space-y-3 pt-2",children:[k.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-green-700 dark:text-green-400 mb-1",children:a("scenarioPlayer.feedback.strengths","Styrker:")}),e.jsx("ul",{className:"space-y-1",children:k.map((U,Q)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm leading-relaxed",children:[e.jsx(me,{className:"w-4 h-4 text-green-500 mt-0.5 flex-shrink-0"}),U]},Q))})]}),S.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-700 dark:text-amber-400 mb-1",children:a("scenarioPlayer.feedback.improvements","Forbedringsområder:")}),e.jsx("ul",{className:"space-y-1",children:S.map((U,Q)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm leading-relaxed",children:[e.jsx(ft,{className:"w-4 h-4 text-amber-600 mt-0.5 flex-shrink-0","aria-hidden":"true"}),U]},Q))})]}),(C?.suggestions?.length??0)>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-blue-700 dark:text-blue-400 mb-1",children:a("scenarioPlayer.feedback.suggestions","Tips videre:")}),e.jsx("ul",{className:"space-y-1",children:C?.suggestions.map((U,Q)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm leading-relaxed",children:[e.jsx(Qt,{className:"w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0"}),U]},Q))})]})]}),e.jsxs("div",{className:F("grid gap-4 lg:items-start",C?.conversation_arc&&"lg:grid-cols-2"),children:[e.jsx(ka,{criteria:C?.criteria??[],...C?.pitfalls?{pitfalls:C.pitfalls}:{},showEmptyState:!0}),C?.conversation_arc&&e.jsx(Na,{arc:C.conversation_arc})]}),C?.dimensions&&Pr(C.dimensions),Ar()]})]}),f===1&&e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(L,{onClick:Ss,disabled:B||!j,className:"flex-1 bg-primary-light hover:bg-primary-hover",size:"lg",children:[B?e.jsx(ye,{className:"w-4 h-4 mr-2 animate-spin"}):null,a("scenarioPlayer.reflection.retryNow","Prøv igjen nå")]}),e.jsx(L,{onClick:Cr,disabled:B,variant:"outline",className:"flex-1",size:"lg",children:a("scenarioPlayer.reflection.saveAndLater","Lagre og prøv senere")})]}),f>=2&&e.jsxs(e.Fragment,{children:[e.jsxs(se,{children:[e.jsx(xe,{children:e.jsx(he,{className:"text-lg",children:a("scenarioPlayer.reflection.yourReflection","Din refleksjon")})}),e.jsxs(re,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:a("scenarioPlayer.reflection.whatDoYouTakeAway","Hva tar du med deg fra denne samtalen? (valgfritt)")}),e.jsx(gt,{value:te,onChange:U=>M(U.target.value),placeholder:a("scenarioPlayer.reflection.thoughtsPlaceholder","Skriv dine tanker og læringspunkter..."),className:"min-h-[100px]"})]})]}),e.jsxs(L,{onClick:Ht,disabled:B,className:"w-full bg-primary-light hover:bg-primary-hover",size:"lg",children:[B?e.jsx(ye,{className:"w-4 h-4 mr-2 animate-spin"}):null,a("scenarioPlayer.reflection.completeButton","Fullfør og se oppsummering")]})]}),!Ge&&e.jsx(ri,{onTakeAssessment:()=>ae("/personality-assessment")}),jt?!Tt&&e.jsx(ni,{}):qt&&e.jsx(ai,{onStartOnboarding:()=>ae("/onboarding?resume=1")})]})},Er=()=>
48e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-green-100 mx-auto mb-4 flex items-center justify-center",children:e.jsx(me,{className:"w-10 h-10 text-green-500"})}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:a("scenarioPlayer.summary.congrats","Gratulerer!")}),e.jsx("p",{className:"text-muted-foreground",children:a("scenarioPlayer.summary.completedScenario",'Du har fullført scenarioet "{{title}}"',{title:t.title})})]}),e.jsx("div",{className:"text-left",children:e.jsx(Yn,{behaviorCategoryId:t.primary_behavior_category_id})}),W.filter(c=>c.role!=="system").length>0&&e.jsxs(Ye,{className:"text-left rounded-lg border bg-muted/30",children:[e.jsxs(Je,{className:"group flex w-full items-center justify-between gap-2 px-4 py-3 text-sm font-medium hover:bg-muted/50 transition-colors",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"h-4 w-4 text-muted-foreground"}),a("scenarioPlayer.summary.viewTranscript","Vis samtalen"),e.jsxs("span",{className:"text-xs text-muted-foreground font-normal",children:["(",W.filter(c=>c.role!=="system").length,")"]})]}),e.jsx(Oe,{className:F("h-4 w-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180")})]}),e.jsx(Qe,{className:"px-4 pb-4 pt-1",children:e.jsx(wa,{messages:W,characterAvatarUrl:t.ai_character_avatar_url,characterName:t.ai_character_name})})]}),t.code&&!o&&e.jsx(Xn,{scenarioId:t.id,attemptId:A&&!A.startsWith("attempt-")?A:null}),t.code&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3 rounded-lg border bg-muted/30 px-4 py-3 text-left",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a("scenarioPlayer.summary.sharePrompt","Kjenner du noen som burde øve på dette?")}),e.jsx(Xs,{scenario:{code:t.code,title:t.title},className:"shrink-0"})]}),ue&&C&&e.jsx("div",{className:"text-left",children:e.jsx(Yt,{title:a("upgradeWall.summaryTitle","Vil du trene mer?"),message:a("upgradeWall.summaryLead","Kjøp tilgang for å ta hele katalogen — og gjøre hver samtale om igjen til den sitter.")})}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(L,{variant:"outline",onClick:m,className:"flex-1",children:a("scenarioPlayer.summary.backToLibrary","Tilbake til biblioteket")}),j&&C&&e.jsx(L,{onClick:()=>j(C),className:"flex-1 bg-primary-light hover:bg-primary-hover",children:a("scenarioPlayer.summary.retry","Prøv igjen")})]})]}),Ir=ti({phase:_,attemptId:A,isFreeTier:le,statusLoaded:!!pt,spent:At,freeScenarioId:tt,scenarioId:t.id});if(oe||Ir){const c=Math.max(0,vt-qe);return e.jsxs("div",{className:"scenario-player-shell h-full overflow-y-auto bg-background px-4 py-8",children:[st?e.jsx(Yt,{title:a("upgradeWall.lockedTitle","Gratisversjonen gjelder én samtale"),message:ke?.title?a("upgradeWall.lockedBodyNamed",{defaultValue:"Du valgte «{{title}}» som gratissamtale, og har {{count}} forsøk igjen der. Kjøp tilgang for å trene på hele katalogen.",title:ke.title,count:c}):a("upgradeWall.lockedBody",{defaultValue:"Du har {{count}} forsøk igjen på samtalen du valgte først. Kjøp tilgang for å trene på hele katalogen.",count:c})}):e.jsx(Yt,{...oe?{message:oe.message}:{}}),e.jsxs("div",{className:"mx-auto mt-4 w-full max-w-lg space-y-2",children:[st&&ke?.code&&e.jsx(L,{variant:"outline",className:"w-full",onClick:()=>ae(`/scenarios?ovelse=${ke.code}`),children:a("upgradeWall.backToLocked",{defaultValue:"Ta «{{title}}» én gang til",title:ke.title})}),e.jsx(L,{variant:"ghost",className:"w-full",onClick:m,children:a("upgradeWall.back","Tilbake til scenarioene")})]})]})}return e.jsxs("div",{className:"scenario-player-shell h-full bg-background flex flex-col min-h-0 overflow-hidden",children:[_==="video-intro"&&Nr(),e.jsxs("div",{className:F("flex-1 min-h-0 max-w-6xl mx-auto w-full px-4 py-4",_==="conversation"||_==="voice-conversation"?"overflow-hidden":"overflow-y-auto"),children:[_==="intro"&&wr(),_==="conversation"&&_r(),_==="voice-conversation"&&Sr(),_==="reflection"&&Lr(),_==="summary"&&Er()]}),e.jsx(li,{open:Kt,characterName:t.ai_character_name})]})}function Bs(t,s){try{var n=t()}catch(r){return s(r)}return n&&n.then?n.then(void 0,s):n}function mi(t,s){for(var n={};t.length;){var r=t[0],m=r.code,l=r.message,o=r.path.join(".");if(!n[o])if("unionErrors"in r){var f=r.unionErrors[0].errors[0];n[o]={message:f.message,type:f.code}}else n[o]={message:l,type:m};
48if("unionErrors"in r&&r.unionErrors.forEach(function(j){return j.errors.forEach(function(a){return t.push(a)})}),s){var h=n[o].types,g=h&&h[r.code];n[o]=dr(o,s,n,m,g?[].concat(g,r.message):r.message)}t.shift()}return n}function ui(t,s){for(var n={};t.length;){var r=t[0],m=r.code,l=r.message,o=r.path.join(".");if(!n[o])if(r.code==="invalid_union"&&r.errors.length>0){var f=r.errors[0][0];n[o]={message:f.message,type:f.code}}else n[o]={message:l,type:m};if(r.code==="invalid_union"&&r.errors.forEach(function(j){return j.forEach(function(a){return t.push(a)})}),s){var h=n[o].types,g=h&&h[r.code];n[o]=dr(o,s,n,m,g?[].concat(g,r.message):r.message)}t.shift()}return n}function gi(t,s,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(t))return function(r,m,l){try{return Promise.resolve(Bs(function(){return Promise.resolve(t[n.mode==="sync"?"parse":"parseAsync"](r,s)).then(function(o){return l.shouldUseNativeValidation&&Is({},l),{errors:{},values:n.raw?Object.assign({},r):o}})},function(o){if((function(f){return Array.isArray(f?.issues)})(o))return{values:{},errors:Fs(mi(o.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw o}))}catch(o){return Promise.reject(o)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(t))return function(r,m,l){try{return Promise.resolve(Bs(function(){return Promise.resolve((n.mode==="sync"?an:nn)(t,r,s)).then(function(o){return l.shouldUseNativeValidation&&Is({},l),{errors:{},values:n.raw?Object.assign({},r):o}})},function(o){if((function(f){return f instanceof on})(o))return{values:{},errors:Fs(ui(o.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw o}))}catch(o){return Promise.reject(o)}};throw new Error("Invalid input: not a Zod schema")}const fi=ln,xr=i.createContext({}),$e=({...t})=>e.jsx(xr.Provider,{value:{name:t.name},children:e.jsx(cn,{...t})}),Gt=()=>{const t=i.useContext(xr),s=i.useContext(hr),{getFieldState:n,formState:r}=dn(),m=n(t.name,r);if(!t)throw new Error("useFormField should be used within <FormField>");const{id:l}=s;return{id:l,name:t.name,formItemId:`${l}-form-item`,formDescriptionId:`${l}-form-item-description`,formMessageId:`${l}-form-item-message`,...m}},hr=i.createContext({}),Me=i.forwardRef(({className:t,...s},n)=>{const r=i.useId();return e.jsx(hr.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:F("space-y-2",t),...s})})});Me.displayName="FormItem";const De=i.forwardRef(({className:t,...s},n)=>{const{error:r,formItemId:m}=Gt();return e.jsx(ss,{ref:n,className:F(r&&"text-destructive",t),htmlFor:m,...s})});De.displayName="FormLabel";const Re=i.forwardRef(({...t},s)=>{const{error:n,formItemId:r,formDescriptionId:m,formMessageId:l}=Gt();return e.jsx(en,{ref:s,id:r,"aria-describedby":n?`${m} ${l}`:`${m}`,"aria-invalid":!!n,...t})});Re.displayName="FormControl";const ns=i.forwardRef(({className:t,...s},n)=>{const{formDescriptionId:r}=Gt();return e.jsx("p",{ref:n,id:r,className:F("text-sm text-muted-foreground",t),...s})});ns.displayName="FormDescription";const Ve=i.forwardRef(({className:t,children:s,...n},r)=>{const{error:m,formMessageId:l}=Gt(),o=m?String(m?.message):s;return o?e.jsx("p",{ref:r,id:l,className:F("text-sm font-medium text-destructive",t),...n,children:o}):null});Ve.displayName="FormMessage";const xi=t=>un({title:mt().min(3,t("customScenario.errors.titleMin","Tittel må være minst 3 tegn")).max(100,t("customScenario.errors.titleMax","Tittel kan maks være 100 tegn")),situation:mt().min(20,t("customScenario.errors.situationMin","Beskrivelse må være minst 20 tegn")).max(1e3,t("customScenario.errors.situationMax","Beskrivelse kan maks være 1000 tegn")),characterName:mt().min(2,t("customScenario.errors.nameMin","Navn må være minst 2 tegn")).max(50,t("customScenario.errors.nameMax","Navn kan maks være 50 tegn")),characterRole:mt().min(2,t("customScenario.errors.roleMin","Rolle må være minst 2 tegn")).max(100,t("customScenario.errors.roleMax","Rolle kan maks være 100 tegn")),characterAttitude:gn(["frustrated","skeptical","open","defensive","worried","angry","passive"]),customGoal:mt().max(200,t("
48customScenario.errors.customGoalMax","Egendefinert mål kan maks være 200 tegn")).optional(),background:mt().max(500,t("customScenario.errors.backgroundMax","Bakgrunn kan maks være 500 tegn")).optional()}),hi=["frustrated","skeptical","open","defensive","worried","angry","passive"],pi=["give_feedback","resolve_conflict","motivate","set_boundaries","handle_resistance","build_trust","delegate","difficult_message"];function vi({onSubmit:t,onCancel:s,isLoading:n}){const{t:r}=q(),m=i.useMemo(()=>xi(r),[r]),l=i.useMemo(()=>hi.map(d=>({value:d,label:r(`customScenario.attitudes.${d}.label`),description:r(`customScenario.attitudes.${d}.description`)})),[r]),o=i.useMemo(()=>pi.map(d=>({value:d,label:r(`customScenario.goals.${d}`)})),[r]),f=mn({resolver:gi(m),defaultValues:{title:"",situation:"",characterName:"",characterRole:"",characterAttitude:"skeptical",customGoal:"",background:""}}),[h,g]=i.useState([]),[j,a]=i.useState(null),p=d=>{g(y=>{const w=y.includes(d)?y.filter(z=>z!==d):[...y,d];return w.length>0&&a(null),w})},u=d=>{if(h.length===0){a(r("customScenario.errors.goalsRequired","Velg minst ett mål"));return}t({...d,customGoal:d.customGoal??"",background:d.background??"",goals:h})};return e.jsxs(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6 h-full overflow-y-auto p-3 sm:p-4 lg:p-8",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(L,{"aria-label":r("a11y.back","Tilbake"),variant:"ghost",size:"icon",onClick:s,children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(mr,{className:"h-6 w-6 text-primary"}),r("customScenario.header.title","Lag ditt eget scenario")]}),e.jsx("p",{className:"text-muted-foreground",children:r("customScenario.header.subtitle","Beskriv situasjonen du ønsker å øve på")})]})]})}),e.jsx(fi,{...f,children:e.jsxs("form",{onSubmit:f.handleSubmit(u),className:"space-y-8",children:[e.jsxs(se,{children:[e.jsxs(xe,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ce,{className:"h-5 w-5 text-primary"}),r("customScenario.situation.title","Situasjonsbeskrivelse")]}),e.jsx(wt,{children:r("customScenario.situation.description","Beskriv situasjonen du ønsker å trene på")})]}),e.jsxs(re,{className:"space-y-4",children:[e.jsx($e,{control:f.control,name:"title",render:({field:d})=>e.jsxs(Me,{children:[e.jsxs(De,{children:[r("customScenario.fields.title.label","Tittel")," *"]}),e.jsx(Re,{children:e.jsx(ut,{placeholder:r("customScenario.fields.title.placeholder","F.eks. Konflikt med teamleder"),...d})}),e.jsx(Ve,{})]})}),e.jsx($e,{control:f.control,name:"situation",render:({field:d})=>e.jsxs(Me,{children:[e.jsxs(De,{children:[r("scenarios.whatHappened")," *"]}),e.jsx(Re,{children:e.jsx(gt,{placeholder:r("customScenario.fields.situation.placeholder","Beskriv situasjonen i detalj. F.eks: En medarbeider har kommet for sent til jobb flere ganger den siste uken, og det påvirker teamets moral. Du må ta en samtale med vedkommende..."),className:"min-h-[120px] resize-none",...d})}),e.jsx(ns,{children:r("customScenario.fields.situation.help","Jo mer kontekst du gir, desto mer realistisk blir samtalen")}),e.jsx(Ve,{})]})})]})]}),e.jsxs(se,{children:[e.jsxs(xe,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-lg",children:[e.jsx(fn,{className:"h-5 w-5 text-primary"}),r("customScenario.character.title","Hvem skal du snakke med?")]}),e.jsx(wt,{children:r("customScenario.character.description","Beskriv personen du skal ha samtalen med")})]}),e.jsxs(re,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx($e,{control:f.control,name:"characterName",render:({field:d})=>e.jsxs(Me,{children:[e.jsxs(De,{children:[r("customScenario.fields.name.label","Navn")," *"]}),e.jsx(Re,{children:e.jsx(ut,{placeholder:r("customScenario.fields.name.placeholder","F.eks. Erik"),...d})}),e.jsx(Ve,{})]})}),e.jsx($e,{control:f.control,name:"characterRole",render:({field:d})=>e.jsxs(Me,{children:[e.jsxs(De,{children:[r("customScenario.fields.role.label","Rolle/stilling")," *"]}),e.jsx(Re,{children:e.jsx(ut,{placeholder:r("customScenario.fields.role.placeholder","F.eks. Seniorutvikler, Teamleder"),...d})}),e.jsx(Ve,{})]})})]}),e.jsx($e,{control:f.control,name:"characterAttitude",render:({field:d})=>e.jsxs(Me,{children:[e.jsxs(De,{children:[r("customScenario.fields.attitude.label","Personens holdning")," *"]}),e.jsxs(ar,{onValueChange:d.onChange,defaultValue:d.value,children:[e.jsx(Re,{children:e.jsx(nr,{children:e.jsx(ir,{placeholder:r("customScenario.fields.attitude.placeholder","Velg holdning")})})}),e.jsx(or,{children:l.map(y=>e.jsx(lr,{value:y.value,children:y.label},y.value))})]}),d.value&&e.jsx(ns,{children:l.find(y=>y.value===d.value)?.description}),e.jsx(Ve,{})]})})]})]}),e.jsxs(se,{children:[e.jsxs(xe,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Xe,{className:"h-5 w-5 text-primary"}),r("customScenario.goalsSection.title","Hva ønsker du å oppnå?")]}),e.jsx(wt,{children:r("customScenario.goalsSection.description","Velg ett eller flere mål for samtalen")})]}),e.jsxs(re,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:o.map(d=>{const y=h.includes(d.value);return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>p(d.value),onKeyDown:w=>{(w.key===" "||w.key==="Enter")&&(w.preventDefault(),p(d.value))},className:F("flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all",y?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-muted/50"),children:[e.jsx("div",{className:F("flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border transition-colors",y?"border-primary bg-primary text-primary-foreground":"border-primary"),children:y&&e.jsx(cr,{className:"h-3 w-3"})}),e.jsx("span",{className:F("text-sm font-medium",y?"text-primary":"text-foreground"),children:d.label})]},d.value)})}),j&&e.jsx("p",{className:"text-sm font-medium text-destructive",children:j}),e.jsx($e,{control:f.control,name:"customGoal",render:({field:d})=>e.jsxs(Me,{children:[e.jsx(De,{children:r("customScenario.fields.customGoal.label","Annet mål (valgfritt)")}),e.jsx(Re,{children:e.jsx(ut,{placeholder:r("customScenario.fields.customGoal.placeholder","Beskriv et annet mål du har med samtalen"),...d})}),e.jsx(Ve,{})]})})]})]}),e.jsxs(se,{children:[e.jsxs(xe,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ht,{className:"h-5 w-5 text-primary"}),r("customScenario.context.title","Ekstra kontekst"),e.jsx(Y,{variant:"secondary",className:"ml-2",children:r("customScenario.context.optional","Valgfritt")})]}
48),e.jsx(wt,{children:r("customScenario.context.description","Legg til mer kontekst for en enda mer realistisk samtale")})]}),e.jsx(re,{className:"space-y-4",children:e.jsx($e,{control:f.control,name:"background",render:({field:d})=>e.jsxs(Me,{children:[e.jsx(De,{children:r("customScenario.fields.background.label","Bakgrunnsinformasjon")}),e.jsx(Re,{children:e.jsx(gt,{placeholder:r("customScenario.fields.background.placeholder","F.eks. Dere har jobbet sammen i 2 år. Vedkommende har vanligvis vært en pålitelig medarbeider, men har hatt noen personlige utfordringer den siste tiden..."),className:"min-h-[80px] resize-none",...d})}),e.jsx(Ve,{})]})})})]}),e.jsxs("div",{className:"flex justify-end gap-4",children:[e.jsx(L,{type:"button",variant:"outline",onClick:s,children:r("common.cancel","Avbryt")}),e.jsx(L,{type:"submit",disabled:n,className:"gap-2",children:n?e.jsx(e.Fragment,{children:r("customScenario.submit.loading","Forbereder...")}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4"}),r("customScenario.submit.start","Start scenario")]})})]})]})})]})}function ji({matches:t,query:s,onPick:n}){const{t:r}=q();return t.length===0?null:e.jsxs("div",{"aria-live":"polite",className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:r("scenarios.finder.resultsTitle","Nærmest det du beskrev")}),e.jsx("ul",{className:"space-y-2 list-none",children:t.map(({scenario:m,matchedOn:l})=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>n(m.id,s),className:"group flex w-full items-center gap-3 rounded-lg border bg-background px-3 py-2.5 text-left transition-colors hover:border-primary-light/50 hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:m.title}),l.length>0&&e.jsxs("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:[r("scenarios.finder.becauseOf","Fordi du skrev")," ",l.slice(0,3).map(o=>`«${o}»`).join(", ")]})]}),e.jsx(ft,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]})},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("scenarios.finder.contextNote","Det du skrev følger med inn i samtalen, så motparten kjenner situasjonen din.")})]})}function yi(t=window.location.href){try{const s=performance.getEntriesByType("navigation")[0];return s?.type!=="reload"?!1:Gs(s.name)===Gs(t)}catch{return!1}}function Gs(t){const s=t.indexOf("#");return s===-1?t:t.slice(0,s)}const Wt=["kontakt_relasjon","rammesetting","utforsking","tilrettelegging_oppfolging"];function bi(t){return t.toLowerCase().normalize("NFKD").replace(/[^\p{Letter}\p{Number}\s]/gu," ").replace(/\s+/g," ").trim().split(" ").slice(0,8).join(" ")}function qs(t,s){if(t.length<2)return[];const n=new Map;for(const r of t){if(!r.ai_feedback)continue;let m;try{m=JSON.parse(r.ai_feedback)}catch{continue}const l=m[s]??[],o=new Set;for(const f of l){if(typeof f!="string"||!f.trim())continue;const h=bi(f);if(!h||o.has(h))continue;o.add(h);const g=n.get(h);g?g.count+=1:n.set(h,{text:f.trim(),count:1})}}return Array.from(n.values()).filter(r=>r.count>=2).sort((r,m)=>m.count-r.count).slice(0,3).map(r=>({text:r.text,count:r.count,windowSize:t.length}))}function ki(t,s){if(s.length===0)return null;const n=t.slice(-5),r=p=>[...p].sort((u,d)=>(u.level??99)-(d.level??99));if(n.length<2)return r(s)[0]??null;const m={kontakt_relasjon:0,rammesetting:0,utforsking:0,tilrettelegging_oppfolging:0},l={kontakt_relasjon:0,rammesetting:0,utforsking:0,tilrettelegging_oppfolging:0};for(const p of n)for(const u of Wt){const d=p.scores[u];d!==null&&(m[u]+=d,l[u]+=1)}const o=Wt.filter(p=>l[p]>0).map(p=>[p,m[p]/l[p]]);if(o.length===0)return r(s)[0]??null;const h=o.sort((p,u)=>p[1]-u[1])[0]?.[0];if(!h)return r(s)[0]??null;const j={kontakt_relasjon:[2,3],rammesetting:[1,2],utforsking:[3,4],tilrettelegging_oppfolging:[4,5]}[h],a=s.filter(p=>p.level!==null&&j.includes(p.level));return a.length>0?r(a)[0]??null:r(s)[0]??null}function Ni(){const{user:t}=Pe();return xt({queryKey:["sick-leave-progression",t?.id],enabled:!!t?.id,staleTime:300*1e3,gcTime:600*1e3,refetchOnWindowFocus:!1,queryFn:async()=>{const s={attempts:[],variants:[],notYetTrained:[],hasAnyCompletedAttempt:!1,recurringStrengths:[],recurringPitfalls:[],suggestedNext:null};if(!t?.id)return s;const{data:n}=await G.from("conversation_types").select("id").eq("slug","sykmeldt-oppfolging").maybeSingle();if(!n?.id)return s;const[r,m]=await Promise.all([G.from("scenarios").select("id, title, persona_code, level, illness_type_code, difficulty, estimated_minutes").eq("conversation_type_id",n.id).eq("is_active",!0).eq("is_published",!0),G.from("scenario_attempts").select("*").eq("user_id",t.id).eq("status","completed").order("completed_at",{ascending:!0})]),l=r.data;await Zr(m.data||[],{encrypted_ai_feedback:"ai_feedback"});const o=l??[],f=new Map(o.map(P=>[P.id,P]));if(o.length===0)return s;const h=new Set(o.map(P=>P.id)),g=(m.data??[]).filter(P=>h.has(P.scenario_id)),j=new Set(g.map(P=>P.scenario_id));let a=[];if(g.length>0){const{data:P}=await G.from("scenario_attempt_dimension_scores").select("attempt_id, dimension, score").in("attempt_id",g.map(K=>K.id));a=P??[]}const p=new Map;for(const P of g)p.set(P.id,Wt.reduce((K,_)=>(K[_]=null,K),{}));for(const P of a){const K=p.get(P.attempt_id);K&&Wt.includes(P.dimension)&&(K[P.dimension]=P.score)}const u=g.filter(P=>!!P.completed_at).map(P=>{const K=f.get(P.scenario_id);return{attempt_id:P.id,scenario_id:P.scenario_id,scenario_title:K?.title??"(slettet scenario)",persona_code:K?.persona_code??null,level:K?.level??null,completed_at:P.completed_at,scores:p.get(P.id)??{kontakt_relasjon:null,rammesetting:null,utforsking:null,tilrettelegging_oppfolging:null}}}),d=o.map(P=>({...P,attempted:j.has(P.id)})),y=d.filter(P=>!P.attempted),w=g.slice(-5),z=qs(w,"strengths"),I=qs(w,"improvements"),Te=ki(u,y);return{attempts:u,variants:d,notYetTrained:y,hasAnyCompletedAttempt:u.length>0,recurringStrengths:z,recurringPitfalls:I,suggestedNext:Te}}})}
48const wi=["kontakt_relasjon","rammesetting","utforsking","tilrettelegging_oppfolging"],_i={kontakt_relasjon:"#60a5fa",rammesetting:"#a78bfa",utforsking:"#4ade80",tilrettelegging_oppfolging:"#fbbf24"};function Si(t){return t.map((s,n)=>({name:`#${n+1}`,fullLabel:new Date(s.completed_at).toLocaleDateString(vn(),{day:"2-digit",month:"short"}),kontakt_relasjon:s.scores.kontakt_relasjon,rammesetting:s.scores.rammesetting,utforsking:s.scores.utforsking,tilrettelegging_oppfolging:s.scores.tilrettelegging_oppfolging}))}function Ci(){const{t}=q(),{data:s,isLoading:n}=Ni(),[r,m]=i.useState("5"),[l,o]=i.useState(!1),f=i.useMemo(()=>{if(!s)return[];const u=parseInt(r,10);return s.attempts.slice(-u)},[s,r]),h=i.useMemo(()=>Si(f),[f]),g=i.useMemo(()=>{const u=s?.notYetTrained??[],d=s?.suggestedNext;return[...u].filter(y=>!d||y.id!==d.id).sort((y,w)=>{const z=(y.level??0)-(w.level??0);return z!==0?z:(y.persona_code??"").localeCompare(w.persona_code??"","nb")})},[s]);if(n||!s||!s.hasAnyCompletedAttempt)return null;const{recurringStrengths:j,recurringPitfalls:a,suggestedNext:p}=s;return e.jsxs(se,{children:[e.jsx(xe,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>o(u=>!u),className:"flex items-center gap-2 text-left hover:opacity-80 transition-opacity","aria-expanded":l,children:[e.jsx(rs,{className:"w-5 h-5 text-primary-light"}),e.jsx(he,{className:"text-lg",children:t("sickLeaveProgression.title","Din utvikling på sykmeldt-oppfølging")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx(hn,{value:r,onValueChange:u=>m(u),children:e.jsxs(pn,{children:[e.jsx(Xt,{value:"5",children:t("sickLeaveProgression.window.last","Siste {{n}}",{n:5})}),e.jsx(Xt,{value:"10",children:t("sickLeaveProgression.window.last","Siste {{n}}",{n:10})}),e.jsx(Xt,{value:"20",children:t("sickLeaveProgression.window.last","Siste {{n}}",{n:20})})]})}),e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>o(u=>!u),className:"gap-1","aria-expanded":l,children:l?e.jsxs(e.Fragment,{children:[e.jsx(jn,{className:"w-4 h-4"}),t("sickLeaveProgression.hide","Skjul")]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"w-4 h-4"}),t("sickLeaveProgression.showProgress","Vis utvikling")]})})]})]})}),e.jsxs(re,{className:"space-y-4",children:[!l&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(me,{className:"w-4 h-4 text-green-500"}),t("sickLeaveProgression.summary.completed",{count:s.attempts.length,defaultValue_one:"{{count}} fullført",defaultValue_other:"{{count}} fullførte"})]}),j.length>0&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(me,{className:"w-4 h-4 text-green-500"}),t("sickLeaveProgression.summary.strengths",{count:j.length,defaultValue_one:"{{count}} styrke",defaultValue_other:"{{count}} styrker"})]}),a.length>0&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_t,{className:"w-4 h-4 text-amber-500"}),t("sickLeaveProgression.summary.pitfalls",{count:a.length,defaultValue_one:"{{count}} fallgruve",defaultValue_other:"{{count}} fallgruver"})]}),g.length>0&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ls,{className:"w-4 h-4"}),t("sickLeaveProgression.summary.notTrained","{{count}} ikke trent",{count:g.length})]})]}),p&&e.jsxs("div",{className:"border border-primary-light/30 bg-primary-light/5 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(Xe,{className:"w-4 h-4 text-primary-light"}),e.jsx("h4",{className:"text-sm font-medium",children:t("sickLeaveProgression.recommendedNext","Anbefalt neste øvelse")})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:[t("sickLeaveProgression.levelLabel","Nivå {{level}}",{level:p.level??"?"}),p.persona_code?` · ${p.persona_code}`:""]}),e.jsx("span",{className:"text-sm",children:p.title})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-64 -mx-2",children:e.jsx(yn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:h,margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx(kn,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.08)"}),e.jsx(Nn,{dataKey:"name",tick:{fontSize:11,fill:"currentColor"}}),e.jsx(wn,{domain:[0,100],tick:{fontSize:11,fill:"currentColor"},width:32}),e.jsx(_n,{contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12},labelFormatter:(u,d)=>{const y=d?.[0]?.payload;return y?.fullLabel?`${u} · ${y.fullLabel}`:String(u)},formatter:(u,d)=>{const y=Cs[d]??String(d);return[u==null?t("sickLeaveProgression.notRecorded","ikke registrert"):`${u}/100`,y]}}),e.jsx(Sn,{wrapperStyle:{fontSize:11},formatter:u=>Cs[u]??u}),wi.map(u=>e.jsx(Cn,{type:"monotone",dataKey:u,stroke:_i[u],strokeWidth:2,dot:{r:3},activeDot:{r:5},connectNulls:!0},u))]})})}),(j.length>0||a.length>0)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t",children:[j.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(me,{className:"w-4 h-4 text-green-500"}),e.jsx("h4",{className:"text-sm font-medium",children:t("sickLeaveProgression.recurringStrengths","Gjentatte styrker")})]}),e.jsx("ul",{className:"space-y-2",children:j.map((u,d)=>e.jsxs("li",{className:"text-sm flex items-start gap-2",children:[e.jsx(Y,{variant:"outline",className:"shrink-0 text-xs border-green-300 text-green-700",children:t("sickLeaveProgression.countOf","{{count}}× av {{total}}",{count:u.count,total:u.windowSize})}),e.jsx("span",{className:"text-muted-foreground leading-snug",children:u.text})]},d))})]}),a.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(_t,{className:"w-4 h-4 text-amber-500"}),e.jsx("h4",{className:"text-sm font-medium",children:t("sickLeaveProgression.recurringPitfalls","Gjentatte fallgruver")})]}),e.jsx("ul",{className:"space-y-2",children:a.map((u,d)=>e.jsxs("li",{className:"text-sm flex items-start gap-2",children:[e.jsx(Y,{variant:"outline",className:"shrink-0 text-xs border-amber-300 text-amber-700",children:t("sickLeaveProgression.countOf","{{count}}× av {{total}}",{count:u.count,total:u.windowSize})}),e.jsx("span",{className:"text-muted-foreground leading-snug",children:u.text})]},d))})]})]}),g.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ls,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("h4",{className:"text-sm font-medium",children:t("sickLeaveProgression.notYetTrained","Ikke trent på enda ({{count}})",{count:g.length})})]}),e.jsx("ul",{className:"space-y-2",children:g.map(u=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:[t("sickLeaveProgression.levelLabel","Nivå {{level}}",{level:u.level??"?"}),u.persona_code?` · ${u.persona_code}`:""]}),e.jsx("span",{className:"text-foreground truncate",children:u.title})]},u.id))})]})]})]})]})}const zs={hidden:{opacity:0}
48,visible:{opacity:1,transition:{duration:.15}}},Se={hidden:{opacity:0,y:8},visible:{opacity:1,y:0,transition:{duration:.2,ease:[0,0,.2,1]}}},Pi=new Set(["recommended","bookmarks","sales","nedbemanning","egetforhold"]);function Vl(){const{isFreeTier:t,freeScenarioId:s,conversationsUsed:n,conversationsLimit:r,freeTierSpent:m}=Js(),l=Ks(),o=St(),f=x=>ta(x,{isFreeTier:t,freeScenarioId:s,freeTierSpent:m}),h=f(Ut),{t:g}=q(),[j,a]=Mr(),p=i.useRef(!1),{recommendedScenarios:u,bookmarkedScenarios:d,filteredScenarios:y,scenarios:w,mandatoryScenarios:z,mandatoryProgress:I,salesEnabled:Te,isLoading:P,error:K,searchQuery:_,setBehaviorCategoryId:V,setSearchQuery:oe,toggleBookmark:ce,startScenario:ae,updateAttempt:Ae,getScenario:ue}=Jr(),{startCustomScenario:We,isLoading:Be}=Dn(),{conversationTypes:W}=Qs(),[J,Z]=i.useState(null),[be,B]=i.useState(null),[ee,C]=i.useState(0),[pe,O]=i.useState(""),H=_.trim().includes(" "),te=i.useMemo(()=>H?xn(_,w,3):[],[H,_,w]),[M,ne]=i.useState(null),[Ze,Pt]=i.useState("relevance"),Ge=i.useMemo(()=>!M||M==="recommended"||M==="bookmarks"?!1:W.find(x=>x.id===M)?.slug==="sykmeldt-oppfolging",[M,W]),qt=i.useMemo(()=>w.some(x=>x.track_key==="nedbemanning"),[w]),et=i.useMemo(()=>w.some(x=>x.track_key==="egetforhold"),[w]),[Tt,ve]=i.useState(!1),[le,pt]=i.useState(null),{data:qe,isLoading:vt,isError:tt,refetch:At}=Qr(le?null:J),Lt=i.useMemo(()=>{if(le)return le;if(!J)return null;const x=ue(J);return!x||!qe||qe.id!==J?null:{...qe,...x}},[le,J,ue,qe]),Et=i.useRef(!1);i.useEffect(()=>{if(Et.current)return;const x=j.get("q");x&&(Et.current=!0,oe(x))},[j,oe]);const jt=i.useRef(!1);i.useEffect(()=>{if(jt.current)return;jt.current=!0;const x=j.get("filter"),T=j.get("sort");x&&(ne(x),Pi.has(x)||V(x)),(T==="alphabetical"||T==="relevance"||T==="category")&&Pt(T)},[j,V]),i.useEffect(()=>{if(p.current||P)return;const x=j.get("start");if(!x)return;const T=ue(x);T?(p.current=!0,T.code?a({ovelse:T.code},{replace:!0}):(a({},{replace:!0}),Z(x),C(D=>D+1))):a({},{replace:!0})},[j,P,ue,ae,a]);const st=i.useRef(j.get("ovelse")!==null&&j.get("forstegang")!=="1"&&yi());i.useEffect(()=>{if(le)return;const x=j.get("ovelse");if(!x){J&&(Z(null),B(null),rt(1),Ne(null),X(null));return}if(P)return;const T=Ps(x),D=w.find(N=>Ps(N.code)===T);if(!D){const N=new URLSearchParams(j);N.delete("ovelse"),a(N,{replace:!0});return}D.id!==J&&(Z(D.id),B(null),C(N=>N+1),st.current&&(st.current=!1,fe.info(g("scenarios.restoredFromUrl","Samtalen ble ikke lagret. Du starter fra briefen igjen."))))},[j,a,w,P,J,le,g]);const{user:ke}=Pe(),Le=i.useRef(!1);i.useEffect(()=>{Le.current||!ke?.id||!J||j.get("forstegang")==="1"&&(Le.current=!0,Va(ke.id))},[ke?.id,J,j]);const[A,rt]=i.useState(1),[at,Ne]=i.useState(null),[zt,X]=i.useState(null),we=!P,_e=i.useMemo(()=>{let x=y;if(M==="recommended")x=u;else if(M==="bookmarks")x=d;else if(M==="sales"){const D=new Set(W.filter(N=>N.scenario_group==="sales").map(N=>N.id));x=y.filter(N=>
48N.conversation_type_id&&D.has(N.conversation_type_id)||N.category==="sales")}else if(M==="nedbemanning"){const D=new Set(W.filter(N=>N.scenario_group==="nedbemanning").map(N=>N.id));x=y.filter(N=>N.conversation_type_id&&D.has(N.conversation_type_id)||N.category==="nedbemanning")}else if(M==="egetforhold"){const D=new Set(W.filter(N=>N.scenario_group==="egetforhold").map(N=>N.id));x=y.filter(N=>N.conversation_type_id&&D.has(N.conversation_type_id)||N.category==="egetforhold")}if(M==="sales"||M==="nedbemanning"||M==="egetforhold"||Ge){const D=new Map(W.map(Ee=>[Ee.id,Ee.sort_order??999])),N={beginner:0,intermediate:1,advanced:2};return[...x].sort((Ee,bt)=>{const it=D.get(Ee.conversation_type_id??"")??999,ot=D.get(bt.conversation_type_id??"")??999;if(it!==ot)return it-ot;const kt=N[Ee.difficulty??""]??99,lt=N[bt.difficulty??""]??99;return kt!==lt?kt-lt:Ee.title.localeCompare(bt.title,"nb")})}return[...x].sort((D,N)=>{switch(Ze){case"alphabetical":return D.title.localeCompare(N.title,"nb");case"relevance":return D.title.localeCompare(N.title,"nb");case"category":default:return(D.category||"").localeCompare(N.category||"","nb")}})},[y,u,d,M,Ze,W,Ge]),de=(x,T)=>{T?(ne(x),V(null)):(ne(x),V(x));const D=new URLSearchParams(j);x?D.set("filter",x):D.delete("filter"),a(D,{replace:!0})},yt=x=>{Pt(x);const T=new URLSearchParams(j);x==="relevance"?T.delete("sort"):T.set("sort",x),a(T,{replace:!0})},ze=(x,T="")=>{Z(x),B(null),O(T),C(N=>N+1);const D=ue(x)?.code;if(D){const N=new URLSearchParams(j);N.set("ovelse",D),N.delete("start"),a(N)}},It=()=>{if(l.invalidateQueries({queryKey:["free-tier-status"]}),l.invalidateQueries({queryKey:["scenario-access"]}),Z(null),B(null),pt(null),rt(1),Ne(null),X(null),j.get("ovelse")){const x=new URLSearchParams(j);x.delete("ovelse"),a(x,{replace:!0})}},nt=async(x,T)=>{J&&(Ne(x),X(T||null),B(null),C(D=>D+1),rt(D=>D+1))},Ke=async x=>{const T=await We(x);T&&(pt(T.scenario),B(T.attemptId),Z(T.scenario.id),C(D=>D+1),ve(!1))},Kt=x=>{switch(x){case"category":return g("scenarios.sort.byCategory");case"alphabetical":return g("scenarios.sort.alphabetical");case"relevance":return g("scenarios.sort.byRelevance");default:return g("scenarios.sort.byCategory")}};if(Tt)return e.jsx(vi,{onSubmit:Ke,onCancel:()=>ve(!1),isLoading:Be});if(J){if(Lt)return e.jsx(di,{scenario:Lt,attemptId:be,initialUserContext:pe,createAttempt:async x=>(await ae(J,x))?.id??null,onClose:It,onUpdateAttempt:Ae,isCustom:!!le,attemptNumber:A,previousFeedback:at,previousConversation:zt,onRetryNow:nt},ee);if(!le&&vt)return e.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:e.jsx(Br,{size:"lg"})});if(!le&&tt)return e.jsxs(ie.div,{className:"flex flex-col items-center justify-center h-[400px] text-center gap-4",initial:{opacity:0}
48,animate:{opacity:1},children:[e.jsx("p",{className:"text-muted-foreground",children:g("scenarios.detailLoadError","Kunne ikke laste scenarioet")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{onClick:()=>void At(),children:g("common.retry")}),e.jsx(L,{variant:"outline",onClick:It,children:g("scenarios.preview.toLibrary","Til treningsbiblioteket")})]})]})}return K?e.jsxs(ie.div,{className:"flex flex-col items-center justify-center h-[400px] text-center",initial:{opacity:0},animate:{opacity:1},children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:K}),e.jsx(L,{onClick:()=>window.location.reload(),children:g("common.retry")})]}):e.jsx("div",{className:"h-full overflow-auto overflow-x-hidden p-0 sm:p-2 lg:p-6 min-w-0 w-full",children:e.jsxs(ie.div,{className:"space-y-6 sm:space-y-8 min-w-0",initial:"hidden",animate:"visible",variants:zs,children:[e.jsxs(ie.div,{variants:Se,className:"space-y-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:g("scenarios.title")}),e.jsx("p",{className:"text-muted-foreground mt-1",children:g("scenarios.subtitle")}),e.jsx(Hs,{to:"/scenarios/history",className:"mt-2 inline-flex items-center text-sm text-primary-light hover:text-primary transition-colors",children:g("scenarios.history.linkLabel","Min historikk →")})]}),t&&e.jsx(ea,{used:n,limit:r,claimedTitle:s?w.find(x=>x.id===s)?.title??null:null}),e.jsxs("div",{className:"flex items-center gap-2 w-full min-w-0",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Pn,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(ut,{type:"text",placeholder:g("scenarios.searchPlaceholder","Søk — eller beskriv samtalen du gruer deg til"),value:_,onChange:x=>oe(x.target.value),className:"h-12 pl-11 pr-10 text-base bg-background border-border/50 focus:border-primary"}),_&&e.jsx("button",{onClick:()=>oe(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors",children:e.jsx(Gr,{className:"h-4 w-4"})})]}),e.jsxs(zr,{children:[e.jsx(Kr,{asChild:!0,children:e.jsx(L,{"aria-label":g("a11y.changeSort","Endre sortering"),variant:"outline",size:"icon",className:"shrink-0",children:e.jsx(Tn,{className:"h-4 w-4"})})}),e.jsx(Hr,{align:"end",children:["relevance","category","alphabetical"].map(x=>e.jsx($r,{onClick:()=>yt(x),className:F(Ze===x&&"bg-accent"),children:Kt(x)},x))})]})]}),e.jsx(ji,{matches:te,query:_.trim(),onPick:ze}),e.jsx(aa,{selectedId:M,onSelect:(x,T)=>de(x,T),showAll:!0,showSales:Te,showNedbemanning:qt,showEgetforhold:et,showRecommended:!0,showBookmarks:!0,bookmarkCount:d.length,customAllButton:e.jsxs("button",{onClick:()=>h?o("/billing"):ve(!0),className:F("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-all duration-200","border hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-[hsl(var(--sky-500))]/30",h?"bg-muted text-muted-foreground border-border":"bg-foreground text-background border-transparent hover:bg-foreground
48/90 shadow-sm"),children:[h?e.jsx($s,{className:"h-4 w-4 shrink-0"}):e.jsx(mr,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:h?g("scenarios.card.unlock","Lås opp"):g("scenarios.createCustom")})]})})]}),Ge&&e.jsx(ie.div,{variants:Se,children:e.jsx(Ci,{})}),we&&z.length>0&&e.jsxs(ie.div,{variants:Se,className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("h2",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(An,{className:"w-4 h-4 text-primary-light"}),g("scenarios.mandatory.title","Påkrevd trening")]}),e.jsx("span",{className:"text-sm text-muted-foreground tabular-nums",children:g("scenarios.mandatory.progress","{{done}} av {{total}} fullført",{done:I.done,total:I.total})})]}),e.jsx("div",{className:"grid gap-4 md:gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 min-w-0",children:z.map((x,T)=>e.jsx(ie.div,{variants:Se,custom:T,children:e.jsx(Ms,{scenario:x,onStart:ze,onToggleBookmark:ce,locked:f(x.id)})},`mandatory-${x.id}`))})]}),we&&_&&te.length===0&&e.jsxs(ie.p,{variants:Se,className:"text-sm text-muted-foreground",children:[_e.length," ",_e.length===1?g("scenarios.result"):g("scenarios.results"),_&&` ${g("scenarios.for")} "${_}"`]}),we&&!_&&w.length>0&&e.jsxs(ie.p,{variants:Se,className:"text-sm text-muted-foreground",children:[g("scenarios.library.countLine","{{total}} scenarios",{total:w.length})," ·"," ",e.jsx("span",{className:"text-success font-medium",children:g("scenarios.library.completedCount","{{count}} completed",{count:w.filter(x=>(x.completion_count??0)>0).length})})]}),M==="recommended"&&we&&e.jsx(ie.div,{variants:Se,className:"bg-primary/5 p-4 rounded-lg border border-primary/20",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ht,{className:"w-5 h-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:g("scenarios.recommended.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g("scenarios.recommended.description")})]})]})}),!we&&e.jsx("div",{className:"grid gap-4 md:gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3,4,5,6].map(x=>e.jsx(ie.div,{initial:{opacity:0}
48,animate:{opacity:1},transition:{delay:x*.1},children:e.jsx(qr,{className:"h-72 rounded-xl"})},x))}),we&&_e.length===0&&te.length===0&&e.jsxs(ie.div,{className:"text-center py-16",variants:Se,children:[e.jsx(ie.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:200,delay:.2},children:M==="bookmarks"?e.jsx(Zs,{className:"w-16 h-16 mx-auto text-muted-foreground/50 mb-6"}):M==="recommended"?e.jsx(ht,{className:"w-16 h-16 mx-auto text-muted-foreground/50 mb-6"}):e.jsx(Ct,{className:"w-16 h-16 mx-auto text-muted-foreground/50 mb-6"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:_?Ts(_)?g("scenarios.noCodeMatch","Fant ingen scenario med koden {{code}}",{code:_.trim().toUpperCase()}):g("scenarios.noSearchResults"):g(M==="bookmarks"?"scenarios.noBookmarks":M==="recommended"?"scenarios.noRecommendations":"scenarios.empty.title")}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto",children:_?Ts(_)?g("scenarios.noCodeMatchHint","Sjekk at koden er riktig, eller søk på tittel eller navnet på personen i samtalen."):g("scenarios.tryDifferentSearch"):g(M==="bookmarks"?"scenarios.bookmarksHint":M==="recommended"?"scenarios.recommendedHint":"scenarios.empty.description")}),_&&e.jsx(L,{variant:"outline",onClick:()=>oe(""),className:"mt-4",children:g("scenarios.clearSearch")})]}),we&&_e.length>0&&e.jsx(ie.div,{className:"grid gap-4 md:gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 min-w-0",variants:zs,initial:"hidden",animate:"visible",children:_e.map((x,T)=>e.jsx(ie.div,{variants:Se,custom:T,children:e.jsx(Ms,{scenario:x,onStart:ze,onToggleBookmark:ce,locked:f(x.id)})},x.id))})]})})}export{Vl 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.